Example usage for java.util Arrays deepToString

List of usage examples for java.util Arrays deepToString

Introduction

In this page you can find the example usage for java.util Arrays deepToString.

Prototype

public static String deepToString(Object[] a) 

Source Link

Document

Returns a string representation of the "deep contents" of the specified array.

Usage

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
 *///  w  w  w  . j a  v a  2 s  .c o 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:gov.lanl.adore.djatoka.plugin.ExtractPDF.java

/**
 * Extracts region defined in DjatokaDecodeParam as BufferedImage
 * @param input absolute file path of PDF file.
 * @param params DjatokaDecodeParam instance containing region and transform settings.
 * @return extracted region as a BufferedImage
 * @throws DjatokaException/*from   w ww .j a  v  a  2 s .c  om*/
 */
@Override
public BufferedImage process(String input, DjatokaDecodeParam params) throws DjatokaException {

    logger.debug("ExtractPDF.process:\n\tinput: " + input + "\n\tparams: " + params);

    if (input == null)
        throw new DjatokaException("Unknown failure while converting file: no image produced.");

    try {
        setPDFCommandsPath();
    } catch (IllegalStateException e) {
        logger.error("Failed to set PDF commands path: ", e);
        throw e;
    }

    int page_number = 1 + params.getCompositingLayer(); // From 0-based to 1-based.
    int status = 0;
    BufferedImage processedImage = null;
    try {
        /*
        // First get max physical dim of bounding box of the page
        // to compute the DPI to ask for..  otherwise some AutoCAD
        // drawings can produce enormous files even at 75dpi, for
        // 48" drawings..
        int dpi = 0;
        Dimension pageSize = getPDFPageSize(input, page_number);
        if (pageSize == null)
        {
        logger.error("Sanity check: Did not find \"Page " + page_number + " size\" line in output of pdfinfo, file="+input);
        throw new IllegalArgumentException("Failed to get \"Page " + page_number + " size\" of PDF with pdfinfo.");
        }
        else
        {
        double w = pageSize.getWidth();
        double h = pageSize.getHeight();
        int maxdim = (int)Math.max(Math.abs(w), Math.abs(h));
        dpi = Math.min(MAX_DPI, (MAX_PX * 72 / maxdim));
        logger.debug("DPI: pdfinfo method got dpi="+dpi+" for max dim="+maxdim+" (points, 1/72\")");
        } */

        // Scale
        int dpi = getScaledDPI(params);

        // Requires Sun JAI imageio additions to read ppm directly.
        // this will get "-[0]+1.ppm" appended to it by pdftoppm
        File outPrefixF = File.createTempFile("pdftopng", "out");
        String outPrefix = outPrefixF.toString();
        outPrefixF.delete();

        //String pdfCmd[] = PDFTOPPM_COMMAND.clone();
        ArrayList<String> pdfCmd = new ArrayList<String>(Arrays.asList(PDFTOPPM_COMMAND));
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_BIN, pdftoppmPath);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FIRSTPAGE, "" + page_number);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_LASTPAGE, "" + page_number);
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_DPI, String.valueOf(dpi));
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_FILE, input.toString());
        pdfCmd.set(PDFTOPPM_COMMAND_POSITION_OUTPUTFILE, outPrefix);

        // Crop
        Rectangle crop = getCropParam(params);
        if (crop != null) {
            String[] cropParams = { "-x", "" + (int) crop.getX(), "-y", "" + (int) crop.getY(), "-W",
                    "" + (int) crop.getWidth(), "-H", "" + (int) crop.getHeight() };
            pdfCmd.addAll(PDFTOPPM_COMMAND_POSITION_OPTIONAL_EXTRAS, Arrays.asList(cropParams));
        }

        String[] pdfCmdA = pdfCmd.toArray(new String[pdfCmd.size()]);
        logger.debug("Running pdftoppm command: " + Arrays.deepToString(pdfCmdA));
        //logger.debug("Running pdftoppm command: " + pdfCmd.toString());

        File outf = null;
        Process pdfProc = null;
        try {
            pdfProc = Runtime.getRuntime().exec(pdfCmdA);
            status = pdfProc.waitFor();
            logger.debug("status: " + status);

            // pdftoppm uses variable numbers of padding 0s to the output prefix.
            // E.g., may be prefix-000001.png, prefix-001.png or even prefix-01.png.
            // Version 0.12.3 (Poppler, not XPDF) seems to consider the total number of pages.
            // So, for example, in a PDF with 90 pages, the output will be "prefix-02.png";
            // for a PDF with 350 pages, the output will be "prefix-002.png".
            // FIXME: try some approach where the PDF number of pages is considered without
            // running pdfinfo command again, thus making it simpler to determine the number
            // of padding zeros. Right now we going "brute force" because we do not know if
            // it is feasable to once again run the pdfinfo command.
            String tests[] = { outPrefix + "-" + page_number + ".png", outPrefix + "-0" + page_number + ".png",
                    outPrefix + "-00" + page_number + ".png", outPrefix + "-000" + page_number + ".png",
                    outPrefix + "-0000" + page_number + ".png", outPrefix + "-00000" + page_number + ".png" };
            for (String outname : tests) {
                if ((new File(outname)).exists()) {
                    outf = new File(outname);
                    break;
                }
            }
            logger.debug("PDFTOPPM output is: " + outf + ", exists=" + outf != null ? outf.exists() : "!");
            processedImage = ImageIO.read(outf);

            // Rotate
            if (params.getRotationDegree() > 0) {
                processedImage = ImageProcessingUtils.rotate(processedImage, params.getRotationDegree());
            }
        } catch (InterruptedException e) {
            logger.error("Failed converting PDF file to image: ", e);
            throw new IllegalArgumentException("Failed converting PDF file to image: ", e);
        } finally {
            if (outf != null)
                outf.delete();
            // Our exec() should not produce any output, but we want to stay safe.
            // http://mark.koli.ch/2011/01/leaky-pipes-remember-to-close-your-streams-when-using-javas-runtimegetruntimeexec.html
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getOutputStream());
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getInputStream());
            org.apache.commons.io.IOUtils.closeQuietly(pdfProc.getErrorStream());
        }
    } catch (Exception e) {
        logger.error("Failed converting PDF file to image: ", e);
        throw new IllegalArgumentException("Failed converting PDF file to image: ", e);
    } finally {
        if (status != 0)
            logger.error("PDF conversion proc failed, exit status=" + status + ", file=" + input);
    }

    return processedImage;
}

