Example usage for java.io File toURL

List of usage examples for java.io File toURL

Introduction

In this page you can find the example usage for java.io File toURL.

Prototype

@Deprecated
public URL toURL() throws MalformedURLException 

Source Link

Document

Converts this abstract pathname into a file: URL.

Usage

From source file:org.ecoinformatics.seek.R.RExpression.java

public synchronized void fire() throws IllegalActionException {
    String newline = System.getProperty("line.separator");

    super.fire();

    boolean graphicsOutputValue = ((BooleanToken) graphicsOutput.getToken()).booleanValue();

    boolean displayGraphicsOutputValue = ((BooleanToken) displayGraphicsOutput.getToken()).booleanValue();

    saveString = save_nosave.stringValue();
    // restoreString = restore_norestore.stringValue();

    String graphicsFormatString = graphicsFormat.stringValue();

    // following line insures that graphics is pdf if automatically
    // displayed//from w  w w. j  a  v  a 2  s. co  m
    // NOT going to automatically do this anymore. Do what the user asks.
    //if (displayGraphicsOutputValue)
    //   graphicsFormatString = "pdf";

    // force file format to 'pdf' is this is a Mac
    // NOT going to force PDF for Mac - not sure why this was in place (legacy?)
    //      String lcOSName = System.getProperty("os.name").toLowerCase();
    //      boolean MAC_OS_X = lcOSName.startsWith("mac os x");
    //      if (MAC_OS_X) {
    //         graphicsFormatString = "pdf";
    //      }

    String nxs = numXPixels.stringValue();
    try {
        (new Integer(nxs)).intValue();
    } catch (Exception w) {
        nxs = "480";
    }

    String nys = numYPixels.stringValue();
    try {
        (new Integer(nys)).intValue();
    } catch (Exception w1) {
        nys = "480";
    }

    String setCWD = "setwd('" + home + "')\n";
    graphicsOutputFile = _getUniqueFileName(graphicsFormatString);
    String graphicsDevice = "";

    if (graphicsOutputValue) {
        // Why not move this stuff up to the try statements for nxs and nys?
        // It looks like we're doing this twice. --Oliver
        int nxp = (new Integer(nxs)).intValue();
        double nxd = nxp / 72.0;
        int nyp = (new Integer(nys)).intValue();
        double nyd = nyp / 72.0;

        if (graphicsFormatString.equals("pdf")) {
            graphicsDevice = "pdf(file = '" + graphicsOutputFile + "'" + ", width = " + nxd + ", height = "
                    + nyd + ")";
        } else if (graphicsFormatString.equals("jpeg") || graphicsFormatString.equals("jpg")) {
            graphicsDevice = "jpeg(filename = '" + graphicsOutputFile + "'" + ", width = " + nxs + ", height = "
                    + nys + ")";
        } else if (graphicsFormatString.equals("png")) {
            graphicsDevice = "png(file = '" + graphicsOutputFile + "'" + ", width = " + nxs + ", height = "
                    + nys + ")";
        } else if (graphicsFormatString.equals("bmp")) {
            graphicsDevice = "bmp(filename = '" + graphicsOutputFile + "'" + ", width = " + nxs + ", height = "
                    + nys + ")";
        } else if (graphicsFormatString.equals("tiff") || graphicsFormatString.equals("tif")) {
            graphicsDevice = "tiff(filename = '" + graphicsOutputFile + "'" + ", width = " + nxs + ", height = "
                    + nys + ")";
        } else if (graphicsFormatString.equals("postscript") || graphicsFormatString.equals("ps")) {
            graphicsOutputFile = _getUniqueFileName("ps");
            graphicsDevice = "postscript(file = '" + graphicsOutputFile + "'" + ", width = " + nxd
                    + ", height = " + nyd + ")";
        } else if (graphicsFormatString.equals("eps")) {
            graphicsDevice = "setEPS()\n";
            graphicsDevice += "postscript(file = '" + graphicsOutputFile + "'" + ", width = " + nxd
                    + ", height = " + nyd + ")";
        } else if (graphicsFormatString.equals("win.metafile") || graphicsFormatString.equals("wmf")) {
            graphicsOutputFile = _getUniqueFileName("wmf");
            graphicsDevice = "win.metafile(filename = '" + graphicsOutputFile + "'" + ", width = " + nxd
                    + ", height = " + nyd + ")";
        } else if (graphicsFormatString.equals("svg")) {
            graphicsDevice = "svg(filename = '" + graphicsOutputFile + "'" + ", width = " + nxd + ", height = "
                    + nyd + ")";
        } else if (graphicsFormatString.equals("xfig") || graphicsFormatString.equals("fig")) {
            graphicsOutputFile = _getUniqueFileName("fig");
            graphicsDevice = "xfig(file = '" + graphicsOutputFile + "'" + ", width = " + nxd + ", height = "
                    + nyd + ")";
        } else if (graphicsFormatString.equals("ghostscript bitmap type pngalpha")) {
            graphicsDevice = "bitmap(file = '" + graphicsOutputFile + "', type = \"pngalpha\", width = " + nxd
                    + ", height = " + nyd + ")";
        } else if (graphicsFormatString.equals("ghostscript bitmap type png16m")) {
            graphicsDevice = "bitmap(file = '" + graphicsOutputFile + "', type = \"png16m\", width = " + nxd
                    + ", height = " + nyd + ")";
        } else if (graphicsFormatString.equals("ghostscript bitmap type png256")) {
            graphicsDevice = "bitmap(file = '" + graphicsOutputFile + "', type = \"png256\", width = " + nxd
                    + ", height = " + nyd + ")";
        }
    }
    List ipList = inputPortList();
    Iterator iter_i = ipList.iterator();
    opList = outputPortList();
    iter_o = opList.iterator();
    String RPortInfo = "";
    RPortInfo = setCWD + graphicsDevice + "\n";
    Token at;
    String temp1;
    while (iter_i.hasNext()) {
        TypedIOPort tiop = (TypedIOPort) iter_i.next();
        int multiPortSize = tiop.numberOfSources();
        List sourcePorts = tiop.sourcePortList();
        for (int i = 0; i < multiPortSize; i++) {
            try {
                if (tiop.hasToken(i)) {
                    String finalPortName = tiop.getName();
                    String sourcePortName = ((TypedIOPort) sourcePorts.get(i)).getName();
                    String tempPortName = tiop.getName();
                    String temp = tiop.getName();
                    Token token = tiop.get(i);
                    String token_type_string = token.getType().toString();
                    String token_class_name = token.getType().getTokenClass().getName();
                    // if this is a multiport, use the upstream source for
                    // the variable name
                    if (tiop.isMultiport()) {
                        temp = temp + i;
                        tempPortName = temp;
                    }
                    // log.debug("token_type_string - " +
                    // token_type_string);
                    // log.debug("token_class_name - " +
                    // token_class_name);
                    // check token type and convert to R appropriately
                    if (token_type_string.equals("string")) {
                        // check for special strings that indicate dataframe
                        // file reference
                        at = (Token) token;
                        temp1 = at.toString();
                        temp1 = temp1.substring(1, temp1.length() - 1); // remove
                        // quotes
                        if (temp1.startsWith("_dataframe_:")) {
                            // assume that the string for a dataframe file
                            // reference is of the form
                            // '_dataframe_:"+<filename>
                            temp1 = temp1.substring(12); // should be
                            // filename
                            // temp = "`" + temp + "` <- " +
                            // "read.table(file='"+temp1+"')";
                            // RPortInfo = RPortInfo + temp + "\n";
                            // use binary version that was serialized
                            RPortInfo = RPortInfo + "conn <- file('" + temp1 + "', 'rb');\n`" + temp
                                    + "` <- unserialize(conn);\n" + "close(conn);\n";

                            // remove the transfer file when we are done
                            // consuming it
                            // this is problematic when dataframes are
                            // output to multiple sinks!
                            // String removeCommand = "file.remove('" +
                            // temp1 + "')";
                            // RPortInfo = RPortInfo + removeCommand + "\n";
                            continue; // stop for this token and go to the
                                      // next
                        } else if (temp1.startsWith("_object_:")) {
                            // assume that the string for an object file
                            // reference is of the form
                            // '_object_:"+<filename>
                            temp1 = temp1.substring(9); // should be
                            // filename
                            // use binary version that was serialized
                            RPortInfo = RPortInfo + "conn <- file('" + temp1 + "', 'rb');\n`" + temp
                                    + "` <- unserialize(conn);\n" + "close(conn);\n";
                            // remove the transfer file when we are done
                            // consuming it
                            // this is problematic when objects are output
                            // to multiple sinks!
                            // String removeCommand = "file.remove('" +
                            // temp1 + "')";
                            // RPortInfo = RPortInfo + removeCommand + "\n";
                            continue; // stop for this token and go to the
                                      // next
                        }
                    }
                    if (token instanceof RecordToken) {
                        String Rcommands = _recordToDataFrame((RecordToken) token, temp);
                        Rcommands = _breakIntoLines(Rcommands);
                        RPortInfo = RPortInfo + Rcommands + "\n";
                    }

                    // convert Kepler matrices to R matrices
                    else if ((token_class_name.indexOf("IntMatrixToken") > -1)
                            || (token_class_name.indexOf("DoubleMatrixToken") > -1)
                            || (token_class_name.indexOf("BooleanMatrixToken") > -1)) {
                        int rows = ((MatrixToken) token).getRowCount();
                        int cols = ((MatrixToken) token).getColumnCount();
                        temp1 = token.toString();
                        temp1 = temp1.replace('\\', '/');
                        temp1 = temp1.replace('[', '(');
                        temp1 = temp1.replace(']', ')');
                        temp1 = temp1.replace(';', ',');
                        temp1 = temp1.replace('"', '\'');
                        // assume that the token's string value might be
                        // 'nil' for a missing value
                        temp1 = temp1.replaceAll("nil", "NA");
                        // TO DO:if string is long, should create a temp
                        // file for passing array data
                        temp = "`" + temp + "` <- matrix(c" + temp1 + ", nrow=" + rows + ",ncol=" + cols + ")";
                        temp = _breakIntoLines(temp);
                        RPortInfo = RPortInfo + temp + "\n";
                    } else if ((token_type_string.equals("double")) || (token_type_string.equals("int"))
                            || (token_type_string.equals("string"))) {

                        at = (Token) token;
                        temp1 = at.toString();
                        // we need to check here if we are passing a string
                        // like '/t' (tab)
                        // Note that quotes are returned around string
                        // tokens
                        // The string "/t" is particularly meaningful when
                        // passed as a seperator
                        // for R expressions -- DFH April 19
                        // Note that previous versions of PTII returned
                        // slightly different format
                        // strings, so this was not necessary.
                        if (!temp1.equals("\"\\t\"")) {
                            temp1 = temp1.replace('\\', '/');
                            // assume that the token's string value might be
                            // 'nil' for a missing value
                            temp1 = temp1.replaceAll("nil", "NA");
                        }
                        temp = "`" + temp + "` <- " + temp1;
                        RPortInfo = RPortInfo + temp + "\n";
                    } else if ((token_type_string.equals("boolean"))) {
                        at = (Token) token;
                        temp1 = at.toString();
                        // ensure uppercase for boolean
                        temp1 = temp1.toUpperCase();
                        temp = "`" + temp + "` <- " + temp1;
                        RPortInfo = RPortInfo + temp + "\n";
                    } else if ((token_type_string.equals("float"))) {
                        FloatToken ft = (FloatToken) token;
                        DoubleToken dt = new DoubleToken(ft.doubleValue());
                        at = (Token) token;
                        temp1 = dt.toString();
                        // we need to check here if we are passing a string
                        // like '/t' (tab)
                        // Note that quotes are returned around string
                        // tokens
                        // The string "/t" is particularly meaningful when
                        // passed as a seperator
                        // for R expressions -- DFH April 19
                        // Note that previous versions of PTII returned
                        // slightly different format
                        // strings, so this was not necessary.
                        if (!temp1.equals("\"\\t\"")) {
                            temp1 = temp1.replace('\\', '/');
                            // assume that the token's string value might be
                            // 'nil' for a missing value
                            temp1 = temp1.replaceAll("nil", "NA");
                        }
                        temp = "`" + temp + "` <- " + temp1;
                        RPortInfo = RPortInfo + temp + "\n";
                    } else if ((token_type_string.equals("{double}")) || (token_type_string.equals("{int}"))
                            || (token_type_string.startsWith("arrayType(double"))
                            || (token_type_string.startsWith("arrayType(int"))
                            || (token_type_string.startsWith("arrayType(niltype"))
                            || (token_type_string.startsWith("arrayType(arrayType(double"))
                            || (token_type_string.startsWith("arrayType(arrayType(int"))) {
                        // token is an arrayToken !!!
                        at = (Token) token;
                        temp1 = at.toString();
                        temp1 = temp1.replace('\\', '/');
                        temp1 = temp1.replaceFirst("\\{", "(");
                        temp1 = temp1.replaceAll("\\{", "c(");
                        temp1 = temp1.replace('}', ')');
                        temp1 = temp1.replace('"', '\'');
                        // assume that the token's string value might be
                        // 'nil' for a missing value
                        temp1 = temp1.replaceAll("nil", "NA");
                        // if string is long, create a temp file for passing
                        // array data
                        if (temp1.length() > maxCommandLineLength
                                && (!token_type_string.startsWith("arrayType(arrayType(double"))
                                && (!token_type_string.startsWith("arrayType(arrayType(int"))) {
                            temp1 = temp1.replace('(', ' ');
                            temp1 = temp1.replace(')', ' ');
                            String filename = _writeDataFile(temp1);
                            temp = "`" + temp + "` <- scan('" + filename + "', sep=',')";
                            temp = temp + "\n" + "file.remove('" + filename + "')";
                            RPortInfo = RPortInfo + temp + "\n";
                        } else { // otherwise use the modified string
                            if (token_type_string.startsWith("arrayType(arrayType(int")
                                    || token_type_string.startsWith("arrayType(arrayType(double")) {
                                temp = "`" + temp + "` <- list" + temp1;
                            } else {
                                temp = "`" + temp + "` <- c" + temp1;
                            }
                            temp = _breakIntoLines(temp);
                            RPortInfo = RPortInfo + temp + "\n";
                        }
                    } else if ((token_type_string.equals("{float}"))
                            || (token_type_string.startsWith("arrayType(float"))
                            || token_type_string.startsWith("arrayType(arrayType(float")) {
                        // token is an arrayToken !!!
                        ArrayToken arrtok = (ArrayToken) token;
                        StringBuffer buffer = new StringBuffer("{");
                        for (int j = 0; j < arrtok.length(); j++) {
                            FloatToken ft = (FloatToken) arrtok.getElement(j);
                            buffer.append(new DoubleToken(ft.doubleValue()).toString());
                            if (j < (arrtok.length() - 1)) {
                                buffer.append(", ");
                            }
                        }
                        buffer.append("}");

                        temp1 = buffer.toString();
                        temp1 = temp1.replace('\\', '/');
                        temp1 = temp1.replaceFirst("\\{", "(");
                        temp1 = temp1.replaceAll("\\{", "c(");
                        temp1 = temp1.replace('}', ')');
                        temp1 = temp1.replace('"', '\'');
                        // assume that the token's string value might be
                        // 'nil' for a missing value
                        temp1 = temp1.replaceAll("nil", "NA");
                        // if string is long, create a temp file for passing
                        // array data
                        if (temp1.length() > maxCommandLineLength
                                && (!token_type_string.startsWith("arrayType(arrayType(float"))) {
                            temp1 = temp1.replace('(', ' ');
                            temp1 = temp1.replace(')', ' ');
                            String filename = _writeDataFile(temp1);
                            temp = "`" + temp + "` <- scan('" + filename + "', sep=',')";
                            temp = temp + "\n" + "file.remove('" + filename + "')";
                            RPortInfo = RPortInfo + temp + "\n";
                        } else { // otherwise use the modified string
                            if (token_type_string.startsWith("arrayType(arrayType(float")) {
                                temp = "`" + temp + "` <- list" + temp1;
                            } else {
                                temp = "`" + temp + "` <- c" + temp1;
                            }
                            temp = _breakIntoLines(temp);
                            RPortInfo = RPortInfo + temp + "\n";
                        }
                    } else if ((token_type_string.equals("{string}"))
                            || (token_type_string.startsWith("arrayType(string")
                                    || (token_type_string.startsWith("arrayType(arrayType(string")))) {
                        // token is an arrayToken !!!
                        at = (Token) token;
                        temp1 = at.toString();
                        temp1 = temp1.replace('\\', '/');
                        temp1 = temp1.replaceFirst("\\{", "(");
                        temp1 = temp1.replaceAll("\\{", "c(");
                        temp1 = temp1.replace('}', ')');
                        temp1 = temp1.replace('"', '\'');
                        // assume that the token's string value might be
                        // 'nil' for a missing value
                        temp1 = temp1.replaceAll("nil", "NA");
                        // if string is long, create a temp file for passing
                        // array data ONLY
                        if ((temp1.length() > maxCommandLineLength)
                                && (!token_type_string.startsWith("arrayType(arrayType(string"))) {
                            temp1 = temp1.replace('(', ' ');
                            temp1 = temp1.replace(')', ' ');
                            String filename = _writeDataFile(temp1);
                            temp = "`" + temp + "` <- scan('" + filename
                                    + "', what='character', sep=',', strip.white=TRUE)";
                            temp = temp + "\n" + "file.remove('" + filename + "')";
                            RPortInfo = RPortInfo + temp + "\n";
                        } else { // otherwise use the modified string
                            //for arrays of arrays, use list()
                            if (token_type_string.startsWith("arrayType(arrayType(string")) {
                                temp = "`" + temp + "` <- list" + temp1;
                            } else {
                                temp = "`" + temp + "` <- c" + temp1;
                            }
                            temp = _breakIntoLines(temp);
                            RPortInfo = RPortInfo + temp + "\n";
                        }
                    } else if (token_type_string.equals("niltype")) {
                        at = token;
                        temp1 = at.toString();
                        temp1 = temp1.replaceAll("nil", "NA");
                        temp = "`" + temp + "` <- " + temp1;
                        RPortInfo = RPortInfo + temp + "\n";
                    }
                    // set metadata on the R objects
                    // String metadataCommand = null;
                    if (tiop.isMultiport()) {
                        // set the metadata on each list item
                        // ("tempPortName") before adding it to the list
                        /* metadataCommand = */_createMetadataCommand(tempPortName, "name", sourcePortName);
                    } else {
                        // just set the metadata attribute for the final
                        // variable name
                        /* metadataCommand = */_createMetadataCommand(finalPortName, "name", sourcePortName);
                    }
                    // add the metadata attribute to the R object
                    // leinfelder, 4/14/2008:
                    // do not include the metadata as it introduces
                    // incompatibility with
                    // certain R methods that expect attributeless objects
                    // (barplot(vector))
                    // RPortInfo = RPortInfo + metadataCommand + "\n";

                    // use lists for making multiport input available in R
                    if (tiop.isMultiport()) {
                        String commandList = null;
                        if (i == 0) {
                            // create list
                            commandList = "`" + finalPortName + "` <- list(" + tempPortName + ")";
                        } else if (i > 0) {
                            // append to list
                            commandList = "`" + finalPortName + "` <- c(" + finalPortName + ", list("
                                    + tempPortName + ") )";
                        }
                        RPortInfo = RPortInfo + commandList + "\n";
                    }
                }
            } catch (IllegalActionException iae) {
                // just continue (port is probably not connected)
            }
        } // for multiport
    }
    // log.debug("RPortInfo: "+RPortInfo);
    // The following command casues R to output a series of 4 dashes which
    // are used as a marker
    // Any R output after this marker is used to construct information for
    // the actor output
    // ports. This information is removed from the R output text displayed
    // to the user.
    String r_out = "cat('----\\n')\n";

    // Ensure that output is echoed from this point on
    // We don't need to echo before cat('----\\n') because the cat statement forces output.
    // This way, the options(echo = TRUE) isn't sent to the "output" port
    r_out += "options(echo = TRUE)\n";
    // The following creates an R function called 'myput' to output port
    // info to output ports
    // r_out = r_out +
    // "if (class(x)=='data.frame') {write.table(x,file='"+df_fn+"');cat('_dataframe_:"+df_fn+"')}\n";
    r_out = r_out + "myput <- function(x, filename) {\n"
    // I'm wrapping the serialization into the doserialize function
    // because it's gotten big.  Unique filename generation is 
    // done here because this is where file creation is actually done.
    // This code relies on the replaceAll code and the added - in the
    // auto-generated .sav filename.  Remember that a \ in the regular 
    // expression is quadrupled for passing through both Java and R.
            + "  doserialize <- function(x, filename) {\n" + "    if (file.exists(filename)) {"
            + "      path <- dirname(filename); " + "      filename <- basename(filename); "
            + "      base <- sub('^(.*-)([0-9*])\\\\.(.*)$', '\\\\1', filename); "
            + "      ext <- sub('^(.*-)([0-9*])\\\\.(.*)$', '\\\\3', filename); "
            + "      dir_base_ext <- dir(pattern = paste(base, '[0-9]*\\\\.', ext, sep = '')); "
            + "      cnt <- max(as.numeric(sub('^(.*-)([0-9*])\\\\.(.*)$', '\\\\2', dir_base_ext)), na.rm = TRUE) + 1; "
            + "      filename <- file.path(path, paste(base, cnt, '.', ext, sep = ''))" + "    }\n"
            + "    conn <- file(filename, 'wb');" + "    serialize(x, conn);" + "    close(conn);"
            + "    filename" + "  }\n"
            // use a binary serialization for data frames
            + "  if (class(x)=='data.frame') {cat('_dataframe_:', doserialize(x, filename), '\\n', sep = '')}\n"
            + "  else if (class(x)=='matrix') {cat('_matrix_:',deparse(x, control=c('keepNA', 'showAttributes')), '\\n', sep = '') }\n"
            + "  else if (mode(x)=='numeric' && substr(deparse(x)[1], 1, 9) != \"structure\") {dput(as.double(x), control = NULL)}\n"
            + "  else if (mode(x)=='character' && substr(deparse(x)[1], 1, 9) != \"structure\") {dput(x)}\n"
            + "  else if (mode(x)=='logical' && substr(deparse(x)[1], 1, 9) != \"structure\") {dput(x)}\n"
            // use R serialization for other unknown objects
            + "  else {cat('_object_:', doserialize(x, filename), '\\n', sep = '')}" + "}\n";

    // Controlled newline test
    r_out = r_out + "cat(\"before newline\\nafter newline\\n\")\n";

    while (iter_o.hasNext()) {
        TypedIOPort tiop_o = (TypedIOPort) iter_o.next();
        String temp_o = tiop_o.getName();
        // now need to create an R script that returns info about an R
        // object with the
        // port name for use in creating Kepler output object
        if ((!temp_o.equals("output")) && (!temp_o.equals("graphicsFileName"))) {
            String df_fn = _getUniqueFileName(temp_o, "sav");
            String temp_o_escaped = temp_o;
            // Doing some basic escaping for the exists statement, 
            // although I'm not 100% sure all of these characters 
            // might occur. --Oliver
            temp_o_escaped = temp_o_escaped.replace("\\", "\\\\");
            temp_o_escaped = temp_o_escaped.replace("'", "\'");
            r_out = r_out + "if(exists('" + temp_o_escaped + "', .GlobalEnv)) {" + "cat(\"portName: " + temp_o
                    + "\\nvectorVal: \"); " + "myput(get(\"" + temp_o_escaped + "\", .GlobalEnv),'" + df_fn
                    + "'); " + "cat(\"endVectorVal\\n\")" + "}\n";
        }
    }

    String script = expression.getExpression();
    script = RPortInfo + script + "\n" + r_out + "\nquit()\n";
    try {
        _exec();
    } catch (Exception w) {
        log.error("Error in _exec()");
    }

    String outputString = "";
    String errorString = "";
    String noRErrorMessage = "There has been a problem running the R script!\n"
            + "It may be due to an error in your script, it may be that R is not\n"
            + "installed on your system, or it may not be on your path and cannot\n"
            + "be located by Kepler.  Please make sure R is installed and the\n"
            + "R command line executable is in the path."
            + "For more information, see \n section 8.2.2 of the Kepler User Manual.";
    try {
        _inputBufferedWriter.write(script);
        _inputBufferedWriter.flush();
        _inputBufferedWriter.close();
    } catch (IOException ex) {
        log.error("IOException while executing R script.");
        // Commenting out this loop--this can cause an infinite loop on XP,
        // (when R is not on user's PATH), which keeps the noRErrorMessage 
        // from ever showing. See bugs #4985 and #5025.
        //while(outputString.equals("")) {
        //   outputString = _outputGobbler.getAndReset();
        //   errorString = _errorGobbler.getAndReset();
        //   log.debug("R standard output: " + newline + outputString);
        //   log.debug("R standard error: " + newline + errorString);
        //}
        throw new IllegalActionException(this, ex, "Problem writing input. " + noRErrorMessage);
    } catch (NullPointerException npe) {
        throw new IllegalActionException(this, npe, noRErrorMessage);
    }
    try {
        int result = _process.waitFor();
        log.debug("Process complete: " + result);
        if (result != 0)
            throw new IllegalActionException(this, "R returned with value " + result + ", likely caused "
                    + newline + "by an error while executing the script.");
    } catch (IllegalActionException e) {
        log.error(e.getMessage());
        while (outputString.equals("")) {
            outputString = _outputGobbler.getAndReset();
            errorString = _errorGobbler.getAndReset();
            log.debug("R standard output: " + newline + outputString);
            log.error("R standard error: " + newline + errorString);
        }
        throw e;
    } catch (Exception www) {
        log.error("Exception waiting for _process to end!");
    }

    while (outputString.equals("")) {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
            log.error("Error in TestApp while sleeping!");
        }
        outputString = _outputGobbler.getAndReset();
        errorString = _errorGobbler.getAndReset();
        int loc = outputString.lastIndexOf("cat('----\\n')");
        int loc1 = outputString.lastIndexOf("----");
        String outputStringDisp = outputString;
        if (loc1 > -1) {
            if (loc < 0) {
                loc = loc1;
            }
            outputStringDisp = outputString.substring(0, loc);
            String rem = outputString.substring(loc1, outputString.length());
            _getOutput(rem);
        }
        output.send(0, new StringToken(outputStringDisp + "\n" + errorString));
        if (displayGraphicsOutputValue && (!graphicsDevice.equals(""))) {
            try {
                File fout = new File(home + graphicsOutputFile);
                URL furl = fout.toURL();
                BrowserLauncher.openURL(furl.toString());
            } catch (Exception e) {
                log.warn("problem launching browser:" + e);
            }
        }
        if (!graphicsDevice.equals(""))
            graphicsFileName.send(0, new StringToken(home + graphicsOutputFile));

    }
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

