Example usage for java.lang.reflect InvocationTargetException printStackTrace

List of usage examples for java.lang.reflect InvocationTargetException printStackTrace

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:edu.harvard.iq.dvn.ingest.dsb.SubsettableFileChecker.java

public String detectSubsettableFormat(File fh) {
    boolean DEBUG = false;
    String readableFormatType = null;
    try {/*from www  . ja va2  s  .com*/
        int buffer_size = this.getBufferSize(fh);
        // set-up a FileChannel instance for a given file object
        FileChannel srcChannel = new FileInputStream(fh).getChannel();

        // create a read-only MappedByteBuffer
        MappedByteBuffer buff = srcChannel.map(FileChannel.MapMode.READ_ONLY, 0, buffer_size);

        //this.printHexDump(buff, "hex dump of the byte-buffer");

        //for (String fmt : defaultFormatSet){
        buff.rewind();
        dbgLog.fine("before the for loop");
        for (String fmt : this.getTestFormatSet()) {
            // get a test method
            Method mthd = testMethods.get(fmt);
            try {
                // invoke this method
                Object retobj = mthd.invoke(this, buff);
                String result = (String) retobj;

                if (result != null) {
                    dbgLog.fine("result for (" + fmt + ")=" + result);
                    if (DEBUG) {
                        out.println("result for (" + fmt + ")=" + result);
                    }
                    if (readableFileTypes.contains(result)) {
                        readableFormatType = result;
                    }
                    dbgLog.fine("readableFormatType=" + readableFormatType);
                    return readableFormatType;
                } else {
                    dbgLog.fine("null was returned for " + fmt + " test");
                    if (DEBUG) {
                        out.println("null was returned for " + fmt + " test");
                    }
                }
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                err.format(cause.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return readableFormatType;

    } catch (FileNotFoundException fe) {
        dbgLog.fine("exception detected: file was not foud");
        fe.printStackTrace();
    } catch (IOException ie) {
        dbgLog.fine("other io exception detected");
        ie.printStackTrace();
    }
    return readableFormatType;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestableDataChecker.java

public String detectTabularDataFormat(File fh) {
    boolean DEBUG = false;
    String readableFormatType = null;
    try {/*from  ww  w  .j av  a2 s .  c  o  m*/
        int buffer_size = this.getBufferSize(fh);
        dbgLog.fine("buffer_size: " + buffer_size);

        // set-up a FileChannel instance for a given file object
        FileChannel srcChannel = new FileInputStream(fh).getChannel();

        // create a read-only MappedByteBuffer
        MappedByteBuffer buff = srcChannel.map(FileChannel.MapMode.READ_ONLY, 0, buffer_size);

        //this.printHexDump(buff, "hex dump of the byte-buffer");

        //for (String fmt : defaultFormatSet){
        buff.rewind();
        dbgLog.fine("before the for loop");
        for (String fmt : this.getTestFormatSet()) {

            // get a test method
            Method mthd = testMethods.get(fmt);
            //dbgLog.info("mthd: " + mthd.getName());

            try {
                // invoke this method
                Object retobj = mthd.invoke(this, buff);
                String result = (String) retobj;

                if (result != null) {
                    dbgLog.fine("result for (" + fmt + ")=" + result);
                    if (DEBUG) {
                        out.println("result for (" + fmt + ")=" + result);
                    }
                    if (readableFileTypes.contains(result)) {
                        readableFormatType = result;
                    }
                    dbgLog.fine("readableFormatType=" + readableFormatType);
                    return readableFormatType;
                } else {
                    dbgLog.fine("null was returned for " + fmt + " test");
                    if (DEBUG) {
                        out.println("null was returned for " + fmt + " test");
                    }
                }
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                // added null check because of "homemade.zip" from https://redmine.hmdc.harvard.edu/issues/3273
                if (cause.getMessage() != null) {
                    err.format(cause.getMessage());
                    e.printStackTrace();
                } else {
                    dbgLog.info("cause.getMessage() was null for " + e);
                    e.printStackTrace();
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (BufferUnderflowException e) {
                dbgLog.info("BufferUnderflowException " + e);
                e.printStackTrace();
            }
        }

        return readableFormatType;

    } catch (FileNotFoundException fe) {
        dbgLog.fine("exception detected: file was not foud");
        fe.printStackTrace();
    } catch (IOException ie) {
        dbgLog.fine("other io exception detected");
        ie.printStackTrace();
    }
    return readableFormatType;
}

From source file:com.connectsdk.cordova.JSCommandDispatcher.java

public void dispatchCommand(String interfaceName, String methodName, JSCommand command, JSONObject args,
        boolean subscribe) {
    Method method = getMethod(interfaceName, methodName);

    if (method != null) {
        try {//from  w ww .  j av  a 2  s  .  c  om
            Object returnValue = method.invoke(this, command, args);

            if (returnValue != null && returnValue instanceof ServiceSubscription) {
                command.serviceSubscription = (ServiceSubscription<?>) returnValue;
            }
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            Exception wrappedException = new DispatcherException(
                    "Exception calling " + methodName + ": " + cause.toString());
            wrappedException.initCause(cause);

            wrappedException.printStackTrace();
            command.error(wrappedException);
        } catch (Exception e) {
            e.printStackTrace();
            command.error(e);
        }
    } else {
        Log.d("ConnectSDKCordova", "Method not implemented: " + interfaceName + "." + methodName);
        command.error("method not implemented");
    }
}

From source file:com.intel.moe.frameworks.inapppurchase.android.util.IabHelper.java

/**
 * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase,
 * which will involve bringing up the Google Play screen. The calling activity will be paused while
 * the user interacts with Google Play, and the result will be delivered via the activity's
 * {@link Activity#onActivityResult} method, at which point you must call
 * this object's {@link #handleActivityResult} method to continue the purchase flow. This method
 * MUST be called from the UI thread of the Activity.
 *
 * @param act The calling activity.//from  w  w w  .j ava2 s.  c o m
 * @param sku The sku of the item to purchase.
 * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS)
 * @param requestCode A request code (to differentiate from other responses --
 *     as in {@link Activity#startActivityForResult}).
 * @param listener The listener to notify when the purchase process finishes
 * @param extraData Extra data (developer payload), which will be returned with the purchase data
 *     when the purchase completes. This extra data will be permanently bound to that purchase
 *     and will always be returned when the purchase is queried.
 */
public void launchPurchaseFlow(Object act, String sku, String itemType, int requestCode,
        OnIabPurchaseFinishedListener listener, String extraData) {
    checkNotDisposed();
    checkSetupDone("launchPurchaseFlow");
    flagStartAsync("launchPurchaseFlow");
    IabResult result;

    if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) {
        IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available.");
        flagEndAsync();
        if (listener != null)
            listener.onIabPurchaseFinished(r, null);
        return;
    }

    try {
        logDebug("Constructing buy intent for " + sku + ", item type: " + itemType);
        Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData);
        int response = getResponseCodeFromBundle(buyIntentBundle);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            logError("Unable to buy item, Error response: " + getResponseDesc(response));
            flagEndAsync();
            result = new IabResult(response, "Unable to buy item");
            if (listener != null)
                listener.onIabPurchaseFinished(result, null);
            return;
        }

        PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT);
        logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode);
        mRequestCode = requestCode;
        mPurchaseListener = listener;
        mPurchasingItemType = itemType;
        Class activityClass = Class.forName("android.app.Activity");

        Class[] paramTypes = new Class[] { IntentSender.class, int.class, Intent.class, int.class, int.class,
                int.class };
        Method method = activityClass.getMethod("startIntentSenderForResult", paramTypes);

        Object[] args = new Object[] { pendingIntent.getIntentSender(), requestCode, new Intent(),
                Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0) };

        method.invoke(act, args);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof IntentSender.SendIntentException) {
            logError("SendIntentException while launching purchase flow for sku " + sku);
            e.printStackTrace();
            flagEndAsync();

            result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent.");
            if (listener != null)
                listener.onIabPurchaseFinished(result, null);
        }
    } catch (RemoteException e) {
        logError("RemoteException while launching purchase flow for sku " + sku);
        e.printStackTrace();
        flagEndAsync();

        result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow");
        if (listener != null)
            listener.onIabPurchaseFinished(result, null);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:azkaban.viewer.reportal.ReportalServlet.java

private HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger logger) throws RuntimeException {

    Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true,
            ReportalServlet.class.getClassLoader());
    logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName());
    HadoopSecurityManager hadoopSecurityManager = null;

    try {//from   ww  w .j  a va 2s .  co m
        Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class);
        hadoopSecurityManager = (HadoopSecurityManager) getInstanceMethod.invoke(hadoopSecurityManagerClass,
                props);
    } catch (InvocationTargetException e) {
        logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName()
                + e.getCause());
        throw new RuntimeException(e.getCause());
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getCause());
    }

    return hadoopSecurityManager;
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRforeignFileConversionServiceImpl.java

/** *************************************************************
 * Execute an R-based dvn statistical analysis request 
 *
 * @param sro    a DvnRJobRequest object that contains various parameters
 * @return    a Map that contains various information about results
 *//*from   w ww .  j  a v  a 2  s.co  m*/

