RAC Customization - Usefull Static Methods - Part I

RAC Customization - Static Methods


In every project, there will be a package called "common", which have classes consist of generic static methods. These methods reduces time, duplication of code, etc..

Below are the few static methods which are created for my project.. I guess, these methods will be very common in every project..

1. /** Method to check whether an item exists in the database with given ID */

    public static boolean isItemExists(TCSession tceSession, String itemId)
    throws TCException {

        String msg = "";
        TCComponentQuery tceItemQuery = null;
      
        TCComponentQueryType qType = (TCComponentQueryType) tceSession.getTypeComponent("ImanQuery");
        tceItemQuery = (TCComponentQuery) qType.find("Item...");      

        String entry[] = { "Item ID" };
        String value[] = { itemId };

        TCComponent[] result = tceItemQuery.execute(entry, value);

        if (result == null || result.length == 0) {
            return false;
        }

        if (result.length > 1) {
            msg = "More than one Item with id " + itemId
            + " exist in the database";
            throw new TCException(msg);
        }

        return true;
    }

------------------------------------------------------------------------------------------------------------------------

2.  /** Method takes string and delimiter as input and spilts the string and returns the array.  */

    public static String[] getStringSplitToArray(String stringValue,String delim)
    {     
        StringTokenizer strToken = new StringTokenizer(stringValue,delim);
        int iLoop = 0;
        int iTokenCnt = strToken.countTokens();

        String[] strArray = new String[iTokenCnt];
        for(iLoop = 0;iLoop < iTokenCnt;iLoop++)
        {
            strArray[iLoop] = strToken.nextToken();
        }

        return strArray;
    }
------------------------------------------------------------------------------------------------------------------------

3. /** Is String number */

    public static boolean isNumber(String str) {
        return (str == null || str.isEmpty()) ? false : str.trim().matches("\\d*");
    }

------------------------------------------------------------------------------------------------------------------------

4.  /** Is Double */

    public static boolean isDouble(String str) {
        try {
            Double.parseDouble(str);
            return true;
        } catch (NumberFormatException ex) {
        }
        return false;
    }
------------------------------------------------------------------------------------------------------------------------

5.  /** Return the lov values */

    public static String[] getLOVValues(TCSession session, String lovName) {
        TCComponent[] foundComponents = null;
        TCClassService classService = session.getClassService();
        try {
            foundComponents = classService.findByClass("ListOfValues", "lov_name", lovName);
       
         if (foundComponents == null || foundComponents.length == 0)
                return null;

            ListOfValuesInfo lovInfo = ((TCComponentListOfValues) foundComponents[0]).getListOfValues();

            if (lovInfo != null) {
                return lovInfo.getStringListOfValues();
            }

        } catch (TCException e) {
            e.printStackTrace();
        }
        return null;
    }
 ------------------------------------------------------------------------------------------------------------------------

6. /** Get variant list of bomline */

    public static String[] getVariants(TCComponentBOMLine bLine) {
        if (bLine == null)
            return null;

        TCComponentItemRevision rev;
        VariantCondition varCond;
        try {
            rev = bLine.getItemRevision();
            TCComponent bomLineCond = bLine.getReferenceProperty("bl_condition_tag");
            ItemRevVariantData irvd = ItemRevVariantData.create(rev, bLine.window());

            if (bomLineCond == null) {
                varCond = VariantCondition.create(bLine.window());
                if (irvd != null) {
                    varCond.setVariantDataContext(irvd);
                }
            } else {
                varCond = VariantCondition.create(bomLineCond, bLine.window(), irvd);
            }

            return varCond.asText();
        } catch (TCException e) {
            e.printStackTrace();
        }
        return null;
    }

 ------------------------------------------------------------------------------------------------------------------------

7. /** Has status on component?  */

    public static boolean hasStatus(TCComponent component, String status) {
        try {
            TCComponent[] revStatus = component.getTCProperty("release_status_list").getReferenceValueArray();

            for (int i = 0; revStatus != null && i < revStatus.length; i++) {
                String statusName = revStatus[i].getTCProperty("name").getPropertyValue().toString();
                if (statusName.equalsIgnoreCase(status)) {
                    return true;
                }
            }
        } catch (TCException e) {
        }
        return false;
    }
 ------------------------------------------------------------------------------------------------------------------------

8. /** Is validation user Id */

    public static boolean isUserId(TCSession session, String userId) {
        TCComponent[] users = findByClass(session, "User", "user_id", userId);
        return !(users == null || users.length == 0);
    }