protected void addSourceCode(ExportFileResource[] allResources, ProcessItem processItem, boolean needSource,
        ExportFileResource resource, String... selectedJobVersion) {
    // getItemResource(processItem, resource, basePath, selectedJobVersion);
    // super.addSource(processItem, needSource, resource, basePath, selectedJobVersion);
    // Get java src
    if (!needSource) {
        return;/*from w w  w .ja va  2s .co m*/
    }
    try {
        String projectName = getCorrespondingProjectName(processItem);
        String jobName = processItem.getProperty().getLabel();
        String jobVersion = processItem.getProperty().getVersion();
        if (!isMultiNodes() && selectedJobVersion != null && selectedJobVersion.length == 1) {
            jobVersion = selectedJobVersion[0];
        }

        String jobFolderName = JavaResourcesHelper.getJobFolderName(jobName, jobVersion);

        IPath path = getSrcRootLocation();
        path = path.append(projectName).append(jobFolderName);

        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".java"); //$NON-NLS-1$
            }
        };
        List<URL> javaFileUrls = new ArrayList<URL>();
        File file = path.toFile();
        if (file.exists() && file.isDirectory()) {
            for (File curFile : file.listFiles(filter)) {
                javaFileUrls.add(FileLocator.toFileURL(curFile.toURL()));
            }
        }

        resource.addResources(
                JOB_SOURCE_FOLDER_NAME + PATH_SEPARATOR + projectName + PATH_SEPARATOR + jobFolderName,
                javaFileUrls);

    } catch (Exception e) {
        ExceptionHandler.process(e);
    }
}