From source file:org.richfaces.tests.metamer.ftest.AbstractGrapheneTest.java

public void testRequestEventsAfterByAlert(String... events) {
    List<String> list = new LinkedList<String>();

    for (int i = 0; i < events.length; i++) {
        waitGui.dontFail().until(alertPresent);
        if (selenium.isAlertPresent()) {
            list.add(selenium.getAlert());
        }//from www.  j av a2s.  c om
    }

    String[] actualEvents = list.toArray(new String[list.size()]);
    assertEquals(actualEvents, events, format("The events ({0}) don't came in right order ({1})",
            Arrays.deepToString(actualEvents), Arrays.deepToString(events)));
}

From source file:org.jahia.services.content.LastModifiedListener.java

public void onEvent(final EventIterator eventIterator) {
    try {//from ww  w.j av  a 2 s  .co m
        final JahiaUser user = ((JCREventIterator) eventIterator).getSession().getUser();
        final int type = ((JCREventIterator) eventIterator).getOperationType();

        if (type == JCRObservationManager.NODE_CHECKOUT || type == JCRObservationManager.NODE_CHECKIN) {
            return;
        }

        final Set<Session> sessions = new HashSet<Session>();
        final Set<String> nodes = new HashSet<String>();
        final Set<String> addedNodes = new HashSet<String>();
        final Set<String> reorderedNodes = new HashSet<String>();
        final List<String> autoPublishedIds;

        if (workspace.equals("default")) {
            autoPublishedIds = new ArrayList<String>();
        } else {
            autoPublishedIds = null;
        }

        JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(user, workspace, null,
                new JCRCallback<Object>() {
                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        Calendar c = GregorianCalendar.getInstance();
                        while (eventIterator.hasNext()) {
                            final Event event = eventIterator.nextEvent();
                            if (event.getType() == Event.NODE_REMOVED && event.getIdentifier() != null) {
                                try {
                                    session.getNodeByIdentifier(event.getIdentifier());
                                } catch (ItemNotFoundException infe) {
                                    try {
                                        final JCRNodeWrapper parent = session
                                                .getNode(StringUtils.substringBeforeLast(event.getPath(), "/"));
                                        if (!session.getWorkspace().getName().equals(Constants.LIVE_WORKSPACE)
                                                && parent.getProvider().getMountPoint().equals("/")) {
                                            // Test if published and has lastPublished property
                                            boolean lastPublished = JCRTemplate.getInstance()
                                                    .doExecuteWithSystemSessionAsUser(user,
                                                            Constants.LIVE_WORKSPACE, null,
                                                            new JCRCallback<Boolean>() {
                                                                public Boolean doInJCR(
                                                                        JCRSessionWrapper session)
                                                                        throws RepositoryException {
                                                                    JCRNodeWrapper nodeByIdentifier = session
                                                                            .getNodeByIdentifier(
                                                                                    event.getIdentifier());
                                                                    boolean lastPublished = nodeByIdentifier
                                                                            .hasProperty(
                                                                                    Constants.LASTPUBLISHED);
                                                                    if (lastPublished && !parent
                                                                            .isNodeType("jmix:autoPublish")) {
                                                                        List<String> nodeTypes = (event instanceof JCRObservationManager.EventWrapper)
                                                                                ? ((JCRObservationManager.EventWrapper) event)
                                                                                        .getNodeTypes()
                                                                                : null;
                                                                        if (nodeTypes != null) {
                                                                            for (String nodeType : nodeTypes) {
                                                                                ExtendedNodeType eventNodeType = NodeTypeRegistry
                                                                                        .getInstance()
                                                                                        .getNodeType(nodeType);
                                                                                if (eventNodeType != null
                                                                                        && eventNodeType
                                                                                                .isNodeType(
                                                                                                        "jmix:autoPublish")) {
                                                                                    nodeByIdentifier.remove();
                                                                                    session.save();
                                                                                    return false;
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                    return lastPublished;
                                                                }
                                                            });

                                            if (lastPublished) {
                                                if (!parent.isNodeType("jmix:deletedChildren")) {
                                                    parent.addMixin("jmix:deletedChildren");
                                                    parent.setProperty("j:deletedChildren",
                                                            new String[] { event.getIdentifier() });
                                                } else if (!parent.hasProperty("j:deletedChildren")) {
                                                    parent.setProperty("j:deletedChildren",
                                                            new String[] { event.getIdentifier() });
                                                } else {
                                                    parent.getProperty("j:deletedChildren")
                                                            .addValue(event.getIdentifier());
                                                }
                                                sessions.add(parent.getRealNode().getSession());
                                            }
                                        }
                                    } catch (PathNotFoundException e) {
                                        // no parent
                                    } catch (ItemNotFoundException e) {
                                        // no live
                                    }
                                }
                            }

                            if (isExternal(event)) {
                                continue;
                            }

                            String path = event.getPath();
                            if (path.startsWith("/jcr:system/")) {
                                continue;
                            }
                            if ((event.getType() & Event.PROPERTY_CHANGED + Event.PROPERTY_ADDED
                                    + Event.PROPERTY_REMOVED) != 0) {
                                if (propertiesToIgnore.contains(StringUtils.substringAfterLast(path, "/"))) {
                                    continue;
                                }
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Receiving event for lastModified date for : " + path);
                            }
                            if (event.getType() == Event.NODE_ADDED) {
                                addedNodes.add(path);
                                //                            if(!path.contains("j:translation")) {
                                //                                nodes.add(StringUtils.substringBeforeLast(path,"/"));
                                //                            }
                            } else if (Event.NODE_MOVED == event.getType()) {
                                // in the case of a real node move, we won't track this as we want to have last modification
                                // properties on moved nodes so we only handle the reordering case.
                                if (event.getInfo().get("srcChildRelPath") != null) {
                                    // this case is a node reordering in it's parent
                                    reorderedNodes.add(path);
                                }
                                nodes.add(StringUtils.substringBeforeLast(path, "/"));
                            } else {
                                nodes.add(StringUtils.substringBeforeLast(path, "/"));
                            }
                        }
                        if (reorderedNodes.size() > 0) {
                            addedNodes.removeAll(reorderedNodes);
                        }
                        if (addedNodes.size() > 0) {
                            nodes.removeAll(addedNodes);
                        }
                        if (!nodes.isEmpty() || !addedNodes.isEmpty()) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Updating lastModified date for existing nodes : "
                                        + Arrays.deepToString(nodes.toArray(new String[nodes.size()])));
                                logger.debug("Updating lastModified date for added nodes : " + Arrays
                                        .deepToString(addedNodes.toArray(new String[addedNodes.size()])));
                            }
                            for (String node : nodes) {
                                try {
                                    JCRNodeWrapper n = session.getNode(node);
                                    sessions.add(n.getRealNode().getSession());
                                    updateProperty(n, c, user, autoPublishedIds, type);
                                } catch (UnsupportedRepositoryOperationException e) {
                                    // Cannot write property
                                } catch (PathNotFoundException e) {
                                    // node has been removed
                                }
                            }
                            for (String addedNode : addedNodes) {
                                try {
                                    JCRNodeWrapper n = session.getNode(addedNode);
                                    sessions.add(n.getRealNode().getSession());
                                    if (!n.hasProperty("j:originWS") && n.isNodeType("jmix:originWS")) {
                                        n.setProperty("j:originWS", workspace);
                                    }
                                    updateProperty(n, c, user, autoPublishedIds, type);
                                } catch (UnsupportedRepositoryOperationException e) {
                                    // Cannot write property
                                } catch (PathNotFoundException e) {
                                    // node has been removed
                                }
                            }
                            for (Session jcrsession : sessions) {
                                try {
                                    jcrsession.save();
                                } catch (RepositoryException e) {
                                    logger.debug("Cannot update lastModification properties");
                                }
                            }
                        }
                        return null;
                    }
                });

        if (autoPublishedIds != null && !autoPublishedIds.isEmpty()) {
            synchronized (this) {
                publicationService.publish(autoPublishedIds, "default", "live", false, null);
            }
        }

    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.eclipse.january.dataset.BinaryOperationTest.java

@Override
public String toString() {
    return "Test of operation (" + operation + ") failed with " + Arrays.deepToString(operands);
}

From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java

public List<Map<String, Object>> getAppAttemptsContainers(String appId, String appAttemptId) {
    List<Map<String, Object>> appAttemptsContainers = new ArrayList<>();
    String appUrl = this.yarnWebHttpAddr + "/ws/v1/cluster/apps/" + appId + "/appattempts/" + appAttemptId
            + "/containers?_=" + System.currentTimeMillis();

    InputStream inputStream = null;
    try {/*from   ww w  . j a  v a2s. com*/
        HttpResponse response = callRestUrl(appUrl, principal, HTTP.GET);
        inputStream = response.getEntity().getContent();
        String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
                .collect(Collectors.joining(System.lineSeparator()));
        if (response.getStatusLine().getStatusCode() != 200 /*success*/) {
            LOGGER.warn("Status code " + response.getStatusLine().getStatusCode());
            LOGGER.warn("message is :" + Arrays.deepToString(response.getAllHeaders()));
            LOGGER.warn("result\n" + result);
        }

        // parse app status json
        appAttemptsContainers = parseAppAttemptsContainers(result);
    } catch (Exception exp) {
        exp.printStackTrace();
    } finally {
        try {
            if (null != inputStream) {
                inputStream.close();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return appAttemptsContainers;
}

From source file:org.rhq.plugins.jmx.MBeanResourceComponent.java

protected void getBeanProperties(MeasurementReport report, EmsBean thisBean,
        Set<MeasurementScheduleRequest> requests) {
    List<String> props = new ArrayList<String>();
    for (MeasurementScheduleRequest request : requests) {
        Matcher m = PROPERTY_PATTERN.matcher(request.getName());
        if (m.matches()) {
            // Complex property
            props.add(getAttributeName(m.group(2)));
        } else {/* w  w  w  . ja v  a  2 s  . c  o  m*/
            // Simple property
            props.add(request.getName());
        }
    }

    List<EmsAttribute> refreshedAttributes = thisBean.refreshAttributes(props);

    for (MeasurementScheduleRequest request : requests) {
        Matcher m = PROPERTY_PATTERN.matcher(request.getName());
        String fullProperty = null;
        String attributeName;
        if (m.matches()) {
            // Complex property
            fullProperty = m.group(2);
            attributeName = getAttributeName(fullProperty);
        } else {
            attributeName = request.getName();
        }

        EmsAttribute attribute = null;
        for (EmsAttribute refreshedAttribute : refreshedAttributes) {
            if (attributeName.equals(refreshedAttribute.getName())) {
                attribute = refreshedAttribute;
            }
        }

        if (attribute == null) {
            log.debug("Unable to collect measurement, attribute [" + request.getName() + "] not found on ["
                    + this.resourceContext.getResourceKey() + "]");
            // TODO GH: report.addError
        } else {
            Object value = attribute.getValue();
            if ((value != null) && (fullProperty != null)) {
                // we're meant to load a specific property of the returned value object
                value = lookupAttributeProperty(value, fullProperty);
            }

            if ((request.getDataType() == DataType.MEASUREMENT) && (value instanceof Number)) {
                report.addData(new MeasurementDataNumeric(request, ((Number) value).doubleValue()));
            } else if (request.getDataType() == DataType.TRAIT) {
                String displayValue = null;
                if ((value != null) && value.getClass().isArray()) {
                    displayValue = Arrays.deepToString((Object[]) value);
                } else {
                    displayValue = String.valueOf(value);
                }

                report.addData(new MeasurementDataTrait(request, displayValue));
            }
        }
    }
}

From source file:com.brianscottrussell.gameoflife.GameGrid.java

@Override
public String toString() {
    return "GameGrid{" + "grid=" + Arrays.deepToString(grid) + ", rowCount=" + rowCount + ", colCount="
            + colCount + '}';
}

From source file:fr.certu.chouette.gui.command.ImportCommand.java

/**
 * @param manager//from   ww  w .  ja  v  a2s  .c  om
 * @param savedIds
 * @param importTask
 * @param validationReport
 */
private void validateLevel3(INeptuneManager<NeptuneIdentifiedObject> manager, List<Long> savedIds,
        JSONObject parameters, ValidationReport validationReport) {

    if (parameters != null) {
        log.info("processing phase 3 validation on " + savedIds.size() + " lines");
        // launch validation on objects
        Filter filter = Filter.getNewInFilter("id", savedIds);
        try {
            List<NeptuneIdentifiedObject> beans = manager.getAll(null, filter);
            if (beans == null || beans.isEmpty()) {
                log.error("cannot read previously saved objects :" + Arrays.deepToString(savedIds.toArray()));

            } else {
                PhaseReportItem phaseReport = new PhaseReportItem(PhaseReportItem.PHASE.THREE);
                validationReport.addItem(phaseReport);
                manager.validate(null, beans, parameters, phaseReport, null, true);
            }
        } catch (Exception e) {
            log.error("cannot read previously saved objects", e);
        }
    }
}

From source file:uk.ac.gla.terrier.probos.controller.KittenUtils2.java

public static boolean detectUseCp(Configuration pConf, final String path) {
    boolean cp = false;
    final String[] USE_RCP_DIRS = pConf.getStrings(PConfiguration.KEY_RCP_USE);

    if (USE_RCP_DIRS != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checking is " + path + " matches in " + Arrays.deepToString(USE_RCP_DIRS));
        }//w  ww.  j  a va  2s. co m
        for (String prefix : USE_RCP_DIRS) {
            if (path.startsWith(prefix)) {
                cp = true;
                LOG.debug(path + " matches in " + prefix);
                break;
            }
        }
    } else {
        LOG.warn(PConfiguration.KEY_RCP_USE + " was null, it should normally be at least empty.");
    }
    return cp;
}