------------------------------------------------------------------------------------------------------------------------

9. /** Find components by class */

    public static TCComponent[] findByClass(TCSession session, String className, String propertyName, String propertyValue) {
        TCComponent[] comps = null;
        TCClassService clsService = session.getClassService();
        try {
            comps = clsService.findByClass(className, propertyName, propertyValue);
        } catch (TCException e) {
            e.printStackTrace();
        }
        return comps;
    }
 ------------------------------------------------------------------------------------------------------------------------

10. /** Find by query*/

    public static TCComponent[] findByQuery(TCSession session, String qryName, String[] propNames, String[] propValues) {
        TCComponent[] allCmps = null;
        TCComponentQueryType qryTypeCmp = null;
        try {
            qryTypeCmp = (TCComponentQueryType) session.getTypeComponent("ImanQuery");
            TCComponentQuery aQuery = (TCComponentQuery) qryTypeCmp.find(qryName);
            allCmps = aQuery.execute(propNames, propValues);
        } catch (TCException ex) {
            ex.printStackTrace();
        }
        return allCmps;
    }
 ------------------------------------------------------------------------------------------------------------------------

11. /** Return IMAN relation map<relation_name, relation_display_name>  */

    public static Map<String, String> getRelationList(TCSession session) {
        Map<String, String> relations = new HashMap<String, String>(0);
        Map<String, List<String>> inputList = new HashMap<String, List<String>>(0);
        List<String> exclusionList = new ArrayList<String>(0);
        inputList.put("ImanRelation", exclusionList);
        Map<String, List<DisplayTypeInfo>> dispTypes = TCUtilities.getDisplayableTypeNamesWithHierarchyInfo(session, inputList);
        if (dispTypes != null && !dispTypes.isEmpty()) {
            for (Map.Entry<String, List<DisplayTypeInfo>> entry : dispTypes.entrySet()) {
                List<DisplayTypeInfo> typeInfos = entry.getValue();
                if (typeInfos != null && !typeInfos.isEmpty()) {
                    for (DisplayTypeInfo typeInfo : typeInfos) {
                        relations.put(typeInfo.getTypeName(), typeInfo.getDisplayTypeName());
                    }
                }
            }
        }
        return relations;
    }
 ------------------------------------------------------------------------------------------------------------------------

12. /** Concatenates the array of values using the connector */
     public static String concatenateValue(String[] values, String connector) {
        if (values == null || values.length == 0)
            return "";

        int i = 0;
        StringBuilder sb = new StringBuilder();
        for (i = 0; i < values.length; i++) {
            if (i != 0) {
                sb.append(connector);
            }
            sb.append(values[i]);
        }
        return sb.toString();
    }
------------------------------------------------------------------------------------------------------------------------

13. /** Decimal format for double data  */

    public static String decimalFormat(double df, int digitCount) {
        return String.format(String.format("%%.%df", digitCount), df);
    }
------------------------------------------------------------------------------------------------------------------------

  14.  /** Decimal format for double string */

    public static String decimalFormat(String df, int digitCount) {
        String dbs = (df == null || df.isEmpty()) ? "0" : df;
        return String.format(String.format("%%.%df", digitCount), Double.parseDouble(dbs));
    }
------------------------------------------------------------------------------------------------------------------------

15. /** Make the number no any '0' postfix. */

    public static String trimNumber(String numberString) {
        String rst = "";
        if (numberString == null || numberString.length() == 0)
            return rst;

        numberString = rst = numberString.trim();
        if (numberString.indexOf(".") != -1) {
            for (int i = numberString.length() - 1; i > 0; i--) {
                char c = numberString.charAt(i);
                if (c == '.') {
                    rst = numberString.substring(0, i);
                    break;
                }
                if (c == '0') {
                    continue;
                }
                rst = numberString.substring(0, i + 1);
                break;
            }
        }
        if (rst.equals("-0"))
            return "0";

        return rst;
    }
------------------------------------------------------------------------------------------------------------------------

16. /** Get 'YYWW' date */

    public static String getYearWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        SimpleDateFormat dFormatter = new SimpleDateFormat("yy");
        return String.format("%s%02d", dFormatter.format(c.getTime()), c.get(Calendar.WEEK_OF_YEAR));
    }
------------------------------------------------------------------------------------------------------------------------

