Examples of UtilTimer


Examples of org.ofbiz.base.util.UtilTimer

    public void loadAttributes() throws GenericEntityException {
        if (attributesLoaded) {
            return;
        }

        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(4, "[UIDisplayObject.loadAttributes] Start");
        }

        attributesLoaded = true;

        // Get all UI display object attributes' generic values from the database.
        HashMap findMap = new HashMap();
        findMap.put("displayObjectId", getDisplayObjectId());

        ArrayList order = new ArrayList();
        order.add("displayAttribId");

        List uiDisplayObjectAttribL = getDelegator().findByAnd("UiDisplayObjectAttrib",
                findMap, order);
        Iterator uiDisplayObjectAttribI = uiDisplayObjectAttribL.iterator();

        while (uiDisplayObjectAttribI.hasNext()) {
            GenericValue uiDisplayObjectAttribGV = (GenericValue) uiDisplayObjectAttribI.next();
            String displayAttribId = uiDisplayObjectAttribGV.getString(
                    "displayAttribId");

            if (displayAttribId == null) {
                displayAttribId = "";
            }

            String attributeValue = uiDisplayObjectAttribGV.getString(
                    "attributeValue");

            if (attributeValue == null) {
                attributeValue = "";
            }

            if (displayAttribId.equals("ALIGN")) {
                setAttribAlign(attributeValue);
            } else if (displayAttribId.equals("ANCHOR_HREF_DEF")) {
                setAttribAnchorHrefDef(attributeValue);
            } else if (displayAttribId.equals("ANCHOR_TARGET")) {
                setAttribAnchorTarget(attributeValue);
            } else if (displayAttribId.equals("CHECKED_DISPLAY")) {
                setAttribCheckedDisplay(attributeValue);
            } else if (displayAttribId.equals("CHECKED_VALUE")) {
                setAttribCheckedValue(attributeValue);
            } else if (displayAttribId.equals("CLASS")) {
                setAttribClass(attributeValue);
            } else if (displayAttribId.equals("COLS")) {
                setAttribCols(attributeValue);
            } else if (displayAttribId.equals("DISABLED")) {
                setAttribDisabled(attributeValue);
            } else if (displayAttribId.equals("DISPLAY_MASK")) {
                setAttribDisplayMask(attributeValue);
            } else if (displayAttribId.equals("EMPTY_FIRST")) {
                setAttribEmptyFirst(attributeValue);
            } else if (displayAttribId.equals("ENTITY")) {
                setAttribEntity(attributeValue);
            } else if (displayAttribId.equals("ENTITY_DISPLAY_DEF")) {
                setAttribEntityDisplayDef(attributeValue);
            } else if (displayAttribId.equals("EVENT_HANDLING")) {
                setAttribEventHandling(attributeValue);
            } else if (displayAttribId.equals("ENTITY_FIND_DEF")) {
                setAttribEntityFindDef(attributeValue);
            } else if (displayAttribId.equals("ENTITY_FIND_METHOD")) {
                setAttribEntityFindMethod(attributeValue);
            } else if (displayAttribId.equals("ENTITY_ORDER_DEF")) {
                setAttribEntityOrderDef(attributeValue);
            } else if (displayAttribId.equals("ENTITY_PK_FIND_DEF")) {
                setAttribEntityPkFindDef(attributeValue);
            } else if (displayAttribId.equals("ENTITY_VALUE_DEF")) {
                setAttribEntityValueDef(attributeValue);
            } else if (displayAttribId.equals("ENTITY_SEARCH_DEF")) {
                setAttribEntitySearchDef(attributeValue);
            } else if (displayAttribId.equals("FIXED_VALUES")) {
                setAttribFixedValues(attributeValue);
            } else if (displayAttribId.equals("FILL_METHOD")) {
                setAttribFillMethod(attributeValue);
            } else if (displayAttribId.equals("MAX_LENGTH")) {
                setAttribMaxLength(attributeValue);
            } else if (displayAttribId.equals("ROWS")) {
                setAttribRows(attributeValue);
            } else if (displayAttribId.equals("SIZE")) {
                setAttribSize(attributeValue);
            } else if (displayAttribId.equals("READ_ONLY")) {
                setAttribReadOnly(attributeValue);
            } else if (displayAttribId.equals("UNCHECKED_DISPLAY")) {
                setAttribUncheckedDisplay(attributeValue);
            } else if (displayAttribId.equals("UNCHECKED_VALUE")) {
                setAttribUncheckedValue(attributeValue);
            } else if (displayAttribId.equals("WRAP")) {
                setAttribWrap(attributeValue);
            }
        }

        if (TIMER) {
            timer.timerString(4, "[UIDisplayObject.loadAttributes] End");
        }

        return;
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

    public void checkDb(Map<String, ModelEntity> modelEntities, List<String> colWrongSize, List<String> messages, boolean checkPks, boolean checkFks, boolean checkFkIdx, boolean addMissing) {
        if (isLegacy) {
            throw new RuntimeException("Cannot run checkDb on a legacy database connection; configure a database helper (entityengine.xml)");
        }
        UtilTimer timer = new UtilTimer();
        timer.timerString("Start - Before Get Database Meta Data");

        // get ALL tables from this database
        TreeSet<String> tableNames = this.getTableNames(messages);
        TreeSet<String> fkTableNames = tableNames == null ? null : new TreeSet<String>(tableNames);
        TreeSet<String> indexTableNames = tableNames == null ? null : new TreeSet<String>(tableNames);

        if (tableNames == null) {
            String message = "Could not get table name information from the database, aborting.";
            if (messages != null) messages.add(message);
            Debug.logError(message, module);
            return;
        }
        timer.timerString("After Get All Table Names");

        // get ALL column info, put into hashmap by table name
        Map<String, Map<String, ColumnCheckInfo>> colInfo = this.getColumnInfo(tableNames, checkPks, messages);
        if (colInfo == null) {
            String message = "Could not get column information from the database, aborting.";
            if (messages != null) messages.add(message);
            Debug.logError(message, module);
            return;
        }
        timer.timerString("After Get All Column Info");

        // -make sure all entities have a corresponding table
        // -list all tables that do not have a corresponding entity
        // -display message if number of table columns does not match number of entity fields
        // -list all columns that do not have a corresponding field
        // -make sure each corresponding column is of the correct type
        // -list all fields that do not have a corresponding column

        timer.timerString("Before Individual Table/Column Check");

        ArrayList<ModelEntity> modelEntityList = new ArrayList<ModelEntity>(modelEntities.values());
        // sort using compareTo method on ModelEntity
        Collections.sort(modelEntityList);
        int curEnt = 0;
        int totalEnt = modelEntityList.size();
        List<ModelEntity> entitiesAdded = FastList.newInstance();
        String schemaName;
        try {
            DatabaseMetaData dbData = this.getDatabaseMetaData(null, messages);
            schemaName = getSchemaName(dbData);
        } catch (SQLException e) {
            String message = "Could not get schema name the database, aborting.";
            if (messages != null) messages.add(message);
            Debug.logError(message, module);
            return;
        }
        List<Future<CreateTableCallable>> tableFutures = FastList.newInstance();
        for (ModelEntity entity: modelEntityList) {
            curEnt++;

            // if this is a view entity, do not check it...
            if (entity instanceof ModelViewEntity) {
                String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " View Entity " + entity.getEntityName();
                Debug.logVerbose(entMessage, module);
                if (messages != null) messages.add(entMessage);
                continue;               
            // if never-check is set then don't check it either
            } else if (entity.getNeverCheck()) {
                String entMessage = "(" + timer.timeSinceLast() + "ms) NOT Checking #" + curEnt + "/" + totalEnt + " Entity " + entity.getEntityName();
                Debug.logVerbose(entMessage, module);
                if (messages != null) messages.add(entMessage);
                continue;
            }

            String plainTableName = entity.getPlainTableName();
            String tableName;
            if (UtilValidate.isNotEmpty(schemaName)) {
                tableName = schemaName + "." + plainTableName;
            } else {
                tableName = plainTableName;
            }
            String entMessage = "(" + timer.timeSinceLast() + "ms) Checking #" + curEnt + "/" + totalEnt +
                " Entity " + entity.getEntityName() + " with table " + tableName;

            Debug.logVerbose(entMessage, module);
            if (messages != null) messages.add(entMessage);

            // -make sure all entities have a corresponding table
            if (tableNames.contains(tableName)) {
                tableNames.remove(tableName);

                if (colInfo != null) {
                    Map<String, ModelField> fieldColNames = FastMap.newInstance();
                    Iterator<ModelField> fieldIter = entity.getFieldsIterator();
                    while (fieldIter.hasNext()) {
                        ModelField field = fieldIter.next();
                        fieldColNames.put(field.getColName(), field);
                    }

                    Map<String, ColumnCheckInfo> colMap = colInfo.get(tableName);
                    if (colMap != null) {
                        for (ColumnCheckInfo ccInfo: colMap.values()) {
                            // -list all columns that do not have a corresponding field
                            if (fieldColNames.containsKey(ccInfo.columnName)) {
                                ModelField field = null;

                                field = fieldColNames.remove(ccInfo.columnName);
                                ModelFieldType modelFieldType = modelFieldTypeReader.getModelFieldType(field.getType());

                                if (modelFieldType != null) {
                                    // make sure each corresponding column is of the correct type
                                    String fullTypeStr = modelFieldType.getSqlType();
                                    String typeName;
                                    int columnSize = -1;
                                    int decimalDigits = -1;

                                    int openParen = fullTypeStr.indexOf('(');
                                    int closeParen = fullTypeStr.indexOf(')');
                                    int comma = fullTypeStr.indexOf(',');

                                    if (openParen > 0 && closeParen > 0 && closeParen > openParen) {
                                        typeName = fullTypeStr.substring(0, openParen);
                                        if (comma > 0 && comma > openParen && comma < closeParen) {
                                            String csStr = fullTypeStr.substring(openParen + 1, comma);
                                            try {
                                                columnSize = Integer.parseInt(csStr);
                                            } catch (NumberFormatException e) {
                                                Debug.logError(e, module);
                                            }

                                            String ddStr = fullTypeStr.substring(comma + 1, closeParen);
                                            try {
                                                decimalDigits = Integer.parseInt(ddStr);
                                            } catch (NumberFormatException e) {
                                                Debug.logError(e, module);
                                            }
                                        } else {
                                            String csStr = fullTypeStr.substring(openParen + 1, closeParen);
                                            try {
                                                columnSize = Integer.parseInt(csStr);
                                            } catch (NumberFormatException e) {
                                                Debug.logError(e, module);
                                            }
                                        }
                                    } else {
                                        typeName = fullTypeStr;
                                    }

                                    // override the default typeName with the sqlTypeAlias if it is specified
                                    if (UtilValidate.isNotEmpty(modelFieldType.getSqlTypeAlias())) {
                                        typeName = modelFieldType.getSqlTypeAlias();
                                    }

                                    // NOTE: this may need a toUpperCase in some cases, keep an eye on it, okay just compare with ignore case
                                    if (!ccInfo.typeName.equalsIgnoreCase(typeName)) {
                                        String message = "WARNING: Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" +
                                            entity.getEntityName() + "] is of type [" + ccInfo.typeName + "] in the database, but is defined as type [" +
                                            typeName + "] in the entity definition.";
                                        Debug.logError(message, module);
                                        if (messages != null) messages.add(message);
                                    }
                                    if (columnSize != -1 && ccInfo.columnSize != -1 && columnSize != ccInfo.columnSize && (columnSize * 3) != ccInfo.columnSize) {
                                        String message = "WARNING: Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" +
                                            entity.getEntityName() + "] has a column size of [" + ccInfo.columnSize +
                                            "] in the database, but is defined to have a column size of [" + columnSize + "] in the entity definition.";
                                        Debug.logWarning(message, module);
                                        if (messages != null) messages.add(message);
                                        if (columnSize > ccInfo.columnSize && colWrongSize != null) {
                                            // add item to list of wrong sized columns; only if the entity is larger
                                            colWrongSize.add(entity.getEntityName() + "." + field.getName());
                                        }
                                    }
                                    if (decimalDigits != -1 && decimalDigits != ccInfo.decimalDigits) {
                                        String message = "WARNING: Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" +
                                            entity.getEntityName() + "] has a decimalDigits of [" + ccInfo.decimalDigits +
                                            "] in the database, but is defined to have a decimalDigits of [" + decimalDigits + "] in the entity definition.";
                                        Debug.logWarning(message, module);
                                        if (messages != null) messages.add(message);
                                    }

                                    // do primary key matching check
                                    if (checkPks && ccInfo.isPk && !field.getIsPk()) {
                                        String message = "WARNING: Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" +
                                            entity.getEntityName() + "] IS a primary key in the database, but IS NOT a primary key in the entity definition. The primary key for this table needs to be re-created or modified so that this column is NOT part of the primary key.";
                                        Debug.logError(message, module);
                                        if (messages != null) messages.add(message);
                                    }
                                    if (checkPks && !ccInfo.isPk && field.getIsPk()) {
                                        String message = "WARNING: Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" +
                                            entity.getEntityName() + "] IS NOT a primary key in the database, but IS a primary key in the entity definition. The primary key for this table needs to be re-created or modified to add this column to the primary key. Note that data may need to be added first as a primary key column cannot have an null values.";
                                        Debug.logError(message, module);
                                        if (messages != null) messages.add(message);
                                    }
                                } else {
                                    String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() +
                                        "] has a field type name of [" + field.getType() + "] which is not found in the field type definitions";
                                    Debug.logError(message, module);
                                    if (messages != null) messages.add(message);
                                }
                            } else {
                                String message = "Column [" + ccInfo.columnName + "] of table [" + tableName + "] of entity [" + entity.getEntityName() + "] exists in the database but has no corresponding field" + ((checkPks && ccInfo.isPk) ? " (and it is a PRIMARY KEY COLUMN)" : "");
                                Debug.logWarning(message, module);
                                if (messages != null) messages.add(message);
                            }
                        }

                        // -display message if number of table columns does not match number of entity fields
                        if (colMap.size() != entity.getFieldsSize()) {
                            String message = "Entity [" + entity.getEntityName() + "] has " + entity.getFieldsSize() + " fields but table [" + tableName + "] has " + colMap.size() + " columns.";
                            Debug.logWarning(message, module);
                            if (messages != null) messages.add(message);
                        }
                    }

                    // -list all fields that do not have a corresponding column
                    for (String colName: fieldColNames.keySet()) {
                        ModelField field = fieldColNames.get(colName);
                        String message = "Field [" + field.getName() + "] of entity [" + entity.getEntityName() + "] is missing its corresponding column [" + field.getColName() + "]" + (field.getIsPk() ? " (and it is a PRIMARY KEY FIELD)" : "");

                        Debug.logWarning(message, module);
                        if (messages != null) messages.add(message);

                        if (addMissing) {
                            // add the column
                            String errMsg = addColumn(entity, field);

                            if (UtilValidate.isNotEmpty(errMsg)) {
                                message = "Could not add column [" + field.getColName() + "] to table [" + tableName + "]: " + errMsg;
                                Debug.logError(message, module);
                                if (messages != null) messages.add(message);
                            } else {
                                message = "Added column [" + field.getColName() + "] to table [" + tableName + "]" + (field.getIsPk() ? " (NOTE: this is a PRIMARY KEY FIELD, but the primary key was not updated automatically (not considered a safe operation), be sure to fill in any needed data and re-create the primary key)" : "");
                                Debug.logImportant(message, module);
                                if (messages != null) messages.add(message);
                            }
                        }
                    }
                }
            } else {
                String message = "Entity [" + entity.getEntityName() + "] has no table in the database";
                Debug.logWarning(message, module);
                if (messages != null) messages.add(message);

                if (addMissing) {
                    // create the table
                    tableFutures.add(submitWork(new CreateTableCallable(entity, modelEntities, tableName)));
                }
            }
        }
        for (CreateTableCallable tableCallable: ExecutionPool.getAllFutures(tableFutures)) {
            tableCallable.updateData(messages, entitiesAdded);
        }

        timer.timerString("After Individual Table/Column Check");

        // -list all tables that do not have a corresponding entity
        for (String tableName: tableNames) {
            String message = "Table named [" + tableName + "] exists in the database but has no corresponding entity";
            Debug.logWarning(message, module);
            if (messages != null) messages.add(message);
        }

        // for each newly added table, add fk indices
        if (datasourceInfo.useFkIndices) {
            int totalFkIndices = 0;
            List<Future<AbstractCountingCallable>> fkIndicesFutures = FastList.newInstance();
            for (ModelEntity curEntity: entitiesAdded) {
                if (curEntity.getRelationsOneSize() > 0) {
                    fkIndicesFutures.add(submitWork(new AbstractCountingCallable(curEntity, modelEntities) {
                        public AbstractCountingCallable call() throws Exception {
                            count = createForeignKeyIndices(entity, datasourceInfo.constraintNameClipLength, messages);
                            return this;
                        }
                    }));
                }
            }
            for (AbstractCountingCallable fkIndicesCallable: ExecutionPool.getAllFutures(fkIndicesFutures)) {
                totalFkIndices += fkIndicesCallable.updateData(messages);
            }
            if (totalFkIndices > 0) Debug.logImportant("==== TOTAL Foreign Key Indices Created: " + totalFkIndices, module);
        }

        // for each newly added table, add fks
        if (datasourceInfo.useFks) {
            int totalFks = 0;
            for (ModelEntity curEntity: entitiesAdded) {
                totalFks += this.createForeignKeys(curEntity, modelEntities, datasourceInfo.constraintNameClipLength, datasourceInfo.fkStyle, datasourceInfo.useFkInitiallyDeferred, messages);
            }
            if (totalFks > 0) Debug.logImportant("==== TOTAL Foreign Keys Created: " + totalFks, module);
        }

        // for each newly added table, add declared indexes
        if (datasourceInfo.useIndices) {
            int totalDis = 0;
            List<Future<AbstractCountingCallable>> disFutures = FastList.newInstance();
            for (ModelEntity curEntity: entitiesAdded) {
                if (curEntity.getIndexesSize() > 0) {
                    disFutures.add(submitWork(new AbstractCountingCallable(curEntity,  modelEntities) {
                    public AbstractCountingCallable call() throws Exception {
                        count = createDeclaredIndices(entity, messages);
                        return this;
                    }
                }));

                }
            }
            for (AbstractCountingCallable disCallable: ExecutionPool.getAllFutures(disFutures)) {
                totalDis += disCallable.updateData(messages);
            }
            if (totalDis > 0) Debug.logImportant("==== TOTAL Declared Indices Created: " + totalDis, module);
        }

        // make sure each one-relation has an FK
        if (checkFks) {
        //if (!justColumns && datasourceInfo.useFks && datasourceInfo.checkForeignKeysOnStart) {
            // NOTE: This ISN'T working for Postgres or MySQL, who knows about others, may be from JDBC driver bugs...
            int numFksCreated = 0;
            // TODO: check each key-map to make sure it exists in the FK, if any differences warn and then remove FK and recreate it

            // get ALL column info, put into hashmap by table name
            Map<String, Map<String, ReferenceCheckInfo>> refTableInfoMap = this.getReferenceInfo(fkTableNames, messages);

            // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module);

            if (refTableInfoMap == null) {
                // uh oh, something happened while getting info...
                if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module);
            } else {
                for (ModelEntity entity: modelEntityList) {
                    String entityName = entity.getEntityName();
                    // if this is a view entity, do not check it...
                    if (entity instanceof ModelViewEntity) {
                        String entMessage = "NOT Checking View Entity " + entity.getEntityName();
                        Debug.logVerbose(entMessage, module);
                        if (messages != null) {
                            messages.add(entMessage);
                        }
                        continue;
                    }

                    // get existing FK map for this table
                    Map<String, ReferenceCheckInfo> rcInfoMap = refTableInfoMap.get(entity.getTableName(datasourceInfo));
                    // Debug.logVerbose("Got ref info for table " + entity.getTableName(datasourceInfo) + ": " + rcInfoMap, module);

                    // go through each relation to see if an FK already exists
                    Iterator<ModelRelation> relations = entity.getRelationsIterator();
                    boolean createdConstraints = false;
                    while (relations.hasNext()) {
                        ModelRelation modelRelation = relations.next();
                        if (!"one".equals(modelRelation.getType())) {
                            continue;
                        }

                        ModelEntity relModelEntity = modelEntities.get(modelRelation.getRelEntityName());
                        if (relModelEntity == null) {
                            Debug.logError("No such relation: " + entity.getEntityName() + " -> " + modelRelation.getRelEntityName(), module);
                            continue;
                        }
                        String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.constraintNameClipLength);
                        ReferenceCheckInfo rcInfo = null;

                        if (rcInfoMap != null) {
                            rcInfo = rcInfoMap.get(relConstraintName);
                        }

                        if (rcInfo != null) {
                            rcInfoMap.remove(relConstraintName);
                        } else {
                            // if not, create one
                            String noFkMessage = "No Foreign Key Constraint [" + relConstraintName + "] found for entity [" + entityName + "]";
                            if (messages != null) messages.add(noFkMessage);
                            if (Debug.infoOn()) Debug.logInfo(noFkMessage, module);

                            if (addMissing) {
                                String errMsg = createForeignKey(entity, modelRelation, relModelEntity, datasourceInfo.constraintNameClipLength, datasourceInfo.fkStyle, datasourceInfo.useFkInitiallyDeferred);
                                if (UtilValidate.isNotEmpty(errMsg)) {
                                    String message = "Could not create foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg;
                                    Debug.logError(message, module);
                                    if (messages != null) messages.add(message);
                                } else {
                                    String message = "Created foreign key " + relConstraintName + " for entity [" + entity.getEntityName() + "]";
                                    Debug.logVerbose(message, module);
                                    if (messages != null) messages.add(message);
                                    createdConstraints = true;
                                    numFksCreated++;
                                }
                            }
                        }
                    }
                    if (createdConstraints) {
                        String message = "Created foreign key(s) for entity [" + entity.getEntityName() + "]";
                        Debug.logImportant(message, module);
                        if (messages != null) messages.add(message);
                    }

                    // show foreign key references that exist but are unknown
                    if (rcInfoMap != null) {
                        for (String rcKeyLeft: rcInfoMap.keySet()) {
                            String message = "Unknown Foreign Key Constraint " + rcKeyLeft + " found in table " + entity.getTableName(datasourceInfo);
                            Debug.logImportant(message, module);
                            if (messages != null) messages.add(message);
                        }
                    }
                }
            }
            if (Debug.infoOn()) Debug.logInfo("Created " + numFksCreated + " fk refs", module);
        }

        // make sure each one-relation has an index
        if (checkFkIdx || datasourceInfo.checkIndicesOnStart) {
        //if (!justColumns && datasourceInfo.useFkIndices && datasourceInfo.checkFkIndicesOnStart) {
            int numIndicesCreated = 0;
            // TODO: check each key-map to make sure it exists in the index, if any differences warn and then remove the index and recreate it

            // get ALL column info, put into hashmap by table name
            boolean needsUpperCase[] = new boolean[1];
            Map<String, Set<String>> tableIndexListMap = this.getIndexInfo(indexTableNames, messages, needsUpperCase);

            // Debug.logVerbose("Ref Info Map: " + refTableInfoMap, module);

            if (tableIndexListMap == null) {
                // uh oh, something happened while getting info...
                if (Debug.verboseOn()) Debug.logVerbose("Ref Table Info Map is null", module);
            } else {
                for (ModelEntity entity: modelEntityList) {
                    String entityName = entity.getEntityName();
                    // if this is a view entity, do not check it...
                    if (entity instanceof ModelViewEntity) {
                        String entMessage = "NOT Checking View Entity " + entity.getEntityName();
                        Debug.logVerbose(entMessage, module);
                        if (messages != null) messages.add(entMessage);
                        continue;
                    }

                    // get existing index list for this table
                    Set<String> tableIndexList = tableIndexListMap.get(entity.getTableName(datasourceInfo));

                    // Debug.logVerbose("Got ind info for table " + entity.getTableName(datasourceInfo) + ": " + tableIndexList, module);

                    if (tableIndexList == null) {
                        // evidently no indexes in the database for this table, do the create all
                        if (checkFkIdx) {
                            this.createForeignKeyIndices(entity, datasourceInfo.constraintNameClipLength, messages);
                        }
                        if (datasourceInfo.checkIndicesOnStart) {
                            this.createDeclaredIndices(entity, messages);
                        }
                        continue;
                    }
                    // go through each relation to see if an FK already exists
                    boolean createdConstraints = false;
                    Iterator<ModelRelation> relations = entity.getRelationsIterator();
                    while (relations.hasNext()) {
                        ModelRelation modelRelation = relations.next();
                        if (!"one".equals(modelRelation.getType())) {
                            continue;
                        }

                        String relConstraintName = makeFkConstraintName(modelRelation, datasourceInfo.constraintNameClipLength);
                        if (tableIndexList.contains(relConstraintName)) {
                            tableIndexList.remove(relConstraintName);
                        } else {
                            if (checkFkIdx) {
                                // if not, create one
                                String noIdxMessage = "No Index [" + relConstraintName + "] found for entity [" + entityName + "]";
                                if (messages != null) messages.add(noIdxMessage);
                                if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module);

                                if (addMissing) {
                                    String errMsg = createForeignKeyIndex(entity, modelRelation, datasourceInfo.constraintNameClipLength);
                                    if (UtilValidate.isNotEmpty(errMsg)) {
                                        String message = "Could not create foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]: " + errMsg;
                                        Debug.logError(message, module);
                                        if (messages != null) messages.add(message);
                                    } else {
                                        String message = "Created foreign key index " + relConstraintName + " for entity [" + entity.getEntityName() + "]";
                                        Debug.logVerbose(message, module);
                                        if (messages != null) messages.add(message);
                                        createdConstraints = true;
                                        numIndicesCreated++;
                                    }
                                }
                            }
                        }
                    }

                    if (createdConstraints) {
                        String message = "Created foreign key index/indices for entity [" + entity.getEntityName() + "]";
                        Debug.logImportant(message, module);
                        if (messages != null) messages.add(message);
                    }
                    // go through each indice to see if an indice already exists
                    boolean createdIndexes = false;
                    Iterator<ModelIndex> indexes = entity.getIndexesIterator();
                    while (indexes.hasNext()) {
                        ModelIndex modelIndex = indexes.next();

                        String relIndexName = makeIndexName(modelIndex, datasourceInfo.constraintNameClipLength);
                        String checkIndexName = needsUpperCase[0] ? relIndexName.toUpperCase() : relIndexName;
                        if (tableIndexList.contains(checkIndexName)) {
                            tableIndexList.remove(checkIndexName);
                        } else {
                            if (datasourceInfo.checkIndicesOnStart) {
                                // if not, create one
                                String noIdxMessage = "No Index [" + relIndexName + "] found for entity [" + entityName + "]";
                                if (messages != null) messages.add(noIdxMessage);
                                if (Debug.infoOn()) Debug.logInfo(noIdxMessage, module);

                                if (addMissing) {
                                    String errMsg = createDeclaredIndex(entity, modelIndex);
                                    if (UtilValidate.isNotEmpty(errMsg)) {
                                        String message = "Could not create index " + relIndexName + " for entity [" + entity.getEntityName() + "]: " + errMsg;
                                        Debug.logError(message, module);
                                        if (messages != null) messages.add(message);
                                    } else {
                                        String message = "Created index " + relIndexName + " for entity [" + entity.getEntityName() + "]";
                                        Debug.logVerbose(message, module);
                                        if (messages != null) messages.add(message);
                                        createdIndexes = true;
                                        numIndicesCreated++;
                                    }
                                }
                            }
                        }
                    }
                    if (createdIndexes) {
                        String message = "Created declared index/indices for entity [" + entity.getEntityName() + "]";
                        Debug.logImportant(message, module);
                        if (messages != null) messages.add(message);
                    }

                    // show Indexe key references that exist but are unknown
                    if (tableIndexList != null) {
                        for (String indexLeft: tableIndexList) {
                            String message = "Unknown Index " + indexLeft + " found in table " + entity.getTableName(datasourceInfo);
                            Debug.logImportant(message, module);
                            if (messages != null) messages.add(message);
                        }
                    }
                }
            }
            if (numIndicesCreated > 0 && Debug.infoOn()) Debug.logInfo("Created " + numIndicesCreated + " indices", module);

        }


        timer.timerString("Finished Checking Entity Database");
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

    // UPDATE - Updates a set of entities in the data base.
    //-------------------------------------------------------------------------
    public int processUpdate(UserInfo userInfo, GenericDelegator delegator,
        DataMatrix dataMatrix) throws GenericEntityException {

        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(2, "[GenericEventProcessor.processUpdate] Start");
        }

        int status = STATUS_CONTINUE;

        // Trigger the pre-update event.
        status = this.preUpdate(userInfo, delegator, dataMatrix);

        if (status != STATUS_CONTINUE) {
            return status;
        }

        if (TIMER) {
            timer.timerString(2,
                "[GenericEventProcessor.processUpdate] Preupdate finished");
        }

        // Trigger the update event.
        status = this.update(userInfo, delegator, dataMatrix);

        if (status != STATUS_CONTINUE) {
            return status;
        }

        if (TIMER) {
            timer.timerString(2,
                "[GenericEventProcessor.processUpdate] Update finished");
        }

        // Trigger the post-update event.
        status = this.postUpdate(userInfo, delegator, dataMatrix);

        if (TIMER) {
            timer.timerString(2,
                "[GenericEventProcessor.processUpdate] Postupdate finished");
        }

        if (TIMER) {
            timer.timerString(2, "[GenericEventProcessor.processUpdate] End");
        }

        return status;
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

     * @throws GenericEntityException
     */
    public int update(UserInfo userInfo, GenericDelegator delegator,
        DataMatrix dataMatrix) throws GenericEntityException {

        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(2, "[GenericEventProcessor.update] Start");
        }

        for (int row = 0; row < dataMatrix.getOriginalBuffer().getRowCount();
                row++) {
            if (TIMER) {
                timer.timerString(2, "[GenericEventProcessor.update] Saving row");
            }

            boolean rowChanged = dataMatrix.getRowChanged(row);

            if (rowChanged) {
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

        }
        if (rname.indexOf('/') > 0) {
            rname = rname.substring(0, rname.indexOf('/'));
        }

        UtilTimer timer = null;
        if (Debug.timingOn()) {
            timer = new UtilTimer();
            timer.setLog(true);
            timer.timerString("[" + rname + "] Servlet Starting, doing setup", module);
        }
       
        // Setup the CONTROL_PATH for JSP dispatching.
        request.setAttribute("_CONTROL_PATH_", request.getContextPath() + request.getServletPath());
        if (Debug.verboseOn())
            Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);

        // for convenience, and necessity with event handlers, make security and delegator available in the request:
        // try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
        GenericDelegator delegator = null;
        String delegatorName = (String) session.getAttribute("delegatorName");
        if (UtilValidate.isNotEmpty(delegatorName)) {
            delegator = GenericDelegator.getGenericDelegator(delegatorName);
        }
        if (delegator == null) {
            delegator = (GenericDelegator) getServletContext().getAttribute("delegator");
        }
        if (delegator == null) {
            Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
        } else {
            request.setAttribute("delegator", delegator);
            // always put this in the session too so that session events can use the delegator
            session.setAttribute("delegatorName", delegator.getDelegatorName());
        }

        // display details on the servlet objects
        if (Debug.verboseOn()) {
            logRequestInfo(request);
        }

    int fyStartMonth = CalendarUtil.getFiscalYearStartMonth( delegator, userInfo );
        if (Debug.timingOn()) timer.timerString("[" + rname + "] Setup done, doing Event(s) and View(s)", module);

    try {
    String monthLabel[] = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    BarChartProperties properties = new BarChartProperties();
    AxisProperties axisProperties = new AxisProperties();
    axisProperties.setScaleFont( new Font( "Arial", Font.BOLD, 12 ) );
    axisProperties.setAxisTitleFont( new Font( "Arial", Font.BOLD, 12 ) );
    axisProperties.setYAxisUseDollarSigns(true);

    LineChartProperties lineChartProperties = new LineChartProperties(new BasicStroke());


    Paint[] paints= { new Color(100,150,100) };
    int width = 330;
    int height = 216;
    String xAxisTitle = " ";
    String yAxisTitle = " ";

    ArrayList xAxisLabels = new ArrayList();
    ArrayList legendLabels = new ArrayList();

    if(request.getParameter("report").equals("salesForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("ownerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("dealStatusId", EntityOperator.EQUALS, "10"));
    list.add(new EntityExpr("actualCloseDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("actualCloseDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("actualCloseDate");

    java.util.List dealList = delegator.findByAnd("Deal", list, order);
    GenericValue dealValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue dealValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }

    xAxisTitle = "Month";
    yAxisTitle = "Sales";

    legendLabels.add("Pipeline for Quarter");

    for(int iz=0;iz<dealValues.length;iz++) {
      dealValue = dealValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dealValue.getDate("actualCloseDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + dealValue.getDouble("amount").doubleValue();
      }
    }

      try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
           
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { throwable.printStackTrace();
      }
    }

    if(request.getParameter("report").equals("leadsForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("leadOwnerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("statusId", EntityOperator.EQUALS, "50"));
    list.add(new EntityExpr("convertedDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("convertedDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("convertedDate");

    java.util.List dealList = delegator.findByAnd("Lead", list, order);
    GenericValue leadValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue leadValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }
    xAxisTitle = "Month";
    yAxisTitle = "Leads";

    legendLabels.add("Leads for Quarter");

    for(int iz=0;iz<leadValues.length;iz++) {
      leadValue = leadValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(leadValue.getTimestamp("convertedDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + 1;
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + 1;
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + 1;
      }
    }

    axisProperties.setYAxisUseDollarSigns(false);
    axisProperties.setYAxisRoundValuesToNearest(0);
//      axisProperties.setXAxisVerticalScaleFlag(true);

    try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { throwable.printStackTrace();
      }
    }

    if(request.getParameter("report").equals("forecastedForQuarter")){
    double data[] = new double[3];
    Calendar cal = Calendar.getInstance();

    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int quarterNumbers[] = CalendarUtil.getQuarterMonthNumbers(month, fyStartMonth);

    ArrayList list = new ArrayList();
    list.add(new EntityExpr("ownerId", EntityOperator.EQUALS, userInfo.getPartyId()));
    list.add(new EntityExpr("projectedCloseDate", EntityOperator.LESS_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMaximumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));
    list.add(new EntityExpr("projectedCloseDate", EntityOperator.GREATER_THAN_EQUAL_TO, new java.sql.Date( CalendarUtil.getMinimumQuarterDate(cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), fyStartMonth).getTime())));

    ArrayList order = new ArrayList();
    order.add("projectedCloseDate");

    java.util.List dealList = delegator.findByAnd("Deal", list, order);
    GenericValue dealValues[] = (GenericValue[])dealList.toArray(new GenericValue[0]);
    GenericValue dealValue = null;

    String months[] = CalendarUtil.getQuarterMonthNames(cal.get(Calendar.MONTH) + 1, fyStartMonth);
    for(int iz=0;iz<months.length;iz++){
      xAxisLabels.add((String)months[iz]);
    }

    xAxisTitle = "month";
    yAxisTitle = "sales";

    legendLabels.add("Forecasted Sales for Quarter");

    for(int iz=0;iz<dealValues.length;iz++) {
      dealValue = dealValues[iz];
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(dealValue.getDate("projectedCloseDate"));

      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[0] && calendar.get(Calendar.YEAR)==year){
        data[0] = data[0] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[1] && calendar.get(Calendar.YEAR)==year){
        data[1] = data[1] + dealValue.getDouble("amount").doubleValue();
      }
      if((calendar.get(Calendar.MONTH)+1)==quarterNumbers[2] && calendar.get(Calendar.YEAR)==year){
        data[2] = data[2] + dealValue.getDouble("amount").doubleValue();
      }
    }

      try {
      BarChart barChart = new BarChart(
        new SingleDataSet(
        data,
        (String[])legendLabels.toArray(new String[0]),
        (String[])xAxisLabels.toArray(new String[0]),
        paints,
        xAxisTitle,
        yAxisTitle ),
      false, properties, axisProperties, width, height );

      response.reset();
      response.setContentType("image/jpeg");
      barChart.exportJPG( response.getOutputStream(), 1.0f);
      response.getOutputStream().flush();
      } catch( Throwable throwable ) { Debug.logError("error creating bar chart", module);throwable.printStackTrace();
      }
    }

  } catch ( Exception e2 ) { Debug.logError("error creating chart", module); }

    if (Debug.timingOn()) timer.timerString("[" + rname + "] Done rendering page, Servlet Finished", module);               
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

     * @throws GenericEntityException
     */
    public String displayFreeFormSection(DataMatrix dataMatrix, String action,
        String sectionTitle, boolean isSubsection, int tabOffset)
        throws GenericEntityException {
        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(1,
                "[UIWebScreenSection.displayFreeFormSection] Start");
        }

        Debug.logVerbose("[displayFreeFormSection] Start", module);

        Vector entityDetailsVector = dataMatrix.getCurrentBuffer()
                                               .getContentsRow(0);
        GenericValue primaryEntityDetails = dataMatrix.getCurrentBuffer()
                                                      .getGenericValue(0, 0);

            Debug.logVerbose("[displayFreeFormSection()] Primary entity name: " +
                primaryEntityDetails.getEntityName(), module);

        StringBuffer displayHtml = new StringBuffer(5000);

        // Get the key values so the form can pass them to the next page for the 4 buttons.
        String keyParams = UIWebUtility.getHiddenArgs(getButtonKeyMap(),
                entityDetailsVector, "       ");

        // Get the extra query parameters so the form can pass them to the next page.
        String sendQueryParams = UIWebUtility.getHiddenArgs(getSendQueryParameterValueMap(),
                "       ");

            Debug.logVerbose("[displayFreeFormSection] sendQueryParams: " +
                sendQueryParams, module);

        String keyUrlArgs = UIWebUtility.getUrlArgs(getButtonKeyMap(),
                entityDetailsVector);
        String queryUrlArgs = UIWebUtility.getUrlArgs(getSendQueryParameterMap(),
                entityDetailsVector);

        // Append script to refresh the list or detail section when this free form section is saved.
        if (!getDetailButtonTarget().equals("") && !isSubsection &&
                (action.equals(ACTION_UPDATE) || action.equals(ACTION_INSERT) ||
                action.equals(ACTION_DELETE))) {
            displayHtml.append(
                "<SCRIPT FOR=\"window\" EVENT=\"onload\" LANGUAGE=\"JavaScript\">\n");

            if (WEB_DEBUG) {
                displayHtml.append("  alert('parent." +
                    getDetailButtonTarget() + ".location.href = ' + parent." +
                    getDetailButtonTarget() + ".location.href)\n");
            }

            displayHtml.append("  if (parent." + getDetailButtonTarget() +
                ".location.href.indexOf('" +
                getDetailButtonAction().substring(13) + "') > 0) {\n");
            displayHtml.append(
                "   // This is the detail section of the current screen section.  Refresh it with new arguments.\n");

            if (WEB_DEBUG) {
                displayHtml.append(
                    "   alert('Reloading related section using HREF: " +
                    getDetailButtonAction() + "?x=" + keyUrlArgs +
                    queryUrlArgs + "');\n");
            }

            displayHtml.append("   parent." + getDetailButtonTarget() +
                ".location.href = \"" + getDetailButtonAction() + "?x=" +
                keyUrlArgs + queryUrlArgs + "\";\n");
            displayHtml.append("  } else {\n");
            displayHtml.append(
                "   // This is a list section.  Refresh it with same arguments used last time.\n");

            if (WEB_DEBUG) {
                displayHtml.append(
                    "   alert('Reloading related section using HREF: ' + parent." +
                    getDetailButtonTarget() + ".location.href);\n");
            }

            displayHtml.append("   parent." + getDetailButtonTarget() +
                ".location.href = parent." + getDetailButtonTarget() +
                ".location.href;\n");
            displayHtml.append("  }\n");
            displayHtml.append("</SCRIPT>\n");
        }

        // Insert the preSubmit function to prevent the onBeforeUnload popup window from being displayed
        // if the Save button was just clicked.
        if (getIsUpdateable()) {
            displayHtml.append("<SCRIPT LANGUAGE=\"JavaScript\">\n");
            displayHtml.append(" function preSubmit" + getSectionName() +
                "() {\n");
            displayHtml.append("  // Prevent the onBeforeUnload popup window\n");
            displayHtml.append("  window.onbeforeunload = null;\n");
            displayHtml.append("  return false;\n");
            displayHtml.append(" }\n");
            displayHtml.append("</SCRIPT>\n");
        }

        displayHtml.append(
            "   <TABLE WIDTH=\"100%\" CLASS=\"freeFormSectionTitleTable\">\n");
        displayHtml.append("    <TR>\n");

        String titleTdName = getSectionName() + "TitleTD";
        displayHtml.append("     <TD NAME=\"" + titleTdName + "\" ID=\"" +
            titleTdName + "\">\n");
        displayHtml.append(sectionTitle + "\n");
        displayHtml.append("     </TD>\n");
        displayHtml.append("     <TD ALIGN=\"right\">\n");
        displayHtml.append("      <TABLE>\n");
        displayHtml.append("       <TR>\n");
        displayHtml.append("\n");

        if (!isSubsection) {
            // Buttons with configurable targets.
            // Don't send query parameters when the new button is clicked from a free-form tab. This will
            // prevent fields from be initialized to the same as the current record.
            displayHtml.append(displayNewButton("", action));
            displayHtml.append(displayEditButton(action, keyParams,
                    sendQueryParams, ACTION_BUTTON));
            displayHtml.append(displayDetailButton(keyParams, sendQueryParams,
                    action));

            // Buttons with same target as current window.
            displayHtml.append("     <TD>\n");
            displayHtml.append("      <FORM NAME=\"" + getSectionName() +
                "FormButton\" METHOD=\"post\"" + " ACTION=\"" +
                getButtonAction() + "\"");

            if ((getButtonTarget() != null) && !getButtonTarget().equals("")) {
                displayHtml.append(" TARGET=\"" + getButtonTarget() + "\"");
            }

            displayHtml.append(">\n");
            displayHtml.append(keyParams);
            displayHtml.append(sendQueryParams);
            displayHtml.append(
                "       <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
                ACTION_BUTTON + "\">\n");

            displayHtml.append(displayQueryButton(action));
            displayHtml.append(displayDeleteButton(action));
            displayHtml.append(displayCopyButton(action));
            displayHtml.append(displayPrintButton(action));
            displayHtml.append("      </FORM>\n");
            displayHtml.append("     </TD>\n");
            displayHtml.append("\n");

            displayHtml.append(displayCustomizeButton());
        }

        displayHtml.append("       </TR>\n");
        displayHtml.append("      </TABLE>\n");
        displayHtml.append("     </TD>\n");
        displayHtml.append("    </TR>\n");
        displayHtml.append("   </TABLE>\n");
        displayHtml.append("\n");

        if (TIMER) {
            timer.timerString(1,
                "[UIWebScreenSection.displayFreeFormSection] Finished title bar");
        }

        displayHtml.append("   <TABLE CLASS=\"freeFormSectionDisplayTable\" ");

        if (!isSubsection) {
//            displayHtml.append("HEIGHT=\"100%\"");
        }

        displayHtml.append(">\n");

        if (!isSubsection) {
            boolean isMultiPart = false;

            for (int fieldNbr = 0; fieldNbr < getUiFieldList().size();
                    fieldNbr++) {
                UIFieldInfo fieldInfo = getUiField(fieldNbr);
                UIDisplayObject uiDisplayObject = fieldInfo.getUiDisplayObject();

                if (uiDisplayObject.getDisplayTypeId().equals(UIDisplayObject.DISPLAY_TYPE_FILE)) {
                    isMultiPart = true;

                    break;
                }
            }

            displayHtml.append("    <FORM METHOD=\"post\" NAME=\"" +
                getSectionName() + "Form\"" + " onSubmit=\"preSubmit" +
                getSectionName() + "()\"");

            if (action.equals(ACTION_SHOW_QUERY) ||
                    action.equals(ACTION_SHOW_QUERY_REPORT) ||
                    action.equals(ACTION_SHOW_REPORT)) {
                Debug.logVerbose("[displayFreeFormSection] search action: " +
                        getSearchAction(), module);
                Debug.logVerbose("[displayFreeFormSection] search target: " +
                        getSearchTarget(), module);

                displayHtml.append(" ACTION=\"" + getSearchAction() + "\"");

                if ((getSearchTarget() != null) &&
                        !getSearchTarget().equals("")) {
                    displayHtml.append(" TARGET=\"" + getSearchTarget() + "\"");
                }
            } else {
                displayHtml.append(" ACTION=\"" + getButtonAction() + "\"");

                if ((getButtonTarget() != null) &&
                        !getButtonTarget().equals("")) {
                    displayHtml.append(" TARGET=\"" + getButtonTarget() + "\"");
                }
            }

            if (isMultiPart) {
                displayHtml.append(" enctype=\"multipart/form-data\"");
            }

            displayHtml.append(">\n");
        }

        displayHtml.append(
            "     <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
            getNextAction(action) + "\">\n");
        displayHtml.append(
            "     <INPUT TYPE=\"hidden\" NAME=\"rowCount\" VALUE=\"1\">\n");
        displayHtml.append(sendQueryParams);

        int htmlColumnCount = 0;
        int htmlRowCount = 0;
    ArrayList requiredFields = new ArrayList();

    if ( action.equals(ACTION_SHOW_QUERY) && getQueryMode().equals("advanced") )
    {
      int fieldListSize = getUiFieldList().size();
     
      StringBuffer fieldNameOptions = new StringBuffer(200);
      fieldNameOptions.append("<option value=''></option>");
      for (int fieldNbr = 0; fieldNbr < fieldListSize; fieldNbr++) {
        UIFieldInfo fieldInfo = getUiField(fieldNbr);
        if (fieldInfo.getIsSearchable()) {
          String htmlName = UIWebUtility.getHtmlName(getSectionName(), fieldInfo,0);
          String displayObjectId = fieldInfo.getDisplayObjectId();
          String displayTypeId = fieldInfo.getUiDisplayObject().getDisplayTypeId();
          String attributeId = fieldInfo.getAttributeId();
          String optValue = htmlName + ";" + attributeId + ";" + displayTypeId + ";" + displayObjectId;
          fieldNameOptions.append("<option value='" + optValue + "'>" + fieldInfo.getDisplayLabel() + "</option>")
        }

      }

      List extendedFields = getRelatedSectionQueryFields();
      if ( extendedFields != null )
      {
        int numFields = extendedFields.size();
        for ( int i=0; i < numFields; i++)
        {
          GenericValue fieldInfo = (GenericValue) extendedFields.get(i);
          String entityName = fieldInfo.getString("entityName");
          String attributeId = fieldInfo.getString("attributeId");
          String attributeName = fieldInfo.getString("attributeName");
          String displayObjectId = fieldInfo.getString("displayObjectId");
          String displayTypeId = fieldInfo.getString("displayTypeId");
          String sectionName = fieldInfo.getString("sectionName");
          String sectionDescription = fieldInfo.getString("sectionDescription");
          String displayLabel = fieldInfo.getString("displayLabel");
          String htmlName = UIWebUtility.getHtmlName( sectionName, entityName, attributeName, 0 );
          String optValue = htmlName + ";" + attributeId + ";" + displayTypeId + ";" + displayObjectId;
          displayLabel = sectionDescription + "." + displayLabel;
          fieldNameOptions.append("<option value='" + optValue + "'>" + displayLabel + "</option>")
        }
      }
     
      StringBuffer conditionOptions = new StringBuffer(100);
      conditionOptions.append("<option value='startsWith'>STARTS WITH</option>");
      conditionOptions.append("<option value='equals'>=</option>");
      conditionOptions.append("<option value='like'>CONTAINS</option>");
      conditionOptions.append("<option value='endsWith'>ENDS WITH</option>");
      conditionOptions.append("<option value='equals'>=</option>");
      conditionOptions.append("<option value='notEqual'>NOT EQUAL</option>");
      conditionOptions.append("<option value='lessThan'>&lt;</option>");
      conditionOptions.append("<option value='greaterThan'>&gt;</option>");
      conditionOptions.append("<option value='lessThanEqualTo'>&lt;=</option>");
      conditionOptions.append("<option value='greaterThanEqualTo'>&gt;=</option>");
      conditionOptions.append("<option value='in'>IN</option>");
      conditionOptions.append("<option value='not-in'>NOT IN</option>");
      conditionOptions.append("<option value='between'>BETWEEN</option>");

     
      displayHtml.append("<table id='queryListTable' border=1>\n");
      displayHtml.append("<tr><td>Field</td><td>Condition</td><td>Value</td><td>Action</td></tr>\n");

      // default show 4 rows
      for ( int i=1; i < 5; i++)
      {
        displayHtml.append("<tr id=queryListRow" + i + "><td><select name=queryListField" + i + ">" +  fieldNameOptions.toString() + "</select></td>\n");
        displayHtml.append("  <td><select name=queryListOperator" + i + ">" + conditionOptions.toString() + "</select></td>\n");
        displayHtml.append("  <td><input name=queryListValue" + i + " size=60></td>\n");
        displayHtml.append("  <td><img src=/sfaimages/remove.gif alt=Del onClick=delConditionRow(" + i + ")>\n");
        displayHtml.append("      <img src=/sfaimages/add.gif alt=Add onClick=addConditionRow(" + i + ")></td>\n");
        displayHtml.append("</tr>");
       
      }

      displayHtml.append("</table>\n");
      displayHtml.append("<input type=hidden id=queryListMaxRows name=queryListMaxRows value=4>\n");     

      displayHtml.append("<script type='text/javascript'>\n");
      displayHtml.append("function addConditionRow(i) {\n");
      displayHtml.append("  var tab1=document.getElementById('queryListTable')\n");
      displayHtml.append("  if ( tab1 ) {\n");
      displayHtml.append("    var numRows = tab1.rows.length\n");
      displayHtml.append("    var maxRows = 10\n");
      displayHtml.append("    if ( numRows > maxRows )\n");
      displayHtml.append("      alert(\"Can't have more than 10 conditions\");\n");
      displayHtml.append("    else {\n");
      displayHtml.append("      var x = tab1.insertRow(numRows)\n");
      displayHtml.append("      var maxRows = document.getElementById('queryListMaxRows')\n");
      displayHtml.append("      var newRow = maxRows.value -  -1\n");
      displayHtml.append("      maxRows.value = newRow\n");
      displayHtml.append("      x.id = \"queryListRow\" + newRow\n");
      displayHtml.append("      var c1=x.insertCell(0)\n");
      displayHtml.append("      var c2=x.insertCell(1)\n");
      displayHtml.append("      var c3=x.insertCell(2)\n");
      displayHtml.append("      var c4=x.insertCell(3)\n");
      displayHtml.append("      c1.innerHTML=\"<select name=queryListField\" + newRow + \">" + fieldNameOptions.toString() + "</select>\"\n");
      displayHtml.append("      c2.innerHTML=\"<select name=queryListOperator\" + newRow + \">" + conditionOptions.toString() +"</select>\"\n");
      displayHtml.append("      c3.innerHTML=\"<input name=queryListValue\" + newRow + \" size=60>\"\n");
      displayHtml.append("      c4.innerHTML=\"<img src=/sfaimages/remove.gif alt=Del onClick=delConditionRow(\" + newRow + \")>\" + \" <img src=/sfaimages/add.gif alt=Add onClick=addConditionRow(\" + newRow + \")>\"\n");

      displayHtml.append("    }\n");
      displayHtml.append("    fixSize()\n");
      displayHtml.append("  }\n");
      displayHtml.append("}\n");
       
      displayHtml.append("function delConditionRow(i)\n");
      displayHtml.append("{\n");
      displayHtml.append("  var row1 = document.getElementById('queryListRow' + i)\n");
      displayHtml.append("  var tab = document.getElementById('queryListTable')\n");
      displayHtml.append("  var rows = tab.rows\n");
      displayHtml.append("  if ( rows.length == 2 ) {\n");
      displayHtml.append("    event.returnValue = false\n");
      displayHtml.append("    return;\n");
      displayHtml.append("  }\n");
      displayHtml.append("  for ( i=0; i < rows.length; i++ ) {\n");
      displayHtml.append("    row = rows[i];\n");
      displayHtml.append("    if ( row.id == row1.id) {\n");
      displayHtml.append("      tab.deleteRow(i);\n");
      displayHtml.append("      break;\n");
      displayHtml.append("    }\n");
      displayHtml.append("  }\n");
      displayHtml.append("  fixSize()\n");
      displayHtml.append("}\n");   
   
      displayHtml.append("</script>\n");
     
    }
    else
    {
        int column = 1;
        int row = 1;
        boolean[][] cellUsed = new boolean[100][20];
        boolean trOpen = false;

          if (TIMER) {
              timer.timerString(1,
                  "[UIWebScreenSection.displayFreeFormSection] Finished preparing form");
          }
 
      int fieldListSize = getUiFieldList().size();
          for (int fieldNbr = 0; fieldNbr < fieldListSize; fieldNbr++) {
              if (TIMER) {
                  timer.timerString(1,
                      "[UIWebScreenSection.displayFreeFormSection] Start field " +
                      String.valueOf(fieldNbr));
              }
 
              UIFieldInfo fieldInfo = getUiField(fieldNbr);
 
              // Multiply the column count by 2 since we need space for the labels, too.
              htmlColumnCount = (getColumnCount() > 1) ? (getColumnCount() * 2) : 2;
 
              int rowSpan = (fieldInfo.getRowSpan() < 2) ? 1
                                                         : fieldInfo.getRowSpan();
 
              // Double the col span and then substract one from the label to get the actual col span of the data field.
              int colSpan = (fieldInfo.getColSpan() < 2) ? 1
                                                         : ((fieldInfo.getColSpan() * 2) -
                  1);
              int displayOrder = fieldInfo.getDisplayOrder();
              String attributeName = fieldInfo.getUiAttribute().getAttributeName();
              int fieldWidth = fieldInfo.getDisplayLength();
              boolean startOnNewRow = fieldInfo.getStartOnNewRow();
 
              if (fieldInfo.getIsVisible()) {
 
          if ( (startOnNewRow ) && (column > 1) )
          {
            int numCellsSkipped = 0;
            for ( int i = column; i <= htmlColumnCount; i++)
            {
              if ( !cellUsed[row][i])
                numCellsSkipped++;
              cellUsed[row][i] = true;
            }               
            if ( numCellsSkipped > 0)
              displayHtml.append("<TD class=freeFormSectionField colspan=" + numCellsSkipped +"></TD>");
          }
                  if (column == 1) {
                      // We are at the beginning of a new row.
                      Debug.logVerbose("[displayFreeFormSection] Starting row " +
                              String.valueOf(row), module);
 
                      displayHtml.append("     <TR>");
                      trOpen = true;
                  }
 
                  // Skip cells already used by fields that were taller or wider than one cell.
                  while (cellUsed[row][column]) {
                      column++;
 
                      if (column > htmlColumnCount) {
                          if (trOpen) {
                              displayHtml.append("     </TR>\n");
                              trOpen = false;
                          }
 
                          Debug.logVerbose("[displayFreeFormSection] Ending row " +
                                  String.valueOf(row) + " (skipped used cells)", module);
 
                          column = 1;
                          row++;
 
                          Debug.logVerbose("[displayFreeFormSection] Starting row " +
                                  String.valueOf(row) + " (skipped used cells)", module);
 
                          displayHtml.append("     <TR>");
                          // + " HEIGHT=\"" +
                          //    String.valueOf(FREE_FORM_ROW_HEIGHT) + "\">\n");
                          trOpen = true;
                      }
                  }
 
                  if (fieldInfo.getIsMandatory() && !getProtect(action)) {
                      displayHtml.append(
                          "      <TD CLASS=\"freeFormSectionLabel\"");
                  } else {
                      displayHtml.append(
                          "      <TD CLASS=\"freeFormSectionLabelOptional\"");
                  }
 
                  if (rowSpan > 1) {
                      displayHtml.append(" ROWSPAN=\"" + String.valueOf(rowSpan) +
                          "\"");
                  }
 
                  displayHtml.append(">\n");
 
                  Debug.logVerbose("[displayFreeFormSection] Displaying label " +
                          fieldInfo.getDisplayLabel() + " at row " +
                          String.valueOf(row) + " column " +
                          String.valueOf(column), module);
 
                  displayHtml.append("        " + fieldInfo.getDisplayLabel() +
                      ":\n");
                  displayHtml.append("      </TD>\n");
                  displayHtml.append("      <TD CLASS=\"freeFormSectionField\"");
 
                  if (rowSpan > 1) {
                      displayHtml.append(" ROWSPAN=\"" + String.valueOf(rowSpan) +
                          "\"");
                  }
 
                  if (colSpan > 1) {
                      displayHtml.append(" COLSPAN=\"" + String.valueOf(colSpan) +
                          "\"");
                  }
 
                  displayHtml.append(">\n");
              }
 
              // Write all fields with display order greater than zero.  The ones that are not visible
              // may be created as hidden fields.
              if ( fieldInfo.getIsVisible() || ( (fieldInfo.getDisplayOrder() > 0) && ( fieldInfo.getUiDisplayObject().getDisplayTypeId().equals(UIDisplayObject.DISPLAY_TYPE_HIDDEN) ) ) )
              {
              displayHtml.append(displayField(fieldInfo, entityDetailsVector,
                      action, 0, isSubsection, tabOffset));
              displayHtml.append("\n");
              }
 
              // If this is a required field, add it to the list of fields to be validated.
              if (fieldInfo.getIsVisible() && fieldInfo.getIsMandatory()) {
                  requiredFields.add(fieldInfo);
              }
 
              if (fieldInfo.getIsVisible()) {
                  // Close the cell.
                  displayHtml.append("      </TD>\n");
 
                  // Mark used cells in the matrix.
                  // Mark all used rows.
                  for (int markRow = row; markRow < (row + rowSpan); markRow++) {
                      // Mark all used columns, including the label.  That's why we have to add 1 here:
                      for (int markColumn = column;
                              markColumn < (column + colSpan + 1);
                              markColumn++) {
                          cellUsed[markRow][markColumn] = true;
                      }
                  }
 
 
                  // Get ready for next time through the loop by adding the column span plus 1 for the label.
                  column += (1 + colSpan);
 
                  if (column > htmlColumnCount) {
                      Debug.logVerbose("[displayFreeFormSection] Ending row " +
                              String.valueOf(row), module);
 
                      if (trOpen) {
                          displayHtml.append("     </TR>\n");
                          trOpen = false;
                      }
 
                      column = 1;
                      row++;
                  }
              }
          }
 
          if (TIMER) {
              timer.timerString(1,
                  "[UIWebScreenSection.displayFreeFormSection] Finished fields");
          }
 
          if (trOpen) {
              displayHtml.append("     </TR>\n");
              trOpen = false;
          }
 
          displayHtml.append("\n");
    }
   
        if (!isSubsection) {
            displayHtml.append("     <TR HEIGHT=\"*\">\n");
            displayHtml.append(
                "      <TD CLASS=\"freeFormSectionSaveButtonArea\" COLSPAN=\"" +
                String.valueOf(htmlColumnCount) + "\">\n");

            if (action.equals(ACTION_SHOW_QUERY) ||
                    action.equals(ACTION_SHOW_QUERY_REPORT) ||
                    action.equals(ACTION_SHOW_REPORT)) {
                displayHtml.append("       Save Query  Definition:\n");
                displayHtml.append(
                    "       <INPUT TYPE=\"text\" WIDTH=\"40\" NAME=\"queryName\">\n");
        displayHtml.append("       Save Results to List:\n");
        displayHtml.append(
          "       <INPUT TYPE=\"text\" WIDTH=\"40\" NAME=\"listName\">\n");
        displayHtml.append(
          "       <INPUT TYPE=\"submit\" CLASS=\"button\" NAME=\"" +
          getSectionName() +
                    "SaveButton\" VALUE=\"Run/Save Query\">\n");
            } else {
                if (!getProtect(action)) {
                    displayHtml.append(
                        "       <INPUT TYPE=\"submit\" CLASS=\"button\" NAME=\"" +
                        getSectionName() +
                        "SaveButton\" VALUE=\"Save\" onClick=\"return verifyRequired" +
                        getSectionName() + "(this.form)\">\n");
                }
            }

            displayHtml.append("      </TD>\n");
            displayHtml.append("     </TR>\n");
            displayHtml.append("    </FORM>\n");
            displayHtml.append("\n");
        }

        displayHtml.append("   </TABLE>\n");
        displayHtml.append("\n");

        // Add the javascript methods for confirming delete and validating required fields.
        displayHtml.append(UIWebUtility.writeConfirmDeleteScript());
        displayHtml.append(UIWebUtility.writeVerifyRequiredScript(
                getSectionName(), requiredFields));

        if (TIMER) {
            timer.timerString(1,
                "[UIWebScreenSection.displayFreeFormSection] End");
        }

        return displayHtml.toString();
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

        Debug.logVerbose("[displayTabularSection()] Screen name: " +
                getUiScreen().getScreenName() + " - SectionName = " +
                getSectionName(), module);

        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(1,
                "[UIWebScreenSection.displayTabularSection] Start");
        }

        // Get the extra query parameters so the form can pass them to the next page.
        Debug.logVerbose("displayTabularSection] getSendQueryParameterValueMap: " +
                getSendQueryParameterValueMap().toString(), module);

        String sendQueryParams = UIWebUtility.getHiddenArgs(getSendQueryParameterValueMap(),
                "       ");

        Debug.logVerbose("[displayTabularSection] sendQueryParams: " +
                sendQueryParams, module);

        StringBuffer displayHtml = new StringBuffer(5000);

        int row = 0;
        int rows = dataMatrix.getCurrentBuffer().getContents().size();

        hasPriorPage = firstVisibleRow > 0;
        hasNextPage = (rowsPerPage > 0) && (totalRows > rowsPerPage );
        priorPageStartRow = firstVisibleRow - rowsPerPage;

        if (priorPageStartRow < 0) {
            priorPageStartRow = 0;
        }

        nextPageStartRow = firstVisibleRow + rowsPerPage;

        Debug.logVerbose("hasPrior=" + hasPriorPage + ", hasNext=" +
                hasNextPage + ",priorStart=" + priorPageStartRow +
                ",nextStart=" + nextPageStartRow, module);

        /*        int lastVisibleRow = rows + 1;
                int numPages = 1;
                if ( (rowsPerPage > 0) && (rows > rowsPerPage) )
                {
                   lastVisibleRow = firstVisibleRow + rowsPerPage -1;
                   numPages = rows/rowsPerPage;
                   if (rows % rowsPerPage > 0)
                       numPages++;
                }
        */
        displayHtml.append(displayTabularSectionHeader(action, sectionTitle,
                queryId, rows, sendQueryParams));

        Iterator entityDetailsVectorIterator = dataMatrix.getCurrentBuffer()
                                                         .getContents()
                                                         .iterator();

        while (entityDetailsVectorIterator.hasNext()) {
            // Get the next item from the vector of entity vectors.
            Vector entityDetailsVector = (Vector) entityDetailsVectorIterator.next();

            // Display the row of fields.
            displayHtml.append(displayTabularSectionRow(row++, rows,
                    entityDetailsVector, action));
        }

        if (hasPriorPage || hasNextPage) {
            displayHtml.append(displayPageButtons(hasPriorPage,
                    priorPageStartRow, hasNextPage, nextPageStartRow, queryId));
        }

        // Display the closing HTML tags, and the alpha search for the screen section.
        displayHtml.append(displayTabularSectionFooter(action, sendQueryParams, queryId));

        Debug.logVerbose("[displayTabularSection()] Finished Screen name: " +
                getUiScreen().getScreenName() + " - SectionName = " +
                getSectionName(), module);

        if (TIMER) {
            timer.timerString(1,
                "[UIWebScreenSection.displayTabularSection] End");
        }

        return displayHtml.toString();
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

     * @throws GenericEntityException
     */
    public String displayTabularSectionHeader(String action,
        String sectionTitle, String queryId, int rows, String sendQueryParams)
        throws GenericEntityException {
        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionHeader] Start");
        }

        StringBuffer displayHtml = new StringBuffer(2000);

        displayHtml.append("<SCRIPT>\n");
        displayHtml.append(" function selectRow" + getSectionName() +
            "(aLinkObj, aClickedObj) {\n");

        if (WEB_DEBUG) {
            displayHtml.append("  alert('[selectRow" + getSectionName() +
                "] Clicked object name: ' + aClickedObj.name);\n");
        }

        if (WEB_DEBUG) {
            displayHtml.append("  alert('[selectRow" + getSectionName() +
                "] Clicked object ID: ' + aClickedObj.id);\n");
        }

        if (WEB_DEBUG) {
            displayHtml.append("  alert('[selectRow" + getSectionName() +
                "] Clicked object tag name: ' + aClickedObj.tagName);\n");
        }

        displayHtml.append("  if (aClickedObj.tagName == 'TD') {\n");
        displayHtml.append(
            "   // An empty space in the row was clicked.  Go ahead and click the hidden anchor.\n");
        displayHtml.append(
            "   // Note: Catch exception to get rid of the 'undefined error' that pops up if the cancel \n");
        displayHtml.append(
            "   // button is clicked in response to the onBeforeUnload processing.\n");
        displayHtml.append("   try {\n");
        displayHtml.append("    aLinkObj.click();\n");
        displayHtml.append("   } catch (Exception) {\n");
        displayHtml.append("   }\n");
        displayHtml.append("  } else {\n");
        displayHtml.append(
            "   // Either an anchor was clicked by the user, in which case that link\n");
        displayHtml.append(
            "   // will take care of reloading pages, or a drop down was clicked, in which case\n");
        displayHtml.append(
            "   // we don't want to select a new row, or this function is executing a second time\n");
        displayHtml.append(
            "   // as the result of the click() it just triggered on the aLinkObj anchor.\n");
        displayHtml.append("   // Don't do anything here.  \n");
        displayHtml.append("  }\n");
        displayHtml.append(" }\n");

        // Insert the preSubmit function to prevent the onBeforeUnload popup window from being displayed
        // if the Save button was just clicked.
        if (getIsUpdateable()) {
            displayHtml.append(" function preSubmit" + getSectionName() +
                "() {\n");
            displayHtml.append("  // Prevent the onBeforeUnload popup window\n");
            displayHtml.append("  window.onbeforeunload = null;\n");
            displayHtml.append("  return false;\n");
            displayHtml.append(" }\n");
        }

        displayHtml.append("</SCRIPT>\n");
        displayHtml.append("\n");
        displayHtml.append(
            "<SCRIPT LANGUAGE=\"JScript\" TYPE=\"text/javascript\" FOR=\"window\" EVENT=\"onload\">\n");
        displayHtml.append("\n");
        displayHtml.append(
            " // Turn on the scroll bars in case the window object is an Iframe that was\n");
        displayHtml.append(
            " // created to hold a set of tab pages, which don't have any scroll bars.\n");
        displayHtml.append(" document.body.scroll=\"auto\";\n");
        displayHtml.append("\n");
        displayHtml.append("</SCRIPT>\n");
        displayHtml.append("\n");

        displayHtml.append(
            "   <TABLE WIDTH=\"100%\" CLASS=\"tabularSectionTitleTable\">\n");
        displayHtml.append("    <TR>\n");
        displayHtml.append("\n");
        displayHtml.append("     <TD>\n");
        displayHtml.append("      <NOBR>" + sectionTitle + "</NOBR>\n");
        displayHtml.append("     </TD>\n");
        displayHtml.append("     <TD ALIGN=\"right\">\n");
        displayHtml.append("      <TABLE>\n");
        displayHtml.append("       <TR>\n");
        displayHtml.append("\n");
        displayHtml.append(displayQueryPicker(sendQueryParams, queryId));

        if (getLayoutTypeId() != LAYOUT_TYPE_SELECT) {
            displayHtml.append(displayNewButton(sendQueryParams, action));
        }

        if (getIsUpdateable()) {
            displayHtml.append(displayEditButton(action, "", sendQueryParams,
                    ACTION_QUERY_UPDATE));
        }

        if (getLayoutTypeId() == LAYOUT_TYPE_SELECT) {
            // This is actually a select section being displayed in tabular mode. Display the Select
            // button so the user can put it back into Select mode.
            displayHtml.append("     <TD WIDTH=\"70\">\n");
            displayHtml.append("      <FORM NAME=\"" + getSectionName() +
                "FormEditButton\" METHOD=\"post\"" + " ACTION=\"" +
                getButtonAction() + "\"");

            if ((getButtonTarget() != null) && !getButtonTarget().equals("")) {
                displayHtml.append(" TARGET=\"" + getButtonTarget() + "\"");
            }

            displayHtml.append(">\n");
            displayHtml.append(
                "       <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
                ACTION_SHOW_SELECT + "\">\n");
            displayHtml.append(sendQueryParams);
            displayHtml.append(displaySelectButton(action));
            displayHtml.append("      </FORM>\n");
            displayHtml.append("     </TD>\n");
            displayHtml.append("\n");
        }

        displayHtml.append(displayCustomizeButton());
        displayHtml.append("       </TR>\n");
        displayHtml.append("      </TABLE>\n");
        displayHtml.append("     </TD>\n");
        displayHtml.append("    </TR>\n");
        displayHtml.append("   </TABLE>\n\n");

        displayHtml.append("   <TABLE CLASS=\"grid\"  ID=\"table" +
            getSectionName() + "\" WIDTH=\"" + getRowWidth(getUiFieldList()) +
            "\" CELLSPACING=\"0\">\n");

        displayHtml.append("    <THEAD>\n");
        displayHtml.append("     <TR valign=\"middle\">\n");

        // Write out the column headings.
        int tempColumnCount = 0;

        for (int column = 0; column < getUiFieldList().size(); column++) {
            UIFieldInfo fieldInfo = (UIFieldInfo) getUiField(column);

            if (fieldInfo.getIsVisible()) {
                displayHtml.append("      <TD  WIDTH=\"");

                if (fieldInfo.getDisplayLabel().length() > fieldInfo.getDisplayLength()) {
                    displayHtml.append((fieldInfo.getDisplayLabel().length() +
                        35));
                } else {
                    displayHtml.append((fieldInfo.getDisplayLength() + 35));
                }

                displayHtml.append(
                    "\" ><INPUT type=button style='width:100%;height:20;font:12px menu;' value='" +
                    fieldInfo.getDisplayLabel() + "'></TD>\n");
            }

            tempColumnCount++;
        }

        // Column count in database is not used for tabular screen sections.
        setColumnCount(tempColumnCount);

        displayHtml.append("     </TR>\n");
        displayHtml.append("    </THEAD>\n");

        displayHtml.append("    <TBODY ID='tableDetails'>\n");

        if ((getButtonAction() != null) && !getButtonAction().equals("") &&
                (getButtonTarget() != null) && !getButtonTarget().equals("") &&
                getIsUpdateable()) {
            displayHtml.append("     <FORM METHOD=\"post\" NAME=\"" +
                getSectionName() + "Form\"" + " onSubmit=\"preSubmit" +
                getSectionName() + "()\"" + " ACTION=\"" + getButtonAction() +
                "\"");
            displayHtml.append(" TARGET=\"" + getButtonTarget() + "\"");
            displayHtml.append(">\n");
            displayHtml.append(
                "      <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
                getNextAction(action) + "\">\n");
            displayHtml.append(sendQueryParams);
        }

        displayHtml.append(
            "      <INPUT TYPE=\"hidden\" NAME=\"rowCount\" VALUE=\"" +
            String.valueOf(rows) + "\">\n");

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionHeader] End");
        }

        return displayHtml.toString();
    }
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

     * @throws GenericEntityException
     */
    public String displayTabularSectionRow(int row, int rows,
        Vector entityDetailsVector, String action)
        throws GenericEntityException {
        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionRow] Start - row " +
                String.valueOf(row));
        }

        StringBuffer displayHtml = new StringBuffer(200);
        String rowClass = (((row % 2) != 0) ? "light" : "medium");

        //    String rowClass = (((row % 2) != 0) ? "tabularSectionField1" : "tabularSectionField2");
        GenericValue primaryEntityDetails = (GenericValue) entityDetailsVector.firstElement();
        displayHtml.append("     <TR CLASS=\"" + rowClass + "\" ID=\"tr_" +
            getSectionName() + "_");
        displayHtml.append(String.valueOf(row) + "\"");

        String hrefName = "a_" + getSectionName() + "_" + String.valueOf(row);

        if (!getDetailButtonAction().equals("") &&
                !getDetailButtonTarget().equals("")) {
            displayHtml.append(" onclick=\"selectRow" + getSectionName() + "(" +
                hrefName + ", window.event.srcElement)\"");
        }

        displayHtml.append(">\n");

        if (!getDetailButtonAction().equals("") &&
                !getDetailButtonTarget().equals("")) {
            // Insert the row select button.
            String href = " <A HREF=\"" + getDetailButtonAction() +
                "?action=show" +
                UIWebUtility.getUrlArgs(getButtonKeyMap(), entityDetailsVector) +
                "\" TARGET=\"" + getDetailButtonTarget() + "\" name=" +
                hrefName + "></A>\n";
            displayHtml.append(href);
        }

        for (int fieldNbr = 0; fieldNbr < getUiFieldList().size();
                fieldNbr++) {
            UIFieldInfo fieldInfo = getUiField(fieldNbr);
            String attributeName = fieldInfo.getUiAttribute().getAttributeName();

            if (fieldInfo.getIsVisible()) {
                Debug.logVerbose("[displayTabularSection()] Section name: " +
                        getSectionName() + " - Field Name = " + attributeName, module);

                displayHtml.append("      <TD NOWRAP ID=\"td_" +
                    String.valueOf(row) + "_" + String.valueOf(fieldNbr) +
                    "\">\n");
            }

            displayHtml.append(displayField(fieldInfo, entityDetailsVector,
                    action, row, false, 0));

            if (fieldInfo.getIsVisible()) {
                displayHtml.append("      </TD>\n");
            }

            displayHtml.append("\n");
        }

        // Make a blank column at the right side so the colors will look right.
        displayHtml.append("      <TD CLASS=\"tabularSectionBlankLabel\">\n");
        displayHtml.append("       &nbsp\n");
        displayHtml.append("      </TD>\n");
        displayHtml.append("     </TR>\n");

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionRow] End - row " +
                String.valueOf(row));
        }

        return displayHtml.toString();