From source file:org.danann.cernunnos.io.FileIteratorTask.java

public void perform(TaskRequest req, TaskResponse res) {

    String d = (String) dir.evaluate(req, res);
    File baseDir = new File(d);

    if (!baseDir.exists()) {
        // We're going to assume this won't happen
        // except where something's really wrong...
        String msg = "The specified DIR does not exist:  " + d;
        log.error(msg);//from   w w  w . ja  v a  2 s .c om
        throw new RuntimeException(msg);
    }

    String incl = (String) includes.evaluate(req, res);
    String[] inclTokens = LIST_DELIM.split(incl);
    List<String>[] inclStacks = new List[inclTokens.length];
    for (int i = 0; i < inclTokens.length; i++) {
        inclStacks[i] = Arrays.asList(PATH_DELIM.split(inclTokens[i]));
    }

    String excl = "[Not Evaluated]";

    Set<File> fileSet = getMatchingDescendants(baseDir, inclStacks);

    if (excludes != null) {
        excl = (String) excludes.evaluate(req, res);
        String[] exclTokens = LIST_DELIM.split(excl);
        List<String>[] exclStacks = new List[exclTokens.length];
        for (int i = 0; i < exclTokens.length; i++) {
            exclStacks[i] = Arrays.asList(PATH_DELIM.split(exclTokens[i]));
        }
        Set<File> exclSet = getMatchingDescendants(baseDir, exclStacks);
        fileSet.removeAll(exclSet);
    }

    // Report on the # of matched files...
    if (log.isTraceEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("FileIteratorTask details:").append("\n\t\tDIR=").append(d).append("\n\t\tINCLUDES=")
                .append(incl).append("\n\t\tEXCLUDES=").append(excl).append("\n\t\tfound ")
                .append(fileSet.size()).append(" matching files\n");
        log.trace(msg.toString());
    }

    // Set the default CONTEXT for subtasks...
    final URL contextUrl;
    try {
        contextUrl = baseDir.toURL();
    } catch (MalformedURLException mue) {
        throw new RuntimeException("Failed to convert dir attribute into URL: " + baseDir, mue);
    }
    res.setAttribute(Attributes.CONTEXT, contextUrl.toString());

    // Iterate over the results, setting each one to the specified request attribute...
    String name = (String) attribute_name.evaluate(req, res);
    String mask;
    try {
        mask = baseDir.getCanonicalPath();
    } catch (IOException ioe) {
        throw new RuntimeException("Could not convert dir attribute into canonical path: " + baseDir, ioe);
    }
    if (!mask.endsWith(File.separator)) {
        mask = mask + File.separator;
    }
    for (File f : fileSet) {
        final String canonicalPath;
        try {
            canonicalPath = f.getCanonicalPath();
        } catch (IOException ioe) {
            throw new RuntimeException("Could not convert file into canonical path: " + f, ioe);
        }

        String location = canonicalPath.substring(mask.length());
        res.setAttribute(name, location);
        super.performSubtasks(req, res);
    }
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

protected List<URL> getLib(List<String> libs, Boolean needLib) {
    List<URL> list = new ArrayList<URL>();
    if (!needLib) {
        return list;
    }/*from w w  w .j a va2 s.  com*/

    try {
        // IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        // IProject prj = root.getProject(JavaUtils.JAVA_PROJECT_NAME);
        // IJavaProject project = JavaCore.create(prj);
        // IPath libPath = project.getResource().getLocation().append(JavaUtils.JAVA_LIB_DIRECTORY);
        // File file = libPath.toFile();
        // File[] files = file.listFiles(new FilenameFilter() {
        //
        // public boolean accept(File dir, String name) {
        //                    return name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".properties") //$NON-NLS-1$ //$NON-NLS-2$
        //                            || name.toLowerCase().endsWith(".zip") ? true : false; //$NON-NLS-1$
        // }
        // });
        //
        // for (int i = 0; i < files.length; i++) {
        // File tempFile = files[i];
        // try {
        // if (libs.contains(tempFile.getName())) {
        // list.add(tempFile.toURL());
        // }
        // } catch (MalformedURLException e) {
        // ExceptionHandler.process(e);
        // }
        // }

        org.talend.core.model.general.Project projecdddt = ProjectManager.getInstance().getCurrentProject();
        IProject fsProject = null;
        try {
            fsProject = ResourceUtils.getProject(projecdddt);
        } catch (PersistenceException e2) {
            ExceptionHandler.process(e2);
        }
        IPath temPath = fsProject.getLocation().append(File.separator + "temp"); //$NON-NLS-1$
        ILibraryManagerService repositoryBundleService = CorePlugin.getDefault().getRepositoryBundleService();
        if (repositoryBundleService != null) {
            repositoryBundleService.retrieve(libs, temPath.toString());
        }
        File file = temPath.toFile();
        File[] files = file.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(FileConstants.JAR_FILE_SUFFIX)
                        || name.toLowerCase().endsWith(FileConstants.PROPERTIES_FILE_SUFFIX)
                        || name.toLowerCase().endsWith(FileConstants.ZIP_FILE_SUFFIX) ? true : false;
            }
        });

        for (File tempFile : files) {
            try {
                if (libs.contains(tempFile.getName())) {
                    list.add(tempFile.toURL());
                }
            } catch (MalformedURLException e) {
                ExceptionHandler.process(e);
            }
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    }
    return list;
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

/**
 * Gets required java jars.//from w  ww  .  j a  v a 2 s .co  m
 * 
 * @param process
 * 
 * @param boolean1
 * @return
 */
protected List<URL> getExternalLibraries(boolean needLibraries, ExportFileResource[] process,
        final Set<String> neededLibraries) {
    List<URL> list = new ArrayList<URL>();
    if (!needLibraries) {
        return list;
    }
    IFolder libFolder = null;
    if (GlobalServiceRegister.getDefault().isServiceRegistered(IRunProcessService.class)) {
        IRunProcessService processService = (IRunProcessService) GlobalServiceRegister.getDefault()
                .getService(IRunProcessService.class);
        ITalendProcessJavaProject talendProcessJavaProject = processService.getTalendProcessJavaProject();
        if (talendProcessJavaProject != null) {
            libFolder = talendProcessJavaProject.getLibFolder();
        }
    }
    if (libFolder == null) {
        return list;
    }
    File file = libFolder.getLocation().toFile();
    File[] files = file.listFiles(FilesUtils.getAcceptModuleFilesFilter());
    // Lists all the needed jar files
    Set<String> listModulesReallyNeeded = new HashSet<String>();
    if (neededLibraries == null) {
        // in case export as been done with option "not recompile", then libraires can't be retrieved when build.
        IDesignerCoreService designerService = RepositoryPlugin.getDefault().getDesignerCoreService();
        for (ExportFileResource resource : process) {
            ProcessItem item = (ProcessItem) resource.getItem();
            String version = item.getProperty().getVersion();
            if (!isMultiNodes() && this.getSelectedJobVersion() != null) {
                version = this.getSelectedJobVersion();
            }
            ProcessItem selectedProcessItem;
            if (resource.getNode() != null) {
                selectedProcessItem = ItemCacheManager.getProcessItem(resource.getNode().getRoot().getProject(),
                        item.getProperty().getId(), version);
            } else {
                // if no node given, take in the current project only
                selectedProcessItem = ItemCacheManager.getProcessItem(item.getProperty().getId(), version);
            }
            IProcess iProcess = designerService.getProcessFromProcessItem(selectedProcessItem);
            Set<String> processNeededLibraries = iProcess.getNeededLibraries(true);
            if (processNeededLibraries != null) {
                listModulesReallyNeeded.addAll(processNeededLibraries);
            }
        }
    } else {
        listModulesReallyNeeded.addAll(neededLibraries);
    }

    // jar from routines
    List<IRepositoryViewObject> collectRoutines = new ArrayList<IRepositoryViewObject>();
    boolean useBeans = false;
    if (GlobalServiceRegister.getDefault().isServiceRegistered(ICamelDesignerCoreService.class)) {
        ICamelDesignerCoreService camelService = (ICamelDesignerCoreService) GlobalServiceRegister.getDefault()
                .getService(ICamelDesignerCoreService.class);
        if (camelService.isInstanceofCamel(process[0].getItem())) {
            useBeans = true;
        }
    }
    String include = null;
    if (useBeans) {
        include = USER_BEANS_PATH;
    } else {
        include = USER_ROUTINES_PATH;
    }
    collectRoutines.addAll(collectRoutines(process, include));
    collectRoutines.addAll(collectRoutines(process, USER_PIGUDF_PATH));

    for (IRepositoryViewObject object : collectRoutines) {
        Item item = object.getProperty().getItem();
        if (item instanceof RoutineItem) {
            RoutineItem routine = (RoutineItem) item;
            EList imports = routine.getImports();
            for (Object o : imports) {
                IMPORTType type = (IMPORTType) o;
                listModulesReallyNeeded.add(type.getMODULE());
            }
        }
    }
    if (Log4jPrefsSettingManager.getInstance().isLog4jEnable()) {
        addLog4jToJarList(listModulesReallyNeeded);
    }
    for (File tempFile : files) {
        try {
            if (listModulesReallyNeeded.contains(tempFile.getName())) {
                list.add(tempFile.toURL());
            }
        } catch (MalformedURLException e) {
            ExceptionHandler.process(e);
        }
    }
    return list;
    // List<URL> libraries = new ArrayList<URL>();
    // if (needLibraries) {
    // try {
    // ILibrariesService service = CorePlugin.getDefault().getLibrariesService();
    // libraries = service.getTalendRoutines();
    // } catch (Exception e) {
    // ExceptionHandler.process(e);
    // }
    // }
    // return libraries;
}

From source file:org.apache.axis2.jaxws.description.impl.OperationDescriptionImpl.java

/**
 * This method will drive the building of AttachmentDescription objects for the
 * operation input/output messages in the WSDL.
 *
 *//*w w  w.  ja v a 2  s .c  om*/
private void buildAttachmentInformation() {
    if (log.isDebugEnabled()) {
        log.debug("Start buildAttachmentInformation");
    }
    // Only building attachment info if we find a full WSDL
    if (this.getEndpointInterfaceDescriptionImpl().getEndpointDescriptionImpl().isWSDLFullySpecified()) {
        if (log.isDebugEnabled()) {
            log.debug("A full WSDL is available.  Query the WSDL binding for the "
                    + "AttachmentDescription information.");
        }
        DescriptionUtils.getAttachmentFromBinding(this,
                this.getEndpointInterfaceDescriptionImpl().getEndpointDescriptionImpl().getWSDLBinding());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The WSDL is not available.  Looking for @WebService wsdlLocation.");
        }

        // Try getting a WSDL
        String wsdlLocation = this.getEndpointInterfaceDescriptionImpl().getEndpointDescriptionImpl()
                .getAnnoWebServiceWSDLLocation();

        if (wsdlLocation == null || wsdlLocation.length() == 0) {
            if (log.isDebugEnabled()) {
                log.debug("@WebService wsdlLocation is not specified.  "
                        + "Processing continues without AttachmentDescription information");
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("@WebService wsdlLocation is " + wsdlLocation);
            }

            Definition def = null;
            WSDL4JWrapper wsdl4j = null;
            try {
                File file = new File(wsdlLocation);
                URL url = file.toURL();
                wsdl4j = new WSDL4JWrapper(url, true, 2); // In this context, limit the wsdl memory
                def = wsdl4j.getDefinition();
            } catch (Throwable t) {
                if (log.isDebugEnabled()) {
                    log.debug("Error occurred while loading WSDL.  "
                            + "Procesing continues without AttachmentDescription " + "information. " + t);
                }
            }
            if (def != null) {
                // Set the WSDL on the server
                this.getEndpointInterfaceDescriptionImpl().getEndpointDescriptionImpl()
                        .getServiceDescriptionImpl().setWsdlWrapper(wsdl4j);
                if (log.isDebugEnabled()) {
                    log.debug("WSDL Definition is loaded.  Get the WSDL Binding.");
                }

                Binding binding = this.getEndpointInterfaceDescriptionImpl().getEndpointDescriptionImpl()
                        .getWSDLBinding();

                if (binding == null) {
                    if (log.isDebugEnabled()) {
                        log.debug("WSDL Binding was not found for serviceName="
                                + this.getEndpointInterfaceDescription().getEndpointDescription()
                                        .getServiceQName()
                                + " and portName=" + this.getEndpointInterfaceDescription()
                                        .getEndpointDescription().getPortQName());
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Query Binding for AttachmentDescription Information");
                    }
                    DescriptionUtils.getAttachmentFromBinding(this, binding);
                }
            }
        }

    }
    if (log.isDebugEnabled()) {
        log.debug("End buildAttachmentInformation");
    }
}

From source file:org.talend.repository.ui.wizards.exportjob.scriptsmanager.JobJavaScriptsManager.java

/**
 * User may delete some contexts after generating the context files. So we will only export those files that match
 * any existing context name. See bug 0003568: Three contexts file exported, while only two contexts in the job.
 * //from  w w w  .  ja  v a 2 s  .c  o m
 * @param listFiles The generated context files.
 * @param processItem The current process item that will be exported.
 * @return An url list of context files.
 * @throws MalformedURLException
 */
private List<URL> getActiveContextFiles(File[] listFiles, ProcessItem processItem)
        throws MalformedURLException {
    List<URL> contextFileUrls = new ArrayList<URL>();
    try {
        // get all context name from process
        Set<String> contextNames = new HashSet<String>();
        for (String contextName : LastGenerationInfo.getInstance()
                .getContextPerJob(processItem.getProperty().getId(), processItem.getProperty().getVersion())) {
            contextNames.add(contextName.replace(" ", "")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        for (File file : listFiles) {
            String fileName = file.getName();
            // remove file extension
            fileName = fileName.substring(0, fileName.lastIndexOf('.'));
            if (contextNames.contains(fileName)) {
                // if the file match any existing context, add this file to list
                contextFileUrls.add(file.toURL());
            }
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    }
    return contextFileUrls;
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Add a file to the path. This classloader reads the manifest, if
 * available, and adds any additional class path jars specified in the
 * manifest./*from   w  ww  .  jav a  2 s .  com*/
 *
 * @param pathComponent the file which is to be added to the path for
 *                      this class loader
 *
 * @throws IOException if data needed from the file cannot be read.
 */
public void addPathFile(File pathComponent) throws IOException {
    pathComponents.addElement(pathComponent);

    if (pathComponent.isDirectory()) {
        return;
    }

    String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-"
            + pathComponent.length();
    String classpath = pathMap.get(absPathPlusTimeAndLength);
    if (classpath == null) {
        ZipFile jarFile = null;
        InputStream manifestStream = null;
        try {
            jarFile = new ZipFile(pathComponent);
            manifestStream = jarFile.getInputStream(new ZipEntry("META-INF/MANIFEST.MF"));

            if (manifestStream == null) {
                return;
            }
            Manifest manifest = new Manifest(manifestStream);
            classpath = manifest.getMainAttributes().getValue("Class-Path");

        } finally {
            if (manifestStream != null) {
                manifestStream.close();
            }
            if (jarFile != null) {
                jarFile.close();
            }
        }
        if (classpath == null) {
            classpath = "";
        }
        pathMap.put(absPathPlusTimeAndLength, classpath);
    }

    if (!"".equals(classpath)) {
        URL baseURL = pathComponent.toURL();
        StringTokenizer st = new StringTokenizer(classpath);
        while (st.hasMoreTokens()) {
            String classpathElement = st.nextToken();
            URL libraryURL = new URL(baseURL, classpathElement);
            if (!libraryURL.getProtocol().equals("file")) {
                logger.fine("Skipping jar library " + classpathElement
                        + " since only relative URLs are supported by this" + " loader");
                continue;
            }
            File libraryFile = new File(libraryURL.getFile());
            if (libraryFile.exists() && !isInPath(libraryFile)) {
                addPathFile(libraryFile);
            }
        }
    }
}

From source file:org.smilec.smile.student.CourseList.java

@SuppressWarnings("deprecation")
private void getStoredFileURL() {

    // save URL for stored file
    File data_dir = getBaseContext().getFilesDir();

    try {//from w  w w .  j av a 2s . c o m

        URL url = data_dir.toURL();
        stored_file_url = url.toString();
    } catch (Exception e) {
        Log.d(APP_TAG, "URL ERROR");
    }
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java

/**
 * <p> Creates a new {@link StandaloneProcessingUnitContainer} based on the configured
 * parameters. A standalone processing unit container is a container that understands a
 * processing unit archive structure (both when working with an "exploded" directory and when
 * working with a zip/jar archive of it). It is provided with the location of the processing
 * unit using {@link org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider#StandaloneProcessingUnitContainerProvider(String)}.
 * The location itself follows Spring resource loader syntax.
 *
 * <p> If {@link #addConfigLocation(String)} is used, the Spring xml context will be read based
 * on the provided locations. If no config location was provided the default config location
 * will be <code>classpath*:/META-INF/spring/pu.xml</code>.
 *
 * <p> If {@link #setBeanLevelProperties(org.openspaces.core.properties.BeanLevelProperties)} is
 * set will use the configured bean level properties in order to configure the application
 * context and specific beans within it based on properties. This is done by adding {@link
 * org.openspaces.core.properties.BeanLevelPropertyBeanPostProcessor} and {@link
 * org.openspaces.core.properties.BeanLevelPropertyPlaceholderConfigurer} to the application
 * context./* w ww . ja v  a2  s.co m*/
 *
 * <p> If {@link #setClusterInfo(org.openspaces.core.cluster.ClusterInfo)} is set will use it to
 * inject {@link org.openspaces.core.cluster.ClusterInfo} into beans that implement {@link
 * org.openspaces.core.cluster.ClusterInfoAware}.
 *
 * @return An {@link StandaloneProcessingUnitContainer} instance
 */
public ProcessingUnitContainer createContainer() throws CannotCreateContainerException {
    File fileLocation = new File(location);
    if (!fileLocation.exists()) {
        throw new CannotCreateContainerException("Failed to locate pu location [" + location + "]");
    }

    // in case we don't have a cluster info specific members
    final ClusterInfo clusterInfo = getClusterInfo();
    if (clusterInfo != null && clusterInfo.getInstanceId() == null) {
        ClusterInfo origClusterInfo = clusterInfo;
        List<ProcessingUnitContainer> containers = new ArrayList<ProcessingUnitContainer>();
        for (int i = 0; i < clusterInfo.getNumberOfInstances(); i++) {
            ClusterInfo containerClusterInfo = clusterInfo.copy();
            containerClusterInfo.setInstanceId(i + 1);
            containerClusterInfo.setBackupId(null);
            setClusterInfo(containerClusterInfo);
            containers.add(createContainer());
            if (clusterInfo.getNumberOfBackups() != null) {
                for (int j = 0; j < clusterInfo.getNumberOfBackups(); j++) {
                    containerClusterInfo = containerClusterInfo.copy();
                    containerClusterInfo.setBackupId(j + 1);
                    setClusterInfo(containerClusterInfo);
                    containers.add(createContainer());
                }
            }
        }
        setClusterInfo(origClusterInfo);
        return new CompoundProcessingUnitContainer(
                containers.toArray(new ProcessingUnitContainer[containers.size()]));
    }

    if (clusterInfo != null) {
        ClusterInfoParser.guessSchema(clusterInfo);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Starting a Standalone processing unit container "
                + (clusterInfo != null ? "with " + clusterInfo : ""));
    }

    List<URL> urls = new ArrayList<URL>();
    List<URL> sharedUrls = new ArrayList<URL>();
    if (fileLocation.isDirectory()) {
        if (fileLocation.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Adding pu directory location [" + location + "] to classpath");
            }
            try {
                urls.add(fileLocation.toURL());
            } catch (MalformedURLException e) {
                throw new CannotCreateContainerException(
                        "Failed to add classes to class loader with location [" + location + "]", e);
            }
        }
        addJarsLocation(fileLocation, urls, "lib");
        addJarsLocation(fileLocation, sharedUrls, "shared-lib");
    } else {
        JarFile jarFile;
        try {
            jarFile = new JarFile(fileLocation);
        } catch (IOException e) {
            throw new CannotCreateContainerException("Failed to open pu file [" + location + "]", e);
        }
        // add the root to the classpath
        try {
            urls.add(new URL("jar:" + fileLocation.toURL() + "!/"));
        } catch (MalformedURLException e) {
            throw new CannotCreateContainerException(
                    "Failed to add pu location [" + location + "] to classpath", e);
        }
        // add jars in lib and shared-lib to the classpath
        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry jarEntry = entries.nextElement();
            if (isWithinDir(jarEntry, "lib") || isWithinDir(jarEntry, "shared-lib")) {
                // extract the jar into a temp location
                if (logger.isDebugEnabled()) {
                    logger.debug("Adding jar [" + jarEntry.getName() + "] with pu location [" + location + "]");
                }
                File tempLocation = new File(System.getProperty("java.io.tmpdir") + "/openspaces");
                tempLocation.mkdirs();
                File tempJar;
                String tempJarName = jarEntry.getName();
                if (tempJarName.indexOf('/') != -1) {
                    tempJarName = tempJarName.substring(tempJarName.lastIndexOf('/') + 1);
                }
                try {
                    tempJar = File.createTempFile(tempJarName, ".jar", tempLocation);
                } catch (IOException e) {
                    throw new CannotCreateContainerException("Failed to create temp jar at location ["
                            + tempLocation + "] with name [" + tempJarName + "]", e);
                }
                tempJar.deleteOnExit();
                if (logger.isTraceEnabled()) {
                    logger.trace("Extracting jar [" + jarEntry.getName() + "] to temporary jar ["
                            + tempJar.getAbsolutePath() + "]");
                }

                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(tempJar);
                } catch (FileNotFoundException e) {
                    throw new CannotCreateContainerException(
                            "Failed to find temp jar [" + tempJar.getAbsolutePath() + "]", e);
                }
                InputStream is = null;
                try {
                    is = jarFile.getInputStream(jarEntry);
                    FileCopyUtils.copy(is, fos);
                } catch (IOException e) {
                    throw new CannotCreateContainerException(
                            "Failed to create temp jar [" + tempJar.getAbsolutePath() + "]");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e1) {
                            // do nothing
                        }
                    }
                    try {
                        fos.close();
                    } catch (IOException e1) {
                        // do nothing
                    }
                }

                try {
                    if (isWithinDir(jarEntry, "lib")) {
                        urls.add(tempJar.toURL());
                    } else if (isWithinDir(jarEntry, "shared-lib")) {
                        sharedUrls.add(tempJar.toURL());
                    }
                } catch (MalformedURLException e) {
                    throw new CannotCreateContainerException("Failed to add pu entry [" + jarEntry.getName()
                            + "] with location [" + location + "]", e);
                }
            }
        }
    }

    List<URL> allUrls = new ArrayList<URL>();
    allUrls.addAll(sharedUrls);
    allUrls.addAll(urls);

    addUrlsToContextClassLoader(allUrls.toArray(new URL[allUrls.size()]));

    StandaloneContainerRunnable containerRunnable = new StandaloneContainerRunnable(getBeanLevelProperties(),
            clusterInfo, configLocations);
    Thread standaloneContainerThread = new Thread(containerRunnable, "Standalone Container Thread");
    standaloneContainerThread.setDaemon(false);
    standaloneContainerThread.start();

    while (!containerRunnable.isInitialized()) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for standalone container to initialize");
        }
    }

    if (containerRunnable.hasException()) {
        throw new CannotCreateContainerException("Failed to start container", containerRunnable.getException());
    }

    return new StandaloneProcessingUnitContainer(containerRunnable);
}