17. /** Get 'YYYYWW' date */

    public static String getLongYearWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        SimpleDateFormat dFormatter = new SimpleDateFormat("yyyy");
        return String.format("%s%02d", dFormatter.format(c.getTime()), c.get(Calendar.WEEK_OF_YEAR));
    }
------------------------------------------------------------------------------------------------------------------------

18.    /**
     * Paste value form clipboard component to selected component. NOTE: if
     * clipboard component is TCComponentBOMLine, only paste one component of
     * selected components
     *
     * @param clipboardComponents
     * @param selectedComponents
     * @param propertyKey
     * @throws TCException
     */
    public static void paste(TCComponent clipboardComponents, TCComponent[] selectedComponents, final String propertyKey) throws TCException {
        if (clipboardComponents == null) {
            return;
        }

        if (propertyKey.equals("bl_variant_condition") || propertyKey.equals("bl_condition_tag") || propertyKey.equals("bl_formula")) {
            if (!(clipboardComponents instanceof TCComponentBOMLine))
                return;
            try {
                TCComponentBOMLine line = (TCComponentBOMLine) clipboardComponents;
                TCComponent condition = line.getReferenceProperty("bl_condition_tag");
                if (condition == null) {
                    String varCondMvl = line.getProperty("bl_variant_condition");
                    TCComponentBOMLine toLine = (TCComponentBOMLine) selectedComponents[0];
                    toLine.getSession().getVariantService().setLineMvlCondition(toLine, varCondMvl);
                } else {
                    VariantCondition clauses = VariantCondition.create(condition, line.window());
                    selectedComponents[0].setReferenceProperty("bl_condition_tag", clauses.toCondition());
                }
            } catch (TCException e) {
                throw new TCException(e);
            }
            return;
        }

        for (TCComponent selectedComponent : selectedComponents) {
            try {
                selectedComponent.setProperty(propertyKey, clipboardComponents.getProperty(propertyKey));
            } catch (TCException e) {
                throw new TCException(e);
            }
        }
    }
------------------------------------------------------------------------------------------------------------------------

19. /** Get relation name
     * @param primary
     * @param second
     * @return
     *
     *         NOTE: If you want to see the relation in IC mode, it will not be
     *         available. The relation name in IC mode should read from
     *         TCComponentCfgAttachmentLine's 'al_context'.
     */
    public static String getRelationName(TCComponent primary, TCComponent second) {
        String relationName = "";

        boolean isFolder = false;
        AIFComponentContext[] contx;
        if (primary instanceof TCComponentFolder) {
            isFolder = true;
        }

        try {
            contx = isFolder ? primary.getChildren() : second.whereReferenced(); // not second.getPrimary
            if (contx != null && contx.length != 0) {
                for (AIFComponentContext ctx : contx) {
                    TCComponent primaryParent = (TCComponent) ctx.getComponent();
                    if (primaryParent.getUid().equals(primary.getUid())) {
                        relationName = isFolder ? "contents" : (String) ctx.getContext();
                        break;
                    }
                }
            }
        } catch (TCException e) {
            e.printStackTrace();
        }

        return relationName;
    }
------------------------------------------------------------------------------------------------------------------------

20. /** Is zero for double */

    public static boolean isZero(double dValue) {
        double epsilon = 0.0000001;
        return (dValue > -epsilon && dValue < epsilon );
    }
------------------------------------------------------------------------------------------------------------------------




Comments

  1. Solai,

    Please add some more examples related to RAC Customization & BMIDE.

    The examples that you write in your blog are very beneficial for all.

    Regards,
    Neha Agrawal

    ReplyDelete
  2. Neha,
    Thanks for your comment.. Will update them shortly..

    ReplyDelete
  3. Will you tell me code which will customize the structure manager based on external exe file. sumantmahangade@yahoo.com mail me

    ReplyDelete
  4. When i click the MSExcel file in tc,my code should be called automatically without any command buttons.what should i do? could you help me sir??

    ReplyDelete
  5. please add some more examples regarding rac and bmide..

    ReplyDelete
  6. please upload basics of rac and things to know before starting it.It would be really helpful.

    Above codes are very useful.Thank and waiting for more

    ReplyDelete
  7. This is really helping out. Does somebody know by chance how to retrieve properties on relation ?

    ReplyDelete

Post a Comment

Popular posts from this blog

RAC Customization - Useful Static Methods - Part II

ITK Debug Configuration - Visual Studio