View Full Code Here

Examples of org.ofbiz.base.util.UtilTimer

     *
     * @return
     */
    public String displayTabularSectionFooter(String action,
        String sendQueryParams, String queryId) {
        UtilTimer timer = new UtilTimer();

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionFooter] Start");
        }

        StringBuffer displayHtml = new StringBuffer(200);

        if ((getButtonAction() != null) && !getButtonAction().equals("") &&
                (getButtonTarget() != null) && !getButtonTarget().equals("") &&
                getIsUpdateable() &&
                (action.equals(ACTION_QUERY_UPDATE) || action.equals(ACTION_SHOW_INSERT) ||
                action.equals(ACTION_UPDATE))) {
            displayHtml.append("     <TR>\n");
            displayHtml.append("      <TD></TD>\n");
            displayHtml.append(
                "      <TD CLASS=\"tabularSectionSaveButtonArea\" COLSPAN=\"" +
                String.valueOf(getColumnCount()) + "\">\n");
            displayHtml.append(
                "       <INPUT TYPE=\"submit\" CLASS=\"button\" NAME=\"" +
                getSectionName() + "SaveButton\" VALUE=\"Save\">\n");
            displayHtml.append("      </TD>\n");
            displayHtml.append("     </TR>\n");
            displayHtml.append("\n");
        }

        if ((getButtonAction() != null) && !getButtonAction().equals("") &&
                (getButtonTarget() != null) && !getButtonTarget().equals("") &&
                getIsUpdateable()) {
            displayHtml.append("    </FORM>\n");
        }

        displayHtml.append("   </TBODY>\n");
        displayHtml.append("  </TABLE>\n");


        Debug.logVerbose("[displayTabularSection()] getSearchAction(): " +
            getSearchAction(), module);
        Debug.logVerbose("[displayTabularSection()] getSearchTarget(): " +
            getSearchTarget(), module);
        Debug.logVerbose("[displayTabularSection()] getSearchAttributeId(): " +
            getSearchAttributeId(), module);

        if (hasPriorPage || hasNextPage) {
         
          String scrollAction = action;
          if ( scrollAction.equals(ACTION_UPDATE) || ( scrollAction.equals(ACTION_INSERT)))
            scrollAction = ACTION_QUERY;
           
            displayHtml.append(
                "<FORM STYLE=\"padding=0; border=0; margin=0\" ACTION=\"" +
                getSearchAction() + "\"" + " TARGET=\"" + getSearchTarget() +
                "\" NAME=\"" + getSectionName() + "PageButtons\">\n");
            displayHtml.append(
                "       <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
                scrollAction + "\">\n");
            displayHtml.append(
                "       <INPUT TYPE=\"hidden\" NAME=\"startRow\" VALUE=\"" + 0 +
                "\">\n");
            displayHtml.append(sendQueryParams);
            if ( queryId != null && queryId.length() > 0)
              displayHtml.append("<INPUT TYPE=hidden name=queryId value=\"" + queryId + "\">\n");
            displayHtml.append("<CENTER><TABLE>\n<TR>\n");
            displayHtml.append("<TD ALIGN=CENTER>");

            if (hasPriorPage) {
                displayHtml.append(
                    "<input type=submit CLASS=\"titleBarImageButton\" title=\"Previous Page\" name=previous value=\"Previous\" onClick=\"startRow.value =" +
                    priorPageStartRow + "\">\n");
            }

            displayHtml.append("</TD><TD ALIGN=CENTER>");

            if (hasNextPage) {
                displayHtml.append(
                    "<TD><input type=submit CLASS=\"titleBarImageButton\" title=\"Next Page\" name=next value=\"Next\" onClick=\"startRow.value =" +
                    nextPageStartRow + "\">\n");
            }

            displayHtml.append("</TD></TR></TABLE></CENTER>\n");
            displayHtml.append("</FORM>\n");
        }

        if (!getSearchAction().equals("") && !getSearchTarget().equals("") &&
                !getSearchAttributeId().equals("")) {
            // Draw the alpha search under the list.
            Debug.logVerbose("[displayTabularSection()] Displaying alpha search buttons.", module);

            displayHtml.append("  <TABLE WIDTH=\"100%\">\n");

            String[] alphabet = {
                "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
                "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
                "*"
            };
            displayHtml.append("\n");
            displayHtml.append("    <TR>\n");
            displayHtml.append("     <TD WIDTH=\"30\"></TD>\n");
            displayHtml.append("     <TD ALIGN=\"left\">\n");
            displayHtml.append(
                "      <FORM STYLE=\"padding=0; border=0; margin=0\" ACTION=\"" +
                getSearchAction() + "\"" + " TARGET=\"" + getSearchTarget() +
                "\" NAME=\"" + getSectionName() + "AlphaQueryForm\">\n");
            displayHtml.append(
                "       <INPUT TYPE=\"hidden\" NAME=\"action\" VALUE=\"" +
                ACTION_QUERY + "\">\n");
            displayHtml.append(sendQueryParams);
            displayHtml.append(
                "       <TABLE BORDER=\"0\" BGCOLOR=\"white\" CELLSPACING=\"0\" CELLPADDING=\"0\" BORDER=\"0\">\n");
            displayHtml.append("        <TR>\n");

            for (int letterNbr = 0; letterNbr < alphabet.length; letterNbr++) {
                displayHtml.append("         <TD>\n");
                displayHtml.append(
                    "          <INPUT WIDTH=\"10\" TYPE=\"submit\" CLASS=\"button\" NAME=\"nameToSearch\" VALUE=\"" +
                    alphabet[letterNbr] + "\">\n");
                displayHtml.append("         </TD>\n");
            }

            displayHtml.append("        </TR>\n");
            displayHtml.append("       </TABLE>\n");
            displayHtml.append("      </FORM>\n");
            displayHtml.append("     </TD>\n");
            displayHtml.append("    </TR>\n");
            displayHtml.append("   </TABLE>\n");
            displayHtml.append("\n");
        }

        if (TIMER) {
            timer.timerString(2,
                "[UIWebScreenSection.displayTabularSectionFooter] End");
        }

        return displayHtml.toString();
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.