public Map<String, String> execute(DvnRJobRequest sro) {
    dbgLog.fine("***** DvnRforeignFileConversionServiceImpl: execute() starts here *****");

    // set the return object
    Map<String, String> result = new HashMap<String, String>();
    // temporary result
    Map<String, String> tmpResult = new HashMap<String, String>();

    try {
        // Set up an Rserve connection
        dbgLog.fine("sro dump:\n" + ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

        dbgLog.fine("RSERVE_USER=" + RSERVE_USER + "[default=rserve]");
        dbgLog.fine("RSERVE_PWD=" + RSERVE_PWD + "[default=rserve]");
        dbgLog.fine("RSERVE_PORT=" + RSERVE_PORT + "[default=6311]");

        RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT);
        dbgLog.fine("hostname=" + RSERVE_HOST);

        c.login(RSERVE_USER, RSERVE_PWD);
        dbgLog.fine(">" + c.eval("R.version$version.string").asString() + "<");

        // check working directories
        // This needs to be done *before* we try to create any files 
        // there!
        setupWorkingDirectory(c);

        // save the data file at the Rserve side
        String infile = sro.getSubsetFileName();
        InputStream inb = new BufferedInputStream(new FileInputStream(infile));

        int bufsize;
        byte[] bffr = new byte[1024];

        RFileOutputStream os = c.createFile(tempFileName);
        while ((bufsize = inb.read(bffr)) != -1) {
            os.write(bffr, 0, bufsize);
        }
        os.close();
        inb.close();

        // Rserve code starts here
        dbgLog.fine("wrkdir=" + wrkdir);
        c.voidEval(librarySetup);

        // variable type
        /* 
        vartyp <-c(1,1,1)
        */
        // java side
        // int [] jvartyp  = {1,1,1};// = mp.get("vartyp").toArray()
        // int [] jvartyp  = sro.getVariableTypes();
        /*
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0 ; i< jvartyp.length; i++){
        if (i == (jvartyp.length -1)){
            sb.append(String.valueOf(jvartyp[i]));
        } else {
            sb.append(String.valueOf(jvartyp[i])+", ");
        }
                    }
                            
                    // R side
        */

        /*
         * Note that we want to use the "getVariableTypesWithBoolean method 
         * below; when we create a SRO object for analysis, in 
         * DvnRDataAnalysisServiceImpl, we'll still be using getVariableTypes
         * method, that don't recognize Booleans as a distinct class of 
         * variables. So those would be treated simply as numeric categoricals 
         * (factors) with the "TRUE" and "FALSE" labels. But for the purposes
         * of saving the subset in R format, we want to convert these into
         * R "logical" vectors.
         */

        dbgLog.fine("raw variable type=" + sro.getVariableTypesWithBoolean());
        c.assign("vartyp", new REXPInteger(sro.getVariableTypesWithBoolean()));
        String[] tmpt = c.eval("vartyp").asStrings();
        dbgLog.fine("vartyp length=" + tmpt.length + "\t " + StringUtils.join(tmpt, ","));

        // variable format (date/time)
        /* 
        varFmt<-list();
        c.voidEval("varFmt<-list()");
        */

        Map<String, String> tmpFmt = sro.getVariableFormats();
        dbgLog.fine("tmpFmt=" + tmpFmt);
        if (tmpFmt != null) {
            Set<String> vfkeys = tmpFmt.keySet();
            String[] tmpfk = (String[]) vfkeys.toArray(new String[vfkeys.size()]);
            String[] tmpfv = getValueSet(tmpFmt, tmpfk);
            c.assign("tmpfk", new REXPString(tmpfk));
            c.assign("tmpfv", new REXPString(tmpfv));
            String fmtNamesLine = "names(tmpfv)<- tmpfk";
            c.voidEval(fmtNamesLine);
            String fmtValuesLine = "varFmt<- as.list(tmpfv)";
            c.voidEval(fmtValuesLine);
        } else {
            String[] varFmtN = {};
            List<String> varFmtV = new ArrayList<String>();
            c.assign("varFmt", new REXPList(new RList(varFmtV, varFmtN)));
        }
        /*
        vnames<-c("race","age","vote")
        */

        // variable names
        // String [] jvnames = {"race","age","vote"};
        String[] jvnamesRaw = sro.getVariableNames();
        String[] jvnames = null;

        //VariableNameFilterForR nf = new VariableNameFilterForR(jvnamesRaw);

        if (sro.hasUnsafedVariableNames) {
            // create  list
            jvnames = sro.safeVarNames;
            dbgLog.fine("renamed=" + StringUtils.join(jvnames, ","));
        } else {
            jvnames = jvnamesRaw;
        }
        String vnQList = DvnDSButil.joinNelementsPerLine(jvnames, true);

        c.assign("vnames", new REXPString(jvnames));

        // confirmation
        String[] tmpjvnames = c.eval("vnames").asStrings();
        dbgLog.fine("vnames:" + StringUtils.join(tmpjvnames, ","));

        /*
        x<-read.table141vdc(file="/tmp/VDC/t.28948.1.tab", 
            col.names=vnames, colClassesx=vartyp, varFormat=varFmt)
        */

        //String datafilename = "/nfs/home/A/asone/java/rcode/t.28948.1.tab";

        // tab-delimited file name = tempFileName

        // Parameters:
        // file -> tempFileName
        // col.names -> Arrays.deepToString(new REXPString(jvnames)).asStrings())
        // colClassesx -> Arrays.deepToString((new REXPInteger(sro.getVariableTypes())).asStrings())
        // varFormat -> Arrays.deepToString((new REXPString(getValueSet(tmpFmt, tmpFmt.keySet().toArray(new String[tmpFmt.keySet().size()])))).asStrings())

        dbgLog.fine("<<<<<<<<<<<<<<<<<<<<<<<<<");
        dbgLog.fine("col.names = " + Arrays.deepToString((new REXPString(jvnames)).asStrings()));
        dbgLog.fine("colClassesx = "
                + Arrays.deepToString((new REXPInteger(sro.getVariableTypesWithBoolean())).asStrings()));
        dbgLog.fine("varFormat = " + Arrays.deepToString((new REXPString(
                getValueSet(tmpFmt, tmpFmt.keySet().toArray(new String[tmpFmt.keySet().size()]))))
                        .asStrings()));
        dbgLog.fine(">>>>>>>>>>>>>>>>>>>>>>>>>");

        String readtableline = "x<-read.table141vdc(file='" + tempFileName
                + "', col.names=vnames, colClassesx=vartyp, varFormat=varFmt )";
        dbgLog.fine("readtable=" + readtableline);

        c.voidEval(readtableline);

        // safe-to-raw variable name
        /* 
          attr(x, "Rsafe2raw")<-list();
        */
        //if (nf.hasRenamedVariables()){
        if (sro.hasUnsafedVariableNames) {
            dbgLog.fine("unsafeVariableNames exist");
            // create  list
            //jvnames = nf.getFilteredVarNames();
            jvnames = sro.safeVarNames;
            String[] rawNameSet = sro.renamedVariableArray;
            String[] safeNameSet = sro.renamedResultArray;

            c.assign("tmpRN", new REXPString(rawNameSet));
            c.assign("tmpSN", new REXPString(safeNameSet));

            String raw2safevarNameTableLine = "names(tmpRN)<- tmpSN";
            c.voidEval(raw2safevarNameTableLine);
            String attrRsafe2rawLine = "attr(x, 'Rsafe2raw')<- as.list(tmpRN)";
            c.voidEval(attrRsafe2rawLine);
        } else {
            String attrRsafe2rawLine = "attr(x, 'Rsafe2raw')<-list();";
            c.voidEval(attrRsafe2rawLine);
        }

        //Map<String, String> Rsafe2raw = sro.getRaw2SafeVarNameTable();

        // asIs
        /* 
        for (i in 1:dim(x)[2]){if (attr(x,"var.type")[i] == 0) {
        x[[i]]<-I(x[[i]]);  x[[i]][ x[[i]] == '' ]<-NA  }}
        */
        String asIsline = "for (i in 1:dim(x)[2]){ " + "if (attr(x,'var.type')[i] == 0) {"
                + "x[[i]]<-I(x[[i]]);  x[[i]][ x[[i]] == '' ]<-NA  }}";
        c.voidEval(asIsline);

        // replication: copy the data.frame
        String repDVN_Xdupline = "dvnData<-x";
        c.voidEval(repDVN_Xdupline);
        tmpResult.put("dvn_dataframe", "dvnData");

        // subsetting (mutating the data.frame strips non-default attributes 
        // 
        // variable type must be re-attached

        //String varTypeNew = "vartyp<-c(" + StringUtils.join( sro.getUpdatedVariableTypesAsString(),",")+")";
        // c.voidEval(varTypeNew);
        dbgLog.fine("updated var Type =" + sro.getUpdatedVariableTypes());
        c.assign("vartyp", new REXPInteger(sro.getUpdatedVariableTypes()));

        String reattachVarTypeLine = "attr(x, 'var.type') <- vartyp";
        c.voidEval(reattachVarTypeLine);

        // TODO: 
        // "getUpdatedVariableTypesWithBooleans" ?? -- L.A.

        // replication: variable type
        String repDVN_vt = "attr(dvnData, 'var.type') <- vartyp";
        c.voidEval(repDVN_vt);

        // variable Id
        /* 
        attr(x, "var.nmbr")<-c("v198057","v198059","v198060")
        */

        // String[] jvarnmbr = {"v198057","v198059","v198060"};
        //String[] jvarnmbr = sro.getVariableIds();
        // after recoding 
        String[] jvarnmbr = sro.getUpdatedVariableIds();

        String viQList = DvnDSButil.joinNelementsPerLine(jvarnmbr, true);
        c.assign("varnmbr", new REXPString(jvarnmbr));

        String attrVarNmbrLine = "attr(x, 'var.nmbr')<-varnmbr";
        c.voidEval(attrVarNmbrLine);

        // confirmation
        String[] vno = c.eval("attr(x, 'var.nmbr')").asStrings();
        dbgLog.fine("varNo=" + StringUtils.join(vno, ","));

        // replication: variable number
        String repDVN_vn = "attr(dvnData, 'var.nmbr') <- varnmbr";
        c.voidEval(repDVN_vn);

        // variable labels
        /* 
        attr(x, "var.labels")<-c("race","age","vote")
        */

        // String[] jvarlabels = {"race","age","vote"};
        // String[] jvarlabels = sro.getVariableLabels();
        // after recoding
        String[] jvarlabels = sro.getUpdatedVariableLabels();

        String vlQList = DvnDSButil.joinNelementsPerLine(jvarlabels, true);

        c.assign("varlabels", new REXPString(jvarlabels));

        String attrVarLabelsLine = "attr(x, 'var.labels')<-varlabels";
        c.voidEval(attrVarLabelsLine);

        // confirmation
        String[] vlbl = c.eval("attr(x, 'var.labels')").asStrings();
        dbgLog.fine("varlabels=" + StringUtils.join(vlbl, ","));

        // replication: 
        String repDVN_vl = "attr(dvnData, 'var.labels') <- varlabels";
        c.voidEval(repDVN_vl);

        // --------- start: block to be used for the production code
        // value-label table
        /* 
        VALTABLE<-list()
        VALTABLE[["1"]]<-list(
        "2"="white",
        "1"="others")
        attr(x, 'val.table')<-VALTABLE
        */

        // create the VALTABLE
        String vtFirstLine = "VALTABLE<-list()";
        c.voidEval(vtFirstLine);

        // vltbl includes both base and recoded cases when it was generated
        Map<String, Map<String, String>> vltbl = sro.getValueTable();
        Map<String, String> rnm2vi = sro.getRawVarNameToVarIdTable();
        String[] updatedVariableIds = sro.getUpdatedVariableIds();

        //for (int j=0;j<jvnamesRaw.length;j++){
        for (int j = 0; j < updatedVariableIds.length; j++) {
            // if this variable has its value-label table,
            // pass its key and value arrays to the Rserve
            // and finalize a value-table at the Rserve

            //String varId = rnm2vi.get(jvnamesRaw[j]);
            String varId = updatedVariableIds[j];

            if (vltbl.containsKey(varId)) {

                Map<String, String> tmp = (HashMap<String, String>) vltbl.get(varId);
                Set<String> vlkeys = tmp.keySet();
                String[] tmpk = (String[]) vlkeys.toArray(new String[vlkeys.size()]);
                String[] tmpv = getValueSet(tmp, tmpk);
                // debug
                dbgLog.fine("tmp:k=" + StringUtils.join(tmpk, ","));
                dbgLog.fine("tmp:v=" + StringUtils.join(tmpv, ","));

                // index number starts from 1(not 0)
                int indx = j + 1;
                dbgLog.fine("index=" + indx);

                if (tmpv.length > 0) {

                    c.assign("tmpk", new REXPString(tmpk));

                    c.assign("tmpv", new REXPString(tmpv));

                    String namesValueLine = "names(tmpv)<- tmpk";
                    c.voidEval(namesValueLine);

                    String sbvl = "VALTABLE[['" + Integer.toString(indx) + "']]" + "<- as.list(tmpv)";
                    dbgLog.fine("frag=" + sbvl);
                    c.voidEval(sbvl);

                    // confirmation test for j-th variable name
                    REXP jl = c.parseAndEval(sbvl);
                    dbgLog.fine("jl(" + j + ") = " + jl);
                }
            }
        }

        // debug: confirmation test for value-table
        dbgLog.fine("length of vl=" + c.eval("length(VALTABLE)").asInteger());
        String attrValTableLine = "attr(x, 'val.table')<-VALTABLE";
        c.voidEval(attrValTableLine);

        // replication: value-label table
        String repDVN_vlt = "attr(dvnData, 'val.table') <- VALTABLE";
        c.voidEval(repDVN_vlt);

        // --------- end: block to be used for the production code

        // missing-value list: TO DO
        /*
        MSVLTBL<-list(); attr(x, 'missval.table')<-MSVLTBL
        */
        String msvStartLine = "MSVLTBL<-list();";
        c.voidEval(msvStartLine);
        // data structure
        String attrMissvalLine = "attr(x, 'missval.table')<-MSVLTBL";
        c.voidEval(attrMissvalLine);

        // replication: missing value table
        String repDVN_mvlt = "attr(dvnData, 'missval.table') <- MSVLTBL";
        c.voidEval(repDVN_mvlt);

        // attach attributes(tables) to the data.frame
        /*
        x<-createvalindex(dtfrm=x, attrname='val.index')
        x<-createvalindex(dtfrm=x, attrname='missval.index')
        */
        String createVIndexLine = "x<-createvalindex(dtfrm=x, attrname='val.index');";
        c.voidEval(createVIndexLine);
        String createMVIndexLine = "x<-createvalindex(dtfrm=x, attrname='missval.index');";
        c.voidEval(createMVIndexLine);

        // reflection block: start ------------------------------------------>

        String requestTypeToken = sro.getRequestType();// (Download|EDA|Xtab|Zelig)
        dbgLog.fine("requestTypeToken=" + requestTypeToken);
        // get a test method
        Method mthd = runMethods.get(requestTypeToken);
        dbgLog.fine("method=" + mthd);

        try {
            // invoke this method
            result = (Map<String, String>) mthd.invoke(this, sro, c);
        } catch (InvocationTargetException e) {
            //Throwable cause = e.getCause();
            //err.format(cause.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // add the variable list
        result.put("variableList", joinNelementsPerLine(jvnamesRaw, 5, null, false, null, null));

        //result.put("variableList",StringUtils.join(jvnamesRaw, ", "));

        // replication: var-level unf
        String repDVN_varUNF = "attr(dvnData, 'variableUNF') <- paste(unf(dvnData,version=3))";
        c.voidEval(repDVN_varUNF);

        // calculate the file-leve UNF

        String fileUNFline = "fileUNF <- paste(summary(unf(dvnData, version=3)))";
        c.voidEval(fileUNFline);
        String fileUNF = c.eval("fileUNF").asString();
        if (fileUNF == null) {
            fileUNF = "NA";
        }

        // replication: file-level unf
        String repDVN_fileUNF = "attr(dvnData, 'fileUNF') <- fileUNF";
        c.voidEval(repDVN_fileUNF);

        String RversionLine = "R.Version()$version.string";
        String Rversion = c.eval(RversionLine).asString();

        // replication: R version
        String repDVN_Rversion = "attr(dvnData, 'R.version') <- R.Version()$version.string";
        c.voidEval(repDVN_Rversion);

        String zeligVersionLine = "packageDescription('Zelig')$Version";
        String zeligVersion = c.eval(zeligVersionLine).asString();

        //String RexecDate = c.eval("date()").asString();
        String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString();
        // replication: date
        String repDVN_date = "attr(dvnData, 'date') <- as.character(as.POSIXct(Sys.time()))";
        c.voidEval(repDVN_date);

        String repDVN_dfOrigin = "attr(dvnData, 'data.frame.origin')<- "
                + "list('provider'='Dataverse Network Project',"
                + "'format' = list('name' = 'DVN data.frame', 'version'='1.3'))";
        c.voidEval(repDVN_dfOrigin);
        /*
        if (result.containsKey("option")){
        result.put("R_run_status", "T");
        } else {
        result.put("option", requestTypeToken.toLowerCase()); //download  zelig eda xtab
        result.put("R_run_status", "F");
        }
        */
        if (sro.hasRecodedVariables()) {
            if (sro.getSubsetConditions() != null) {
                result.put("subsettingCriteria", StringUtils.join(sro.getSubsetConditions(), "\n"));
                // replication: subset lines
                String[] sbst = null;
                sbst = (String[]) sro.getSubsetConditions()
                        .toArray(new String[sro.getSubsetConditions().size()]);

                c.assign("sbstLines", new REXPString(sbst));

                String repDVN_sbst = "attr(dvnData, 'subsetLines') <- sbstLines";
                c.voidEval(repDVN_sbst);
            }
            /* to be used in the future? */
            if (sro.getRecodeConditions() != null) {
                result.put("recodingCriteria", StringUtils.join(sro.getRecodeConditions(), "\n"));
                String[] rcd = null;
                rcd = (String[]) sro.getRecodeConditions()
                        .toArray(new String[sro.getRecodeConditions().size()]);

                c.assign("rcdtLines", new REXPString(rcd));

                String repDVN_rcd = "attr(dvnData, 'recodeLines') <- rcdtLines";
                c.voidEval(repDVN_rcd);
            }

        }

        // save workspace as a replication data set

        String RdataFileName = "DVNdataFrame." + PID + ".RData";
        result.put("Rdata", "/" + requestdir + "/" + RdataFileName);

        String saveWS = "save('dvnData', file='" + wrkdir + "/" + RdataFileName + "')";
        dbgLog.fine("save the workspace=" + saveWS);
        c.voidEval(saveWS);

        // write back the R workspace to the dvn 

        String wrkspFileName = wrkdir + "/" + RdataFileName;
        dbgLog.fine("wrkspFileName=" + wrkspFileName);

        int wrkspflSize = getFileSize(c, wrkspFileName);

        File wsfl = writeBackFileToDvn(c, wrkspFileName, RWRKSP_FILE_PREFIX, "RData", wrkspflSize);

        result.put("dvn_RData_FileName", wsfl.getName());

        if (wsfl != null) {
            result.put("wrkspFileName", wsfl.getAbsolutePath());
            dbgLog.fine("wrkspFileName=" + wsfl.getAbsolutePath());
        } else {
            dbgLog.fine("wrkspFileName is null");
        }

        result.put("library_1", "VDCutil");

        result.put("fileUNF", fileUNF);
        result.put("dsbHost", RSERVE_HOST);
        result.put("dsbPort", DSB_HOST_PORT);
        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("Rversion", Rversion);
        result.put("zeligVersion", zeligVersion);
        result.put("RexecDate", RexecDate);

        result.putAll(tmpResult);
        dbgLog.fine("result object (before closing the Rserve):\n" + result);

        // reflection block: end

        // close the Rserve connection
        c.close();

    } catch (RserveException rse) {
        // RserveException (Rserve is not running)
        rse.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (REXPMismatchException mme) {

        // REXP mismatch exception (what we got differs from what we expected)
        mme.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (IOException ie) {
        ie.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (Exception ex) {
        ex.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);

        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;
    }

    return result;

}

From source file:org.pentaho.ui.xul.swt.tags.SwtTree.java

protected void onSwtDragOver(DropTargetEvent dropEvent) {

    dropEvent.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
    if (dropEvent.item != null) {
        Rectangle bounds = null;// ww  w  .  j  a  va  2  s  .  c  o  m
        Point pt = null;
        if (isHierarchical()) {
            TreeItem item = (TreeItem) dropEvent.item;
            pt = tree.getControl().getDisplay().map(null, tree.getControl(), dropEvent.x, dropEvent.y);
            bounds = item.getBounds();
        } else {
            TableItem item = (TableItem) dropEvent.item;
            pt = table.getControl().getDisplay().map(null, table.getControl(), dropEvent.x, dropEvent.y);
            bounds = item.getBounds();
        }

        if (pt.y < bounds.y + bounds.height / 3) {
            curPos = DropPosition.ABOVE;
        } else if (pt.y > bounds.y + 2 * (bounds.height / 3)) {
            curPos = DropPosition.BELOW;
        } else {
            curPos = DropPosition.MIDDLE;
        }

        resolveDropVetoerMethod();

        DropEvent event = SwtDragManager.getInstance().getCurrentDropEvent();
        if (dropVetoerMethod != null) {

            XulTreeItem xulItem = (XulTreeItem) dropEvent.item.getData();

            if (curPos == DropPosition.MIDDLE) {
                event.setDropParent(xulItem.getBoundObject());
            } else {

                XulComponent parent = xulItem.getParent().getParent();
                Object parentObj;
                if (parent instanceof SwtTree) {
                    parentObj = SwtTree.this.elements;
                } else {
                    parentObj = ((XulTreeItem) parent).getBoundObject();
                }
                event.setDropParent(parentObj);
            }

            event.setNativeEvent(dropEvent);
            event.setAccepted(true);

            resolveDndParentAndIndex(event);

            event.setDropPosition(curPos);

            // if(curPos == DropPosition.MIDDLE){
            // event.setDropParent(xulItem.getBoundObject());
            // } else {
            //
            // XulComponent parent = xulItem.getParent().getParent();
            // Object parentObj;
            // if(parent instanceof GwtTree){
            // parentObj = GwtTree.this.elements;
            // } else {
            // parentObj = ((XulTreeItem) parent).getBoundObject();
            // }
            // event.setDropParent(parentObj);
            // }

            try {
                // Consult Vetoer method to see if this is a valid drop operation
                dropVetoerMethod.invoke(dropVetoerController, new Object[] { event });

            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (event.isAccepted() == false) {
            dropEvent.feedback = DND.FEEDBACK_NONE;
        } else if (pt.y < bounds.y + bounds.height / 3) {
            dropEvent.feedback |= DND.FEEDBACK_INSERT_BEFORE;
        } else if (pt.y > bounds.y + 2 * (bounds.height / 3)) {
            dropEvent.feedback |= DND.FEEDBACK_INSERT_AFTER;
        } else {
            dropEvent.feedback |= DND.FEEDBACK_SELECT;
        }

    }

}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRDataAnalysisServiceImpl.java

/** *************************************************************
 * Execute an R-based dvn statistical analysis request 
 *
 * @param sro    a DvnRJobRequest object that contains various parameters
 * @return    a Map that contains various information about results
 *///w  w  w  .j a va  2s . c  om

public Map<String, String> execute(DvnRJobRequest sro) {

    // Step 1. Copy of Rdata file
    // Step 2. Subset Rdata file
    // Step 3. Return the subsetted Rdata file instead of the original

    // set the return object
    Map<String, String> result = new HashMap<String, String>();
    // temporary result
    Map<String, String> tmpResult = new HashMap<String, String>();

    try {
        // Set up an Rserve connection
        dbgLog.info("sro dump:\n" + ToStringBuilder.reflectionToString(sro, ToStringStyle.MULTI_LINE_STYLE));

        dbgLog.fine("RSERVE_USER=" + RSERVE_USER + "[default=rserve]");
        dbgLog.fine("RSERVE_PWD=" + RSERVE_PWD + "[default=rserve]");
        dbgLog.fine("RSERVE_PORT=" + RSERVE_PORT + "[default=6311]");

        RConnection c = new RConnection(RSERVE_HOST, RSERVE_PORT);
        dbgLog.fine("hostname=" + RSERVE_HOST);

        c.login(RSERVE_USER, RSERVE_PWD);
        dbgLog.info("R Version = " + c.eval("R.version$version.string").asString() + "<");
        dbgLog.info("SRO request type: " + sro.getRequestType());

        // check working directories
        // This needs to be done *before* we try to create any files 
        // there!
        setupWorkingDirectories(c);

        // save the data file at the Rserve side
        String infile = sro.getSubsetFileName();

        InputStream inb = new BufferedInputStream(new FileInputStream(infile));

        int bufsize;
        byte[] bffr = new byte[1024];

        RFileOutputStream os = c.createFile(tempFileName);
        while ((bufsize = inb.read(bffr)) != -1) {
            os.write(bffr, 0, bufsize);
        }
        os.close();
        inb.close();

        // save the original data file on the server-side

        // WORKS STARTS HERE
        // os = c.createFile(tempOriginalFileName);

        // Rserve code starts here
        dbgLog.fine("DvnRserveComm: " + "wrkdir=" + wrkdir);
        //dbgLog.fine("DvnRserveComm: "+librarySetup);
        //historyEntry.add(librarySetup);
        //c.voidEval(librarySetup);

        Properties p = System.getProperties();
        String domainRoot = p.getProperty("com.sun.aas.instanceRoot");
        String rFunctionsFileName = domainRoot + "/config/" + DVN_R_DATA_FUNCTIONS;

        dbgLog.fine("Source code for the custom DVN R functions: " + rFunctionsFileName);

        File rFunctionsFile = new File(rFunctionsFileName);
        if (!rFunctionsFile.exists()) {
            throw new IOException("Could not find R source code file " + rFunctionsFileName);
        }

        /* 
         * Send the R code file across:
         */

        inb = new BufferedInputStream(new FileInputStream(rFunctionsFile));

        os = c.createFile(tempRCodeFileName);
        while ((bufsize = inb.read(bffr)) != -1) {
            os.write(bffr, 0, bufsize);
        }
        os.close();
        inb.close();

        /* 
         * And read it in: 
         */

        String newLibrarySetup = "source(\"" + tempRCodeFileName + "\");";
        dbgLog.fine("DvnRserveComm: " + newLibrarySetup);
        historyEntry.add(newLibrarySetup);
        c.voidEval(newLibrarySetup);
        dbgLog.fine("DVN R Code library has been read.");

        // variable type
        /* 
        vartyp <-c(1,1,1)
        */
        // java side
        // int [] jvartyp  = {1,1,1};// = mp.get("vartyp").toArray()
        // int [] jvartyp  = sro.getVariableTypes();
        /*
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0 ; i< jvartyp.length; i++){
        if (i == (jvartyp.length -1)){
            sb.append(String.valueOf(jvartyp[i]));
        } else {
            sb.append(String.valueOf(jvartyp[i])+", ");
        }
                    }
                            
                    // R side
                    historyEntry.add("vartyp<-c(" + sb.toString()+")");
        */

        //c.assign("vartyp", new REXPInteger(jvartyp));
        if ("Download".equals(sro.getRequestType())) {
            /*
             * Note that we want to use the "getVariableTypesWithBoolean method 
             * when the subset is being created for download/conversion; when 
             * we create a SRO object for analysis, we'll still be using 
             * the old getVariableTypes
             * method, that don't recognize Booleans as a distinct class. 
             * So they will be treated simply as numeric categoricals 
             * (factors) with the "TRUE" and "FALSE" labels. But for the purposes
             * of saving the subset in R format, we want to convert these into
             * R "logical" vectors.
             * 
             * TODO: verify what's going to happen to these "logical"
             * variables when we call R package Foreign to convert the 
             * dataset into STATA format. -- L.A. 
             */

            dbgLog.fine("raw variable type=" + sro.getVariableTypesWithBoolean());
            c.assign("vartyp", new REXPInteger(sro.getVariableTypesWithBoolean()));
            String[] tmpt = c.eval("vartyp").asStrings();
            dbgLog.fine("vartyp length=" + tmpt.length + "\t " + StringUtils.join(tmpt, ","));

        } else {
            historyEntry.add("vartyp<-c(" + StringUtils.join(sro.getVariableTypesAsString(), ",") + ")");
            dbgLog.fine("DvnRserveComm: " + "vartyp<-c(" + StringUtils.join(sro.getVariableTypesAsString(), ",")
                    + ")");

            dbgLog.fine("raw variable type=" + sro.getVariableTypes());
            c.assign("vartyp", new REXPInteger(sro.getVariableTypes()));
            String[] tmpt = c.eval("vartyp").asStrings();
            dbgLog.fine(
                    "DvnRserveComm: " + "vartyp length=" + tmpt.length + "\t " + StringUtils.join(tmpt, ","));
        }

        // variable format (date/time)
        /* 
        varFmt<-list();
        c.voidEval("varFmt<-list()");
        */

        Map<String, String> tmpFmt = sro.getVariableFormats();
        dbgLog.fine("DvnRserveComm: " + "tmpFmt=" + tmpFmt);
        if (tmpFmt != null) {
            Set<String> vfkeys = tmpFmt.keySet();
            String[] tmpfk = (String[]) vfkeys.toArray(new String[vfkeys.size()]);
            String[] tmpfv = getValueSet(tmpFmt, tmpfk);
            historyEntry.add("tmpfk<-c(" + StringUtils.join(tmpfk, ", ") + ")");
            dbgLog.fine("DvnRserveComm: " + "tmpfk<-c(" + StringUtils.join(tmpfk, ", ") + ")");

            c.assign("tmpfk", new REXPString(tmpfk));
            historyEntry.add("tmpfv<-c(" + StringUtils.join(tmpfv, ", ") + ")");
            dbgLog.fine("DvnRserveComm: " + "tmpfv<-c(" + StringUtils.join(tmpfv, ", ") + ")");
            c.assign("tmpfv", new REXPString(tmpfv));
            String fmtNamesLine = "names(tmpfv)<- tmpfk";
            historyEntry.add(fmtNamesLine);

            dbgLog.fine("DvnRserveComm: " + fmtNamesLine);
            c.voidEval(fmtNamesLine);

            String fmtValuesLine = "varFmt<- as.list(tmpfv)";
            historyEntry.add(fmtValuesLine);

            dbgLog.fine("DvnRserveComm: " + fmtValuesLine);
            c.voidEval(fmtValuesLine);
        } else {
            String[] varFmtN = {};
            List<String> varFmtV = new ArrayList<String>();
            historyEntry.add("varFmt <- list()");

            dbgLog.fine("DvnRserveComm: " + "varFmt <- list()");
            c.assign("varFmt", new REXPList(new RList(varFmtV, varFmtN)));
        }
        /*
        vnames<-c("race","age","vote")
        */

        // variable names
        // String [] jvnames = {"race","age","vote"};

        String[] jvnamesRaw = sro.getVariableNames();
        String[] jvnames = null;

        //VariableNameFilterForR nf = new VariableNameFilterForR(jvnamesRaw);

        if (sro.hasUnsafedVariableNames) {
            // create  list
            jvnames = sro.safeVarNames;
            dbgLog.fine("renamed=" + StringUtils.join(jvnames, ","));
        } else {
            jvnames = jvnamesRaw;
        }
        //historyEntry.add("vnamnes<-c("+ StringUtils.join(jvnames, ", ")+")");
        String vnQList = DvnDSButil.joinNelementsPerLine(jvnames, true);
        historyEntry.add("vnames<-c(" + vnQList + ")");

        c.assign("vnames", new REXPString(jvnames));

        // confirmation
        String[] tmpjvnames = c.eval("vnames").asStrings();
        dbgLog.fine("DvnRserveComm: " + "vnames:" + StringUtils.join(tmpjvnames, ","));

        /*
        x<-read.table141vdc(file="/tmp/VDC/t.28948.1.tab", 
            col.names=vnames, colClassesx=vartyp, varFormat=varFmt)
        */

        //String datafilename = "/nfs/home/A/asone/java/rcode/t.28948.1.tab";

        // tab-delimited file name = tempFileName

        // vnames = Arrays.deepToString(new REXPString(jvnames).asStrings())
        // vartyp = Arrays.deepToString(new REXPInteger(sro.getUpdatedVariableTypes()).asStrings())
        // varFmt = 
        dbgLog.fine("col names ..... " + Arrays.deepToString(jvnames));
        dbgLog.fine("colClassesX ... " + Arrays.toString(sro.getVariableTypesWithBoolean()));
        dbgLog.fine("varFormat ..... " + tmpFmt);

        String readtableline = "x<-read.table141vdc(file='" + tempFileName
                + "', col.names=vnames, colClassesx=vartyp, varFormat=varFmt )";

        historyEntry.add(readtableline);
        dbgLog.fine("DvnRserveComm: " + "readtable=" + readtableline);

        c.voidEval(readtableline);

        // safe-to-raw variable name
        /* 
          attr(x, "Rsafe2raw")<-list();
        */
        //if (nf.hasRenamedVariables()){
        if (sro.hasUnsafedVariableNames) {
            dbgLog.fine("unsafeVariableNames exist");
            // create  list
            //jvnames = nf.getFilteredVarNames();
            jvnames = sro.safeVarNames;
            String[] rawNameSet = sro.renamedVariableArray;
            String[] safeNameSet = sro.renamedResultArray;

            historyEntry.add("tmpRN<-c(" + StringUtils.join(rawNameSet, ", ") + ")");
            c.assign("tmpRN", new REXPString(rawNameSet));
            historyEntry.add("tmpSN<-c(" + StringUtils.join(safeNameSet, ", ") + ")");
            c.assign("tmpSN", new REXPString(safeNameSet));

            String raw2safevarNameTableLine = "names(tmpRN)<- tmpSN";
            historyEntry.add(raw2safevarNameTableLine);
            c.voidEval(raw2safevarNameTableLine);
            String attrRsafe2rawLine = "attr(x, 'Rsafe2raw')<- as.list(tmpRN)";
            historyEntry.add(attrRsafe2rawLine);
            c.voidEval(attrRsafe2rawLine);
        } else {
            String attrRsafe2rawLine = "attr(x, 'Rsafe2raw')<-list();";
            historyEntry.add(attrRsafe2rawLine);
            c.voidEval(attrRsafe2rawLine);
        }

        //Map<String, String> Rsafe2raw = sro.getRaw2SafeVarNameTable();

        // asIs
        /* 
        for (i in 1:dim(x)[2]){if (attr(x,"var.type")[i] == 0) {
        x[[i]]<-I(x[[i]]);  x[[i]][ x[[i]] == '' ]<-NA  }}
        */

        /* 
         * Commenting out the fragment below: 
         * - this is now being done early on in the read.table141vdc
         *   R function:
                 
        String asIsline  = "for (i in 1:dim(x)[2]){ "+
        "if (attr(x,'var.type')[i] == 0) {" +
        "x[[i]]<-I(x[[i]]);  x[[i]][ x[[i]] == '' ]<-NA  }}";
        historyEntry.add(asIsline);
        c.voidEval(asIsline);
        */

        // replication: copy the data.frame
        String repDVN_Xdupline = "dvnData<-x";
        c.voidEval(repDVN_Xdupline);
        tmpResult.put("dvn_dataframe", "dvnData");

        // recoding line
        if (sro.hasRecodedVariables()) {

            // subsetting 

            // For operations on time values during recoding we need
            // to set the following option (this is to enable millisecond
            // precision time): 
            //      -- L.A., v3.6

            c.voidEval("saved.options <- options(digits.secs = 3)");

            List<String> scLst = sro.getSubsetConditions();
            if (scLst != null) {
                for (String sci : scLst) {
                    dbgLog.fine("sci:" + sci);
                    historyEntry.add(sci);
                    c.voidEval(sci);
                }
                tmpResult.put("subset", "T");
            }
            // recoding

            List<String> rcLst = sro.getRecodeConditions();
            if (rcLst != null) {
                for (String rci : rcLst) {
                    dbgLog.fine("rci:" + rci);

                    historyEntry.add(rci);
                    c.voidEval(rci);
                }

                // subsetting (mutating the data.frame strips non-default attributes 
                // 
                // variable type must be re-attached

                if (!"Download".equals(sro.getRequestType())) {
                    String varTypeNew = "vartyp<-c("
                            + StringUtils.join(sro.getUpdatedVariableTypesAsString(), ",") + ")";
                    historyEntry.add(varTypeNew);
                    dbgLog.fine("updated var Type =" + sro.getUpdatedVariableTypesAsString());
                    c.assign("vartyp", new REXPInteger(sro.getUpdatedVariableTypes()));
                } else {
                    dbgLog.fine("updated var Type =" + sro.getUpdatedVariableTypesWithBooleanAsString());
                    c.assign("vartyp", new REXPInteger(sro.getUpdatedVariableTypesWithBoolean()));
                }

                String reattachVarTypeLine = "attr(x, 'var.type') <- vartyp";
                historyEntry.add(reattachVarTypeLine);

                dbgLog.fine("DvnRserveComm: " + reattachVarTypeLine);
                c.voidEval(reattachVarTypeLine);

                // replication: variable type
                String repDVN_vt = "attr(dvnData, 'var.type') <- vartyp";

                dbgLog.fine("DvnRserveComm: " + repDVN_vt);
                c.voidEval(repDVN_vt);

                // new (recoded) variable names: 
                String varNamesRecoded = "recodedvnames<-c(" + StringUtils.join(sro.getRecodedVarNameSet(), ",")
                        + ")";
                historyEntry.add(varNamesRecoded);
                dbgLog.fine("recoded var names =" + StringUtils.join(sro.getRecodedVarNameSet(), ","));
                c.assign("recodedvnames", sro.getRecodedVarNameSet());

                tmpFmt = sro.getUpdatedVariableFormats();
                dbgLog.fine("DvnRserveComm: " + "(recoded)tmpFmt=" + tmpFmt);
                if (tmpFmt != null) {
                    Set<String> vfkeys = tmpFmt.keySet();
                    String[] tmpfk = (String[]) vfkeys.toArray(new String[vfkeys.size()]);
                    String[] tmpfv = getValueSet(tmpFmt, tmpfk);
                    historyEntry.add("tmpfk<-c(" + StringUtils.join(tmpfk, ", ") + ")");
                    dbgLog.fine("DvnRserveComm: " + "(recoded)tmpfk<-c(" + StringUtils.join(tmpfk, ", ") + ")");

                    c.assign("tmpfk", new REXPString(tmpfk));
                    historyEntry.add("tmpfv<-c(" + StringUtils.join(tmpfv, ", ") + ")");
                    dbgLog.fine("DvnRserveComm: " + "(recoded)tmpfv<-c(" + StringUtils.join(tmpfv, ", ") + ")");
                    c.assign("tmpfv", new REXPString(tmpfv));
                    String fmtNamesLine = "names(tmpfv)<- tmpfk";
                    historyEntry.add(fmtNamesLine);

                    dbgLog.fine("DvnRserveComm: (recoded)" + fmtNamesLine);
                    c.voidEval(fmtNamesLine);

                    String fmtValuesLine = "varFmt<- as.list(tmpfv)";
                    historyEntry.add(fmtValuesLine);

                    dbgLog.fine("DvnRserveComm: (recoded)" + fmtValuesLine);
                    c.voidEval(fmtValuesLine);
                } else {
                    String[] varFmtN = {};
                    List<String> varFmtV = new ArrayList<String>();
                    historyEntry.add("varFmt <- list()");

                    dbgLog.fine("DvnRserveComm: (recoded)" + "varFmt <- list()");
                    c.assign("varFmt", new REXPList(new RList(varFmtV, varFmtN)));
                }

                // run post-processing on the newly created recode variables:
                dbgLog.fine("running transformrecoded()");

                historyEntry.add("transformrecoded()");
                int recodedVarsStartIndex = sro.getVariableNames().length + 1;
                dbgLog.fine("recoded variables start at " + recodedVarsStartIndex);
                c.voidEval("x<-transformrecoded(x, recodedvarsindx=" + recodedVarsStartIndex
                        + ", col.names=c(vnames,recodedvnames), colClassesx=vartyp, varFormat=varFmt)");
            }

            // reset the milliseconds option: 

            c.voidEval("options(saved.options)");
        }

        // variable Id
        /* 
        attr(x, "var.nmbr")<-c("v198057","v198059","v198060")
        */

        // String[] jvarnmbr = {"v198057","v198059","v198060"};
        //String[] jvarnmbr = sro.getVariableIds();
        // after recoding 
        String[] jvarnmbr = sro.getUpdatedVariableIds();

        String viQList = DvnDSButil.joinNelementsPerLine(jvarnmbr, true);
        historyEntry.add("varnmbr <-c(" + viQList + ")");
        c.assign("varnmbr", new REXPString(jvarnmbr));

        String attrVarNmbrLine = "attr(x, 'var.nmbr')<-varnmbr";
        historyEntry.add(attrVarNmbrLine);

        dbgLog.fine("DvnRserveComm: (varnmbr) " + attrVarNmbrLine);
        c.voidEval(attrVarNmbrLine);

        // confirmation
        String[] vno = c.eval("attr(x, 'var.nmbr')").asStrings();
        dbgLog.fine("varNo=" + StringUtils.join(vno, ","));

        // replication: variable number
        String repDVN_vn = "attr(dvnData, 'var.nmbr') <- varnmbr";

        dbgLog.fine("DvnRserveComm: " + repDVN_vn);
        c.voidEval(repDVN_vn);

        // variable labels
        /* 
        attr(x, "var.labels")<-c("race","age","vote")
        */

        // String[] jvarlabels = {"race","age","vote"};
        // String[] jvarlabels = sro.getVariableLabels();
        // after recoding
        String[] jvarlabels = sro.getUpdatedVariableLabels();

        String vlQList = DvnDSButil.joinNelementsPerLine(jvarlabels, true);

        historyEntry.add("varlabels <-c(" + vlQList + ")");

        dbgLog.fine("DvnRserveComm: " + "varlabels <-c(" + vlQList + ")");
        c.assign("varlabels", new REXPString(jvarlabels));

        String attrVarLabelsLine = "attr(x, 'var.labels')<-varlabels";
        historyEntry.add(attrVarLabelsLine);

        dbgLog.fine("DvnRserveComm: " + attrVarLabelsLine);
        c.voidEval(attrVarLabelsLine);

        // confirmation
        String[] vlbl = c.eval("attr(x, 'var.labels')").asStrings();
        dbgLog.fine("varlabels=" + StringUtils.join(vlbl, ","));

        // replication: 
        String repDVN_vl = "attr(dvnData, 'var.labels') <- varlabels";

        dbgLog.fine("DvnRserveComm: " + repDVN_vl);
        c.voidEval(repDVN_vl);

        // --------- start: block to be used for the production code
        // value-label table
        /* 
        VALTABLE<-list()
        VALTABLE[["1"]]<-list(
        "2"="white",
        "1"="others")
        attr(x, 'val.table')<-VALTABLE
        */

        // create the VALTABLE
        String vtFirstLine = "VALTABLE<-list()";
        historyEntry.add(vtFirstLine);

        dbgLog.fine("DvnRserveComm: " + vtFirstLine);
        c.voidEval(vtFirstLine);

        c.voidEval("VALORDER<-list()");

        // vltbl includes both base and recoded cases when it was generated
        Map<String, Map<String, String>> vltbl = sro.getValueTable();
        Map<String, List<String>> orderedCategoryValues = sro.getCategoryValueOrders();
        Map<String, String> rnm2vi = sro.getRawVarNameToVarIdTable();
        String[] updatedVariableIds = sro.getUpdatedVariableIds();

        //for (int j=0;j<jvnamesRaw.length;j++){
        for (int j = 0; j < updatedVariableIds.length; j++) {
            // if this variable has its value-label table,
            // pass its key and value arrays to the Rserve
            // and finalize a value-table at the Rserve

            //String varId = rnm2vi.get(jvnamesRaw[j]);
            String varId = updatedVariableIds[j];

            if (vltbl.containsKey(varId)) {

                Map<String, String> tmp = (HashMap<String, String>) vltbl.get(varId);
                Set<String> vlkeys = tmp.keySet();
                String[] tmpk = (String[]) vlkeys.toArray(new String[vlkeys.size()]);
                String[] tmpv = getValueSet(tmp, tmpk);
                // debug
                dbgLog.fine("tmp:k=" + StringUtils.join(tmpk, ","));
                dbgLog.fine("tmp:v=" + StringUtils.join(tmpv, ","));

                // index number starts from 1(not 0)
                int indx = j + 1;
                dbgLog.fine("index=" + indx);

                if (tmpv.length > 0) {

                    historyEntry.add("tmpk<-c(" + DvnDSButil.joinNelementsPerLine(tmpk, true) + ")");
                    c.assign("tmpk", new REXPString(tmpk));

                    historyEntry.add("tmpv<-c(" + DvnDSButil.joinNelementsPerLine(tmpv, true) + ")");
                    c.assign("tmpv", new REXPString(tmpv));

                    String namesValueLine = "names(tmpv)<- tmpk";
                    historyEntry.add(namesValueLine);
                    c.voidEval(namesValueLine);

                    String sbvl = "VALTABLE[['" + Integer.toString(indx) + "']]" + "<- as.list(tmpv)";
                    dbgLog.fine("frag=" + sbvl);
                    historyEntry.add(sbvl);
                    c.voidEval(sbvl);

                    // confirmation test for j-th variable name
                    REXP jl = c.parseAndEval(sbvl);
                    dbgLog.fine("jl(" + j + ") = " + jl);
                }
            }

            if (orderedCategoryValues != null && orderedCategoryValues.containsKey(varId)) {
                int indx = j + 1;
                List<String> orderList = orderedCategoryValues.get(varId);
                if (orderList != null) {
                    String[] ordv = (String[]) orderList.toArray(new String[orderList.size()]);
                    dbgLog.fine("ordv=" + StringUtils.join(ordv, ","));
                    c.assign("ordv", new REXPString(ordv));
                    String sbvl = "VALORDER[['" + Integer.toString(indx) + "']]" + "<- as.list(ordv)";
                    dbgLog.fine("VALORDER[...]=" + sbvl);
                    historyEntry.add(sbvl);
                    c.voidEval(sbvl);
                } else {
                    dbgLog.fine("NULL orderedCategoryValues list.");
                }
            }
        }

        // debug: confirmation test for value-table
        dbgLog.fine("length of vl=" + c.eval("length(VALTABLE)").asInteger());
        String attrValTableLine = "attr(x, 'val.table')<-VALTABLE";
        historyEntry.add(attrValTableLine);
        c.voidEval(attrValTableLine);

        // replication: value-label table
        String repDVN_vlt = "attr(dvnData, 'val.table') <- VALTABLE";
        c.voidEval(repDVN_vlt);

        // --------- end: block to be used for the production code

        // missing-value list: TO DO
        /*
        MSVLTBL<-list(); attr(x, 'missval.table')<-MSVLTBL
        */
        String msvStartLine = "MSVLTBL<-list();";
        historyEntry.add(msvStartLine);
        c.voidEval(msvStartLine);
        // data structure
        String attrMissvalLine = "attr(x, 'missval.table')<-MSVLTBL";
        historyEntry.add(attrMissvalLine);
        c.voidEval(attrMissvalLine);

        // replication: missing value table
        String repDVN_mvlt = "attr(dvnData, 'missval.table') <- MSVLTBL";
        c.voidEval(repDVN_mvlt);

        // attach attributes(tables) to the data.frame
        /*
        x<-createvalindex(dtfrm=x, attrname='val.index')
        x<-createvalindex(dtfrm=x, attrname='missval.index')
        */
        String createVIndexLine = "x<-createvalindex(dtfrm=x, attrname='val.index');";
        historyEntry.add(createVIndexLine);
        c.voidEval(createVIndexLine);
        String createMVIndexLine = "x<-createvalindex(dtfrm=x, attrname='missval.index');";
        historyEntry.add(createMVIndexLine);
        c.voidEval(createMVIndexLine);

        // reflection block: start ------------------------------------------>

        String requestTypeToken = sro.getRequestType();// (Download|EDA|Xtab|Zelig)
        dbgLog.fine("requestTypeToken=" + requestTypeToken);
        historyEntry.add("#### The Request is " + requestTypeToken + " ####");
        // get a test method
        Method mthd = runMethods.get(requestTypeToken);
        dbgLog.fine("method=" + mthd);

        try {
            // invoke this method
            result = (Map<String, String>) mthd.invoke(this, sro, c);
        } catch (InvocationTargetException e) {
            //Throwable cause = e.getCause();
            //err.format(cause.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        // add the variable list
        result.put("variableList", joinNelementsPerLine(jvnamesRaw, 5, null, false, null, null));

        //result.put("variableList",StringUtils.join(jvnamesRaw, ", "));

        // replication: var-level unf
        String repDVN_varUNF = "attr(dvnData, 'variableUNF') <- paste(unf(dvnData,version=3))";
        c.voidEval(repDVN_varUNF);

        // calculate the file-leve UNF

        String fileUNFline = "fileUNF <- paste(summary(unf(dvnData, version=3)))";
        c.voidEval(fileUNFline);
        String fileUNF = c.eval("fileUNF").asString();
        if (fileUNF == null) {
            fileUNF = "NA";
        }

        // replication: file-level unf
        String repDVN_fileUNF = "attr(dvnData, 'fileUNF') <- fileUNF";
        c.voidEval(repDVN_fileUNF);

        String RversionLine = "R.Version()$version.string";
        String Rversion = c.eval(RversionLine).asString();

        dbgLog.fine(String.format("R-version String = %s", Rversion));

        // replication: R version
        String repDVN_Rversion = "attr(dvnData, 'R.version') <- R.Version()$version.string";
        c.voidEval(repDVN_Rversion);

        String zeligVersionLine = "packageDescription('Zelig')$Version";
        String zeligVersion = c.eval(zeligVersionLine).asString();

        //String RexecDate = c.eval("date()").asString();
        String RexecDate = c.eval("as.character(as.POSIXct(Sys.time()))").asString();
        // replication: date
        String repDVN_date = "attr(dvnData, 'date') <- as.character(as.POSIXct(Sys.time()))";
        c.voidEval(repDVN_date);

        String repDVN_dfOrigin = "attr(dvnData, 'data.frame.origin')<- "
                + "list('provider'='Dataverse Network Project',"
                + "'format' = list('name' = 'DVN data.frame', 'version'='1.3'))";
        c.voidEval(repDVN_dfOrigin);
        /*
        if (result.containsKey("option")){
        result.put("R_run_status", "T");
        } else {
        result.put("option", requestTypeToken.toLowerCase()); //download  zelig eda xtab
        result.put("R_run_status", "F");
        }
        */
        if (sro.hasRecodedVariables()) {
            if (sro.getSubsetConditions() != null) {
                result.put("subsettingCriteria", StringUtils.join(sro.getSubsetConditions(), "\n"));
                // replication: subset lines
                String[] sbst = null;
                sbst = (String[]) sro.getSubsetConditions()
                        .toArray(new String[sro.getSubsetConditions().size()]);

                c.assign("sbstLines", new REXPString(sbst));

                String repDVN_sbst = "attr(dvnData, 'subsetLines') <- sbstLines";
                c.voidEval(repDVN_sbst);
            }
            /* to be used in the future? */
            if (sro.getRecodeConditions() != null) {
                result.put("recodingCriteria", StringUtils.join(sro.getRecodeConditions(), "\n"));
                String[] rcd = null;
                rcd = (String[]) sro.getRecodeConditions()
                        .toArray(new String[sro.getRecodeConditions().size()]);

                c.assign("rcdtLines", new REXPString(rcd));

                String repDVN_rcd = "attr(dvnData, 'recodeLines') <- rcdtLines";
                c.voidEval(repDVN_rcd);
            }

        }

        // save workspace as a replication data set

        String RdataFileName = "DVNdataFrame." + PID + ".RData";
        result.put("Rdata", "/" + requestdir + "/" + RdataFileName);

        String saveWS = "save('dvnData', file='" + wrkdir + "/" + RdataFileName + "')";
        dbgLog.fine("save the workspace=" + saveWS);
        c.voidEval(saveWS);

        // write back the R workspace to the dvn 

        String wrkspFileName = wrkdir + "/" + RdataFileName;
        dbgLog.fine("wrkspFileName=" + wrkspFileName);

        int wrkspflSize = getFileSize(c, wrkspFileName);

        File wsfl = writeBackFileToDvn(c, wrkspFileName, RWRKSP_FILE_PREFIX, "RData", wrkspflSize);

        result.put("dvn_RData_FileName", wsfl.getName());

        if (wsfl != null) {
            result.put("wrkspFileName", wsfl.getAbsolutePath());
            dbgLog.fine("wrkspFileName=" + wsfl.getAbsolutePath());
        } else {
            dbgLog.fine("wrkspFileName is null");
        }

        result.put("library_1", "VDCutil");

        result.put("fileUNF", fileUNF);
        result.put("dsbHost", RSERVE_HOST);
        result.put("dsbPort", DSB_HOST_PORT);
        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("Rversion", Rversion);
        result.put("zeligVersion", zeligVersion);
        result.put("RexecDate", RexecDate);
        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));

        result.putAll(tmpResult);
        dbgLog.fine("result object (before closing the Rserve):\n" + result);

        // reflection block: end

        // create a zip file of the directory created: 

        //String zipTmpDir = "system(\"(cd "+DSB_TMP_DIR+"; zip -r /tmp/"+requestdir+".zip "+requestdir+")\")";
        //c.voidEval(zipTmpDir);        

        // transfer the zip file to the application side: 

        //RFileInputStream ris = null;
        //OutputStream outbr   = null;

        //int zipSize = getFileSize(c,"/tmp/"+requestdir+".zip");

        String listAnalysisFiles = "list.files('" + DSB_TMP_DIR + "/" + requestdir + "', recursive=TRUE)";
        dbgLog.fine("looking up the analysis result files on the DSB/Rserve side: " + listAnalysisFiles);
        String[] analysisReportFiles = c.eval(listAnalysisFiles).asStrings();
        RFileInputStream ris = null;
        OutputStream outbr = null;

        try {
            File localReportDir = new File(TEMP_DIR + "/DVN", requestdir);
            if (!localReportDir.exists()) {
                localReportDir.mkdir();
            }

            for (int i = 0; i < analysisReportFiles.length; i++) {
                String reportFile = analysisReportFiles[i];
                int reportFileSize = getFileSize(c, DSB_TMP_DIR + "/" + requestdir + "/" + reportFile);
                dbgLog.fine("DvnRData: transferring file " + reportFile);
                dbgLog.fine("DvnRData: file size: " + reportFileSize);

                if (reportFile.lastIndexOf("/") > 0) {
                    File localReportSubDir = new File(TEMP_DIR + "/DVN/" + requestdir,
                            reportFile.substring(0, reportFile.lastIndexOf("/")));
                    if (!localReportSubDir.exists()) {
                        localReportSubDir.mkdirs();
                    }
                }

                ris = c.openFile(DSB_TMP_DIR + "/" + requestdir + "/" + reportFile);
                outbr = new BufferedOutputStream(
                        new FileOutputStream(new File(TEMP_DIR + "/DVN/" + requestdir, reportFile)));

                byte[] obuf = new byte[reportFileSize];
                int obufsize = 0;

                while ((obufsize = ris.read(obuf)) != -1) {
                    outbr.write(obuf, 0, reportFileSize);
                }

                ris.close();
                outbr.close();
            }

            //String unZipCmd = "/usr/bin/unzip "+TEMP_DIR+"/DVN/"+requestdir+".zip -d "+TEMP_DIR+"/DVN";
            //int exitValue = 1;

            //dbgLog.fine("attempting to execute "+unZipCmd);

            //try {
            //Runtime runtime = Runtime.getRuntime();
            //Process process = runtime.exec(unZipCmd);
            //exitValue = process.waitFor();
            //} catch (Exception e) {
            //e.printStackTrace();
            //exitValue = 1;
            //}

            //if (exitValue == 0) {
            //result.put("webFolderArchived",TEMP_DIR+"/DVN/"+requestdir+".zip");
            //}

        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        } finally {
            if (ris != null) {
                ris.close();
            }
            if (outbr != null) {
                outbr.close();
            }
        }

        // // move the temp dir to the web-temp root dir
        //String mvTmpDir = "file.rename('"+wrkdir+"','"+webwrkdir+"')";
        //dbgLog.fine("web-temp_dir="+mvTmpDir);
        //c.voidEval(mvTmpDir);        

        // close the Rserve connection
        c.close();

    } catch (RserveException rse) {
        // RserveException (Rserve is not running)
        rse.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (REXPMismatchException mme) {

        // REXP mismatch exception (what we got differs from what we expected)
        mme.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (IOException ie) {
        ie.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);
        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;

    } catch (Exception ex) {
        ex.printStackTrace();

        result.put("dsbContextRootDir", DSB_CTXT_DIR);
        result.put("PID", PID);

        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));
        result.put("option", sro.getRequestType().toLowerCase());

        result.put("RexecError", "true");
        return result;
    }

    return result;

}

From source file:processing.core.PApplet.java

/**
 * Create an offscreen PGraphics object for drawing. This can be used for
 * bitmap or vector images drawing or rendering.
 * <UL>// ww w .  j ava2 s . com
 * <LI>Do not use "new PGraphicsXxxx()", use this method. This method
 * ensures that internal variables are set up properly that tie the new
 * graphics context back to its parent PApplet.
 * <LI>The basic way to create bitmap images is to use the <A
 * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A>
 * function.
 * <LI>If you want to create a really large scene and write that, first make
 * sure that you've allocated a lot of memory in the Preferences.
 * <LI>If you want to create images that are larger than the screen, you
 * should create your own PGraphics object, draw to that, and use <A
 * HREF="http://processing.org/reference/save_.html">save()</A>. For now,
 * it's best to use <A HREF=
 * "http://dev.processing.org/reference/everything/javadoc/processing/core/PGraphics3D.html"
 * >P3D</A> in this scenario. P2D is currently disabled, and the JAVA2D
 * default will give mixed results. An example of using P3D:
 * 
 * <PRE>
 * 
 * PGraphics big;
 * 
 * void setup() {
 *    big = createGraphics(3000, 3000, P3D);
 * 
 *    big.beginDraw();
 *    big.background(128);
 *    big.line(20, 1800, 1800, 900);
 *    // etc..
 *    big.endDraw();
 * 
 *    // make sure the file is written to the sketch folder
 *    big.save(&quot;big.tif&quot;);
 * }
 * 
 * </PRE>
 * 
 * <LI>It's important to always wrap drawing to createGraphics() with
 * beginDraw() and endDraw() (beginFrame() and endFrame() prior to revision
 * 0115). The reason is that the renderer needs to know when drawing has
 * stopped, so that it can update itself internally. This also handles
 * calling the defaults() method, for people familiar with that.
 * <LI>It's not possible to use createGraphics() with the OPENGL renderer,
 * because it doesn't allow offscreen use.
 * <LI>With Processing 0115 and later, it's possible to write images in
 * formats other than the default .tga and .tiff. The exact formats and
 * background information can be found in the developer's reference for <A
 * HREF=
 * "http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)"
 * >PImage.save()</A>.
 * </UL>
 */
public PGraphics createGraphics(int iwidth, int iheight, String irenderer) {
    PGraphics pg = null;
    if (irenderer.equals(JAVA2D)) {
        pg = new PGraphicsAndroid2D();
    } else if (irenderer.equals(P2D)) {
        pg = new PGraphics2D();
    } else if (irenderer.equals(P3D)) {
        pg = new PGraphics3D();
    } else {
        Class<?> rendererClass = null;
        Constructor<?> constructor = null;
        try {
            // The context class loader doesn't work:
            // rendererClass =
            // Thread.currentThread().getContextClassLoader().loadClass(irenderer);
            // even though it should, according to this discussion:
            // http://code.google.com/p/android/issues/detail?id=11101
            // While the method that is not supposed to work, using the
            // class loader, does:
            rendererClass = this.getClass().getClassLoader().loadClass(irenderer);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException("Missing renderer class");
        }

        if (rendererClass != null) {
            try {
                constructor = rendererClass.getConstructor(new Class[] {});
            } catch (NoSuchMethodException nsme) {
                throw new RuntimeException("Missing renderer constructor");
            }

            if (constructor != null) {
                try {
                    pg = (PGraphics) constructor.newInstance();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (java.lang.InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    pg.setParent(this);
    pg.setPrimary(false);
    pg.setSize(iwidth, iheight);

    return pg;
}

From source file:com.processing.core.PApplet.java

/**
 * Create an offscreen PGraphics object for drawing. This can be used
 * for bitmap or vector images drawing or rendering.
 * <UL>/*from   w  w w. j a  va 2  s  .  c  o m*/
 * <LI>Do not use "new PGraphicsXxxx()", use this method. This method
 * ensures that internal variables are set up properly that tie the
 * new graphics context back to its parent PApplet.
 * <LI>The basic way to create bitmap images is to use the <A
 * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A>
 * function.
 * <LI>If you want to create a really large scene and write that,
 * first make sure that you've allocated a lot of memory in the Preferences.
 * <LI>If you want to create images that are larger than the screen,
 * you should create your own PGraphics object, draw to that, and use
 * <A HREF="http://processing.org/reference/save_.html">save()</A>.
 * For now, it's best to use <A HREF="http://dev.processing.org/reference/everything/javadoc/processing/core/PGraphics3D.html">P3D</A> in this scenario.
 * P2D is currently disabled, and the JAVA2D default will give mixed
 * results. An example of using P3D:
 * <PRE>
 *
 * PGraphics big;
 *
 * void setup() {
 *   big = createGraphics(3000, 3000, P3D);
 *
 *   big.beginDraw();
 *   big.background(128);
 *   big.line(20, 1800, 1800, 900);
 *   // etc..
 *   big.endDraw();
 *
 *   // make sure the file is written to the sketch folder
 *   big.save("big.tif");
 * }
 *
 * </PRE>
 * <LI>It's important to always wrap drawing to createGraphics() with
 * beginDraw() and endDraw() (beginFrame() and endFrame() prior to
 * revision 0115). The reason is that the renderer needs to know when
 * drawing has stopped, so that it can update itself internally.
 * This also handles calling the defaults() method, for people familiar
 * with that.
 * <LI>It's not possible to use createGraphics() with the OPENGL renderer,
 * because it doesn't allow offscreen use.
 * <LI>With Processing 0115 and later, it's possible to write images in
 * formats other than the default .tga and .tiff. The exact formats and
 * background information can be found in the developer's reference for
 * <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>.
 * </UL>
 */
public PGraphics createGraphics(int iwidth, int iheight, String irenderer) {
    PGraphics pg = null;
    if (irenderer.equals(JAVA2D)) {
        pg = new PGraphicsAndroid2D();
    } else if (irenderer.equals(P2D)) {
        if (!g.isGL()) {
            throw new RuntimeException("createGraphics() with P2D requires size() to use P2D or P3D");
        }
        pg = new PGraphics2D();
    } else if (irenderer.equals(P3D)) {
        if (!g.isGL()) {
            throw new RuntimeException("createGraphics() with P3D or OPENGL requires size() to use P2D or P3D");
        }
        pg = new PGraphics3D();
    } else {
        Class<?> rendererClass = null;
        Constructor<?> constructor = null;
        try {
            // The context class loader doesn't work:
            //rendererClass = Thread.currentThread().getContextClassLoader().loadClass(irenderer);
            // even though it should, according to this discussion:
            // http://code.google.com/p/android/issues/detail?id=11101
            // While the method that is not supposed to work, using the class loader, does:
            rendererClass = this.getClass().getClassLoader().loadClass(irenderer);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException("Missing renderer class");
        }

        if (rendererClass != null) {
            try {
                constructor = rendererClass.getConstructor(new Class[] {});
            } catch (NoSuchMethodException nsme) {
                throw new RuntimeException("Missing renderer constructor");
            }

            if (constructor != null) {
                try {
                    pg = (PGraphics) constructor.newInstance();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                }
            }
        }
    }

    pg.setParent(this);
    pg.setPrimary(false);
    pg.setSize(iwidth, iheight);

    return pg;
}