Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

In this page you can find the example usage for java.lang StringBuffer substring.

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:com.krawler.crm.hrmsintegration.bizservice.GoalManagementServiceImpl.java

public JSONObject completedGoalReport(String userid, String companyid, DateFormat dateFormat, int relatedTo,
        int leadPerm, int accountPerm, int oppPerm, Long fromDate, Long toDate, String searchStr,
        String startStr, String limitStr, boolean exportall, Locale locale, String timeZoneDiff)
        throws ServiceException {
    JSONObject jobj = new JSONObject();
    KwlReturnObject kmsg = null;//from ww  w  .jav a2  s . c  om
    JSONArray jarr = new JSONArray();
    int count = 0;
    int start = 0;
    int limit = 25;
    int offSet = TimeZone.getTimeZone("GMT" + timeZoneDiff).getOffset(System.currentTimeMillis());
    try {
        HashMap<String, Object> requestParams = new HashMap<String, Object>();

        ArrayList filter_names = new ArrayList();
        ArrayList filter_params = new ArrayList();

        filter_names.add("c.userID.userID");
        filter_names.add("c.userID.company.companyID");
        filter_names.add("c.deleted");
        filter_params.add(userid);
        filter_params.add(companyid);
        filter_params.add(false);
        if (relatedTo > 0) {
            filter_names.add("c.relatedto");
            filter_params.add(relatedTo);
        } else if (relatedTo == 0) { // Kuldeep Singh : When user select view 'All' goals then fetch goal data according to module's permission
            StringBuffer relatedlist = new StringBuffer();
            if ((leadPerm & 1) == 1) {
                relatedlist.append("" + 1 + ",");
                relatedlist.append("" + 2 + ",");
            }
            if ((accountPerm & 1) == 1) {
                relatedlist.append("" + 3 + ",");
                relatedlist.append("" + 4 + ",");
            }
            if ((oppPerm & 1) == 1) {
                relatedlist.append("" + 5 + ",");
                relatedlist.append("" + 6 + ",");
            }
            String rltedlist = "0";
            if (relatedlist.length() > 0) {
                rltedlist = relatedlist.substring(0, (relatedlist.length() - 1));
            }
            filter_names.add("INc.relatedto");
            filter_params.add(rltedlist);
        }
        if (toDate != null && fromDate != null) {
            Date fmDate = new Date(fromDate);
            Date tDate = new Date(toDate);
            filter_names.add(">=c.startdate");
            filter_names.add("<=c.startdate");
            filter_params.add(dateOnlyFormat.parse(dateOnlyFormat.format(fmDate)).getTime());
            filter_params.add(dateOnlyFormat.parse(dateOnlyFormat.format(tDate)).getTime());
        }

        filter_names.add("<=c.enddate");
        Date now = new Date();
        now = dateOnlyFormat.parse(dateOnlyFormat.format(now));
        filter_params.add(now.getTime());

        requestParams.clear();
        if (startStr != null) {
            start = Integer.parseInt(startStr);
            limit = Integer.parseInt(limitStr);
        }
        if (!StringUtil.isNullOrEmpty(searchStr)) {
            requestParams.put("ss", searchStr);
        }
        if (!exportall) {
            requestParams.put("start", start);
            requestParams.put("limit", limit);
        }
        kmsg = hrmsIntDAOObj.getFinalGoals(requestParams, filter_names, filter_params);
        count = kmsg.getRecordTotalCount();
        if (count > 0) {
            User empuser = profileHandlerDAOObj.getUserObject(userid);
            List<Finalgoalmanagement> finalGoalmanagementList = kmsg.getEntityList();
            for (Finalgoalmanagement fgmt : finalGoalmanagementList) {
                JSONObject tmpObj = new JSONObject();
                double dl = 0;
                String relatedName = "";
                double percentageTarget = 0;
                filter_names.clear();
                filter_params.clear();
                requestParams.clear();
                requestParams.put("distinctFlag", true);

                dl = getAchievedTarget(fgmt, companyid, empuser);
                percentageTarget = getPercentageTarget(fgmt, dl);
                int reltTo = fgmt.getRelatedto() == null ? 0 : fgmt.getRelatedto();
                relatedName = getGoalName(reltTo);
                String gid = fgmt.getId();
                int pastGoals = getPastGoal(fgmt, percentageTarget);
                DecimalFormat decimalFormat = new DecimalFormat("#0");
                String percentAchvd = decimalFormat.format(percentageTarget) + " %";

                tmpObj.put("gid", gid);
                tmpObj.put("gname", fgmt.getGoalname());
                tmpObj.put("empname", empuser.getFirstName() + " " + empuser.getLastName());
                tmpObj.put("empid", empuser.getUserID());
                tmpObj.put("gdescription", fgmt.getGoaldesc());
                tmpObj.put("targeted", fgmt.getTargeted());
                tmpObj.put("relatedto", reltTo);
                tmpObj.put("relatedName", relatedName);
                tmpObj.put("achieved", dl != 0.0 ? dl : "0");
                tmpObj.put("percentageachieved", percentageTarget != 0.0 ? percentAchvd : "0");
                tmpObj.put("pastgoals", pastGoals);
                tmpObj.put("gstartdate", dateFormat.format(fgmt.getStartdate() + offSet));
                tmpObj.put("genddate", dateFormat.format(fgmt.getEnddate() + offSet));
                tmpObj.put("gassignedby", fgmt.getManager().getFirstName() + " "
                        + (fgmt.getManager().getLastName() == null ? "" : fgmt.getManager().getLastName()));
                jarr.put(tmpObj);
            }
        }
        jobj.put("coldata", jarr);
        jobj.put("data", jarr);
        jobj.put("totalCount", count);

        JSONObject jobjTemp = new JSONObject();
        JSONArray jarrColumns = new JSONArray();
        JSONArray jarrRecords = new JSONArray();
        JSONObject jMeta = new JSONObject();

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goalsettings.header.empname", null, locale));//"Employee Name");
        jobjTemp.put("tip", messageSource.getMessage("crm.goalsettings.header.empname", null, locale));//"Employee Name");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("dataIndex", "empname");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.goaltype", null, locale));//"Goal Type");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.goaltype", null, locale));//"Goal Type");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("dataIndex", "relatedName");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.target", null, locale));//"Target");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.target", null, locale));//"Target");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("align", "right");
        jobjTemp.put("dataIndex", "targeted");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.achieved", null, locale));//"Achieved");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.achieved", null, locale));//"Achieved");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("align", "right");
        jobjTemp.put("dataIndex", "achieved");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.percentageachieved", null, locale));//"Percentage Achieved");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.percentageachieved", null, locale));//"Percentage Achieved");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("align", "right");
        jobjTemp.put("dataIndex", "percentageachieved");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.fromdate", null, locale));//"From Date");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.fromdate", null, locale));//"From Date");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("title", "gstartdate");
        jobjTemp.put("dataIndex", "gstartdate");
        jobjTemp.put("align", "center");
        jobjTemp.put("renderer", crmManagerCommon.dateRendererReport());
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.todate", null, locale));//"To Date");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.todate", null, locale));//"To Date");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("title", "gstartdate");
        jobjTemp.put("dataIndex", "genddate");
        jobjTemp.put("align", "center");
        jobjTemp.put("renderer", crmManagerCommon.dateRendererReport());
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("header", messageSource.getMessage("crm.goals.header.assignedby", null, locale));//"Assigned By");
        jobjTemp.put("tip", messageSource.getMessage("crm.goals.header.assignedby", null, locale));//"Assigned By");
        jobjTemp.put("pdfwidth", 60);
        jobjTemp.put("dataIndex", "gassignedby");
        jarrColumns.put(jobjTemp);

        jobjTemp = new JSONObject();
        jobjTemp.put("name", "empname");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "relatedName");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "targeted");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "achieved");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "percentageachieved");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "gassignedby");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "gstartdate");
        jobjTemp.put("type", "date");
        jarrRecords.put(jobjTemp);
        jobjTemp = new JSONObject();
        jobjTemp.put("name", "genddate");
        jobjTemp.put("type", "date");
        jarrRecords.put(jobjTemp);
        jobj.put("columns", jarrColumns);

        jMeta.put("totalProperty", "totalCount");
        jMeta.put("root", "coldata");
        jMeta.put("fields", jarrRecords);
        jMeta.put("id", "asd");
        jobj.put("metaData", jMeta);

    } catch (JSONException e) {
        logger.warn("JSONException exception in completedGoalReport()", e);
        throw ServiceException.FAILURE("GoalManagementServiceImpl.assignedgoalsdelete", e);
    } catch (ServiceException e) {
        logger.warn("ServiceException exception in completedGoalReport()", e);
        throw ServiceException.FAILURE("GoalManagementServiceImpl.assignedgoalsdelete", e);
    } catch (Exception e) {
        logger.warn("General exception in completedGoalReport()", e);
        throw ServiceException.FAILURE("GoalManagementServiceImpl.assignedgoalsdelete", e);
    }
    return jobj;
}

From source file:com.baidu.gcrm.customer.service.impl.CustomerServiceImpl.java

private String agentCountrySort(String soucre) {
    if (StringUtils.isBlank(soucre)) {
        return soucre;
    }/*from  ww  w  .  j  a v a2  s .  co m*/
    String[] countryIds = soucre.split(",");
    Set<Long> countryIdSet = new TreeSet<Long>();
    for (String countryId : countryIds) {
        countryIdSet.add(Long.valueOf(countryId));
    }
    StringBuffer sb = new StringBuffer();
    for (Long countryId : countryIdSet) {
        sb.append(countryId);
        sb.append(",");
    }
    int size = sb.length();
    if (size > 0) {
        return sb.substring(0, size - 1);
    }
    return "";
}

From source file:org.agnitas.beans.impl.MailingImpl.java

/**
 * Scans a textblock for trackable links and replaces them with encoded
 * rdir-links./* ww  w  .  ja  va  2 s. com*/
 */
public String insertTrackableLinks(String aText1, int customerID, ApplicationContext con) {
    if (this.trackableLinks == null) {
        return aText1;
    }

    /*
     * trackableLinks is an unordered HashMap. When there are 2 links in the
     * Map, where one is part of the other, this could lead to an link
     * replacement, depending on the map ordering.
     * 
     * Link 1: http://www.mydomain.de Link 2:
     * http://www.mydomain.de/path/index.htm
     * 
     * If Link 1 is returned before Link 2 from the iterator this resulted
     * in: http://rdir.de/r.html?uid=<uid of Link1>/path/index.htm
     */
    Comparator<String> reverseString = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    };

    Set<String> sorted = new TreeSet<String>(reverseString);
    sorted.addAll(this.trackableLinks.keySet());

    Iterator<String> i = sorted.iterator();
    String aLink = null;
    int start_link = 0;
    int end_link = 0;
    TrackableLink aLinkObj = null;
    StringBuffer aBuf = new StringBuffer(aText1);
    boolean isHref = false;

    if (aText1 == null) {
        return null;
    }

    while (i.hasNext()) {
        aLink = i.next();
        end_link = 0;
        while ((start_link = aBuf.indexOf(aLink, end_link)) != -1) {
            end_link = start_link + 1;
            isHref = false;
            if (start_link > 5 && (aBuf.substring(start_link - 6, start_link).equalsIgnoreCase("href=\""))) {
                isHref = true;
            }
            if (start_link > 6 && (aBuf.substring(start_link - 7, start_link).equalsIgnoreCase("href=\""))) {
                isHref = true;
            }
            if (aBuf.length() > (start_link + aLink.length())) {
                if (!(aBuf.charAt(start_link + aLink.length()) == ' '
                        || aBuf.charAt(start_link + aLink.length()) == '\''
                        || aBuf.charAt(start_link + aLink.length()) == '"')) {
                    isHref = false;
                }
            }
            if (isHref) {
                aLinkObj = (TrackableLink) this.trackableLinks.get(aLink);
                aBuf.replace(start_link, start_link + aLink.length(),
                        aLinkObj.encodeTagStringLinkTracking(con, customerID));
            }
        }
    }
    return aBuf.toString();
}

From source file:org.wso2.carbon.is.migration.MigrationDatabaseCreator.java

/**
 * executes content in SQL script//from w w  w.j a v a 2s . c  o  m
 *
 * @return StringBuffer
 * @throws Exception
 */
private void executeSQLScript(String dbscriptName) throws Exception {

    String databaseType = DatabaseCreator.getDatabaseType(this.conn);
    boolean oracleUserChanged = true;
    boolean keepFormat = false;
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
        oracleUserChanged = false;
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;
    }

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbscriptName);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            //add the oracle database owner
            if (!oracleUserChanged && "oracle".equals(databaseType) && line.contains("databasename :=")) {
                line = "databasename := '" + ISMigrationServiceDataHolder.getIdentityOracleUser() + "';";
                oracleUserChanged = true;
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (Exception e) {
        log.error("Error occurred while executing SQL script for migrating database", e);
        throw new Exception("Error occurred while executing SQL script for migrating database", e);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.MetaThesaurusToSQL.java

/**
 * Adds qualification to concepts and associations in the LexGrid
 * repository./*  w w  w .  ja v a2 s. c  o  m*/
 * 
 * @param aq
 *            Qualification information from the UMLS source.
 * @param constructHCD
 *            Indicates whether artificial context values should be
 *            constructed if not provided in the UMLS information.
 * @param rela
 *            The relationship attribute defined by UMLS (can be empty or
 *            null).
 * @param totalCount
 *            The total number of context links qualified previously.
 * @return The number of contextual links qualified in the repository for
 *         the given UMLS info.
 * @throws SQLException
 */
protected int loadContext(AssociationQualification aq, boolean constructHCD, String rela, int totalCount)
        throws SQLException {
    // If a context identifier was assigned, use it.
    // If a context identifier is not assigned and the option to construct
    // is enabled,
    // derive one based on the root concept code and path to root AUI
    // values.
    int contextLinks = 0;
    String hcd = aq.qualifierValue;
    if (constructHCD && StringUtils.isBlank(hcd) && StringUtils.isNotBlank(aq.pathToRoot)
            && StringUtils.isNotBlank(aq.sourceConceptCode)) {
        MessageDigest md = getSHA1();
        md.reset();
        md.update(aq.pathToRoot.getBytes());
        hcd = String.valueOf(md.digest(aq.sourceConceptCode.getBytes()));
    }
    if (StringUtils.isBlank(hcd))
        return 0;

    // Iterate through the path to root and determine the codes for
    // participating AUIs. We maintain a LRU cache of AUIs to codes to
    // assist.
    // If the associated code is not in the cache, find and cache it here.
    ListOrderedMap orderedPtrAUIToCode = new ListOrderedMap();

    // Break up the path to root into AUIs ...
    String[] auis = aq.pathToRoot.split("\\.");
    if (auis.length > 0) {
        // Check the cache for each. If not found, perform and cache the
        // AUI to code mapping.
        PreparedStatement getPTRCode = umlsConnection2_
                .prepareStatement("SELECT CUI FROM MRCONSO WHERE AUI = ?");
        try {
            String nextCode, nextAUI;
            for (int i = 0; i < auis.length; i++) {
                // Check for registered code in the cache.
                nextAUI = auis[i];
                nextCode = (String) auiToCodeCache_.get(nextAUI);

                // If not cached, perform lookup ...
                if (nextCode == null) {
                    getPTRCode.setString(1, nextAUI);
                    ResultSet ptrCodes = getPTRCode.executeQuery();
                    int count = 0;
                    try {
                        while (ptrCodes.next()) {
                            count++;
                            nextCode = ptrCodes.getString(1);
                        }
                    } finally {
                        ptrCodes.close();
                    }
                    // If one to one mapping (probably should always be, but
                    // doesn't
                    // hurt to check), add to the cache for quick lookup
                    // later...
                    if (count == 1)
                        auiToCodeCache_.put(nextAUI, nextCode);
                }

                // Was it resolved?
                if (nextCode != null)
                    orderedPtrAUIToCode.put(nextAUI, nextCode);
            }
        } finally {
            getPTRCode.close();
        }
    }
    // Ensure we have included the original AUI to code mapping from the
    // provided UMLS qualification info; inserted last as the root
    // of the path.
    orderedPtrAUIToCode.put(aq.sourceConceptAUI, aq.sourceConceptCode);

    // /////////////////////////////////////////////////////////////////////
    // We have all the participating codes and AUIs.
    // Add context qualifiers to the text presentation of each concept
    // based on code/AUI pairs.
    // /////////////////////////////////////////////////////////////////////
    for (OrderedMapIterator omi = orderedPtrAUIToCode.orderedMapIterator(); omi.hasNext();) {
        omi.next();
        String aui = (String) omi.getKey();
        String code = (String) omi.getValue();
        if (code != null)
            qualifyConceptPresentation(code, aui, aq.codingSchemeName, aq.qualifierName, hcd);
    }

    // /////////////////////////////////////////////////////////////////////
    // At this point we have taken care of all the concept qualifiers.
    // Now find and similarly tag each participating association link
    // between AUIs in the path to root chain.
    // /////////////////////////////////////////////////////////////////////

    // Statements to find LexGrid association to concept mappings.
    // Check source to target (parent association as processed)
    // or target to source (child association as processed).

    // Honor the association specified in the MRHIER entry, if provided.
    // For example, the UMLS 'inverse_isa' is mapped on load to 'hasSubtype'
    // association name; account for that here.
    String assoc = mapRela(rela);

    // If a specific relation attribute (rela) was not provided, consider
    // all relevant
    // hierarchical associations (including UMLS standard or source-specific
    // names).
    String assocParam = StringUtils.isNotBlank(assoc) ? '\'' + assoc + '\''
            : toCommaDelimitedWithQuotes(getHierAssocNames(aq.codingSchemeName));

    // Create statements to navigate both directions (up & down the
    // contextual chain).
    PreparedStatement getRelationship_1 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.sourceEntityCodeOrId + " = ? AND "
                                    + stc_.targetEntityCodeOrId + " = ? AND ")
                            .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId
                                    + " IN (")
                            .append(assocParam).append(")").toString());

    PreparedStatement getRelationship_2 = sqlConnection_.prepareStatement(new StringBuffer(
            "SELECT " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + ", " + stc_.targetEntityCodeOrId + ", "
                    + stc_.entityCodeOrAssociationId + ", " + stc_.sourceEntityCodeOrId + " FROM ")
                            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                            .append(" WHERE " + stc_.targetEntityCodeOrId + " = ? AND "
                                    + stc_.sourceEntityCodeOrId + " = ? AND ")
                            .append(stc_.codingSchemeNameOrId + " = ? AND " + stc_.entityCodeOrAssociationId
                                    + " IN (")
                            .append(assocParam).append(")").toString());

    // Statement to update a multi-attributes key for an association
    // mapping.
    PreparedStatement updateMAK = sqlConnection_.prepareStatement(new StringBuffer("UPDATE ")
            .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
            .append(" SET " + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ? " + " WHERE "
                    + stc_.codingSchemeNameOrId + " = ?")
            .append(" AND " + stc_.sourceEntityCodeOrId + " = ? AND " + stc_.targetEntityCodeOrId + " = ?")
            .append(" AND " + stc_.entityCodeOrAssociationId + " = ?").toString());

    // Locate and qualify each affected association link with the context ID
    // ...
    try {
        PreparedStatement[] stmts = new PreparedStatement[] { getRelationship_1, getRelationship_2 };
        for (int s = 0; s < stmts.length; s++) {
            PreparedStatement stmt = stmts[s];
            for (int i = orderedPtrAUIToCode.size() - 1; i > 0; i--) {
                String code = (String) orderedPtrAUIToCode.getValue(i);
                String codePrev = (String) orderedPtrAUIToCode.getValue(i - 1);
                stmt.setString(1, code);
                stmt.setString(2, codePrev);
                stmt.setString(3, aq.codingSchemeName);

                ResultSet results = stmt.executeQuery();
                try {
                    // Iterate through all relevant association links ...
                    while (results.next()) {
                        String multiAttributesKey = results
                                .getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY);
                        String targetConceptCode = results.getString(stc_.targetEntityCodeOrId);
                        String sourceConceptCode = results.getString(stc_.sourceEntityCodeOrId);
                        String association = results.getString(stc_.entityCodeOrAssociationId);

                        // If there is no key to correlate to the
                        // multi-attributes table,
                        // construct and add now.
                        if (multiAttributesKey == null) {
                            StringBuffer key = new StringBuffer().append(System.currentTimeMillis())
                                    .append((int) Math.floor((Math.random() * 100000))).append(totalCount);
                            multiAttributesKey = key.substring(0, Math.min(50, key.length()));
                            updateMAK.setString(1, multiAttributesKey);
                            updateMAK.setString(2, aq.codingSchemeName);
                            updateMAK.setString(3, sourceConceptCode);
                            updateMAK.setString(4, targetConceptCode);
                            updateMAK.setString(5, association);
                            updateMAK.execute();
                        }

                        // Add a context qualifier to the multi-attributes
                        // table.
                        try {
                            addEntityAssociationQualifierToEntityAssociation(aq.codingSchemeName,
                                    multiAttributesKey, aq.qualifierName, hcd);
                            contextLinks++;
                        } catch (SQLException e) {
                            // Because we qualify all relationships along
                            // the PTR and
                            // the HCD is identical for siblings at the same
                            // PTR some
                            // exceptions with regards to identical keys
                            // will come up.

                            // We try to bypass altogether if the message
                            // indicates duplication.
                            // However, message text can vary based on the
                            // database engine.
                            // Rather than exit in error, log the message
                            // and continue.
                            if (!e.getMessage().contains("Duplicate")) {
                                messages_.warn("Unable to add context qualifier to association.", e);
                            }
                        }
                    }
                } finally {
                    results.close();
                }
            }
        }
    } finally {
        updateMAK.close();
        getRelationship_1.close();
        getRelationship_2.close();
    }
    return contextLinks;
}

From source file:org.talend.oozie.scheduler.controller.ExecuteJobCompositeController.java

/**
 * //from   w  ww  . j  av  a2  s . com
 * @return
 */
private JobContext initJobContextForOozie(JobSubmissionType jobSubType, IContext context) {
    JobContext jobContext = new JobContext();

    IProcess2 process = OozieJobTrackerListener.getProcess();
    // if use kerberos
    if (TOozieParamUtils.enableKerberos()
            && ComponentCategory.CATEGORY_4_DI.getName().equals(process.getComponentsType())) {
        jobContext.set("KERBEROS.PRINCIPAL", TOozieParamUtils.getPrincipal()); //$NON-NLS-1$
    }
    // for hadoop properties
    if (process != null && settingDialog != null) {
        if (ComponentCategory.CATEGORY_4_DI.getName().equals(process.getComponentsType())) {
            JSONArray props = new JSONArray();
            for (Map<String, Object> property : settingDialog.getPropertiesValue()) {
                props.put(property);
            }
            jobContext.set("HADOOP.PROPERTIES", props.toString()); //$NON-NLS-1$
        }

        StringBuffer libJars = new StringBuffer();
        Set<String> libNames = JavaProcessorUtilities.extractLibNamesOnlyForMapperAndReducer(process);
        if (libNames != null && libNames.size() > 0) {
            Iterator<String> itLibNames = libNames.iterator();
            while (itLibNames.hasNext()) {
                libJars.append(itLibNames.next()).append(",");//$NON-NLS-1$
            }
        }
        jobContext.set("LIBJARS", libJars.substring(0, libJars.length() - 1)); //$NON-NLS-1$
    }
    // Job name.
    String jobName = process.getLabel();
    jobContext.setJobName(jobName);

    // Job path on HDFS
    String path = executeJobComposite.getPathValue();
    // IProcess2 process = OozieJobTrackerListener.getProcess();
    // String name = JavaResourcesHelper.getJobFolderName(process.getLabel(), process.getVersion()) + "." +
    // process.getLabel();
    // jobContext.setJobPathOnHDFS(path + "/" + name);
    jobContext.setJobPathOnHDFS(path);

    // Oozie end point
    String oozieEPValue = getOozieEndPoint();
    jobContext.setOozieEndPoint(oozieEPValue);

    // Name node end point
    String nameNodeEPValue = getNameNode();
    jobContext.setNameNodeEndPoint(nameNodeEPValue);

    // Job tracker end point
    String jobTrackerEPValue = getJobTracker();
    jobContext.setJobTrackerEndPoint(jobTrackerEPValue);

    // APP path
    // IPath appPath = new Path(nameNodeEPValue).append(path);
    // mhirt : bug fix on linux Path changes // to /. FIXME : Do a better coding for 5.1.1
    String appPath = path;
    String hadoopDistribution = getHadoopDistribution();
    EHadoopDistributions distribution = EHadoopDistributions.getDistributionByName(hadoopDistribution, false);
    if (distribution == EHadoopDistributions.MAPR) {
        appPath = "maprfs:".concat(appPath);//$NON-NLS-1$
    } else if (nameNodeEPValue != null) {
        appPath = nameNodeEPValue.concat(appPath);
    }
    jobContext.set(OozieClient.APP_PATH, appPath);

    // User Name for acessing hadoop
    String userNameValue = getUserNameForHadoop();
    jobContext.set(OozieClient.USER_NAME, userNameValue);

    // TOS job
    String tosJobFQCN = getTOSJobFQCNValue();
    jobContext.setJobFQClassName(tosJobFQCN);
    jobContext.setTosContextPath(context.getName());

    switch (jobSubType) {
    case LOCAL:
        break;
    case REMOTE:
        break;
    case SCHEDULED:
        // Frequency
        int fequency = getFrequencyValue();
        jobContext.setFrequency(fequency);
        // Time unit
        Timeunit timeUnit = getTimeUnitValue();
        jobContext.setTimeUnit(timeUnit);
        // Start Time
        Date startTime = getStartTimeValue();
        jobContext.setStartTime(startTime);
        // End Time
        Date endTime = getEndTimeValue();
        jobContext.setEndTime(endTime);
        break;
    default:
    }

    return jobContext;
}

From source file:org.opencms.ade.contenteditor.CmsContentService.java

/**
 * Returns the value that has to be set for the dynamic attribute.
 *
 * @param file the file where the current content is stored
 * @param value the content value that is represented by the attribute
 * @param attributeName the attribute's name
 * @param editedLocalEntity the entities that where edited last
 * @return the value that has to be set for the dynamic attribute.
 *///from   w w  w .j a  va2 s.c  om
private String getDynamicAttributeValue(CmsFile file, I_CmsXmlContentValue value, String attributeName,
        CmsEntity editedLocalEntity) {

    if ((null != editedLocalEntity) && (editedLocalEntity.getAttribute(attributeName) != null)) {
        getSessionCache().setDynamicValue(attributeName,
                editedLocalEntity.getAttribute(attributeName).getSimpleValue());
    }
    String currentValue = getSessionCache().getDynamicValue(attributeName);
    if (null != currentValue) {
        return currentValue;
    }
    if (null != file) {
        if (value.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME)) {
            List<CmsCategory> categories = new ArrayList<CmsCategory>(0);
            try {
                categories = CmsCategoryService.getInstance().readResourceCategories(getCmsObject(), file);
            } catch (CmsException e) {
                LOG.error(Messages.get().getBundle().key(Messages.ERROR_FAILED_READING_CATEGORIES_1), e);
            }
            I_CmsWidget widget = null;
            try {
                widget = value.getContentDefinition().getContentHandler().getWidget(value);
            } catch (CmsXmlException e) {
                LOG.error(e.getLocalizedMessage(), e);
            }
            if ((null != widget) && (widget instanceof CmsCategoryWidget)) {
                String mainCategoryPath = ((CmsCategoryWidget) widget).getStartingCategory(getCmsObject(),
                        getCmsObject().getSitePath(file));
                StringBuffer pathes = new StringBuffer();
                for (CmsCategory category : categories) {
                    if (category.getPath().startsWith(mainCategoryPath)) {
                        pathes.append(category.getBasePath()).append(category.getPath()).append(',');
                    }
                }
                String dynamicConfigString = pathes.length() > 0 ? pathes.substring(0, pathes.length() - 1)
                        : "";
                getSessionCache().setDynamicValue(attributeName, dynamicConfigString);
                return dynamicConfigString;
            }
        }
    }
    return "";

}

From source file:com.netcrest.pado.tools.pado.command.put.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Map getEntryMap(String fullPath, BufferInfo bufferInfo, List<String> list, boolean keyEnumerated,
        boolean valueEnumerated, int startIndex) throws Exception {
    String pairs = "";
    for (int i = startIndex; i < list.size(); i++) {
        pairs += list.get(i) + " ";
    }// www. j a  va 2  s.c  om

    Map<String, Method> keySetterMap = ReflectionUtil.getAllSettersMap(padoShell.getKeyClass());
    Map<String, Method> valueSetterMap = ReflectionUtil.getAllSettersMap(padoShell.getValueClass());

    String gridPath = GridUtil.getChildPath(fullPath);
    String gridId = SharedCache.getSharedCache().getGridId(fullPath);
    IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IGridMapBiz.class,
            gridPath);
    gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);

    // (x='1,2,3' and y='2',a='hello, world' and b='test')
    HashMap map = new HashMap();
    StringBuffer buffer = new StringBuffer(pairs);
    boolean keySearch = false;
    boolean fieldSearch = false;
    boolean openQuote = false;
    boolean delimiter = false;
    boolean quoted = false;
    String fieldString = "";
    String valueString = "";
    String and = "";

    Object key = null;
    Object value = null;
    for (int i = 0; i < buffer.length(); i++) {
        char c = buffer.charAt(i);
        if (c == '(') {
            if (openQuote == false) {

                String function = null;
                String functionCall = null;
                String functionString = null;
                if (valueString.length() > 0) {
                    functionString = valueString;
                } else if (fieldString.length() > 0) {
                    functionString = fieldString;
                }
                if (functionString != null) {

                    // it's a function

                    // get enclosed parenthesis
                    int enclosedIndex = getEnclosingParenthesis(buffer, i);

                    function = functionString.toLowerCase();
                    if (enclosedIndex == -1) {
                        throw new ParseException("Malformed function call: " + function, i);
                    }

                    functionCall = function + buffer.substring(i, enclosedIndex + 1);
                    Logger.fine("functionCall = |" + functionCall + "|");
                    i = enclosedIndex;
                }
                if (functionCall != null) {
                    if (valueString.length() > 0) {
                        valueString = functionCall;
                    } else if (fieldString.length() > 0) {
                        fieldString = functionCall;
                    }

                } else {
                    key = null;
                    value = null;
                    keySearch = true;
                    fieldSearch = true;
                    fieldString = "";
                    valueString = "";
                }

                quoted = false;

                continue;
            }

        } else if (c == '=') {
            if (keySearch && key == null && keyEnumerated == false) {
                key = padoShell.getKeyClass().newInstance();
            }
            if (keySearch == false && value == null && valueEnumerated == false) {
                if (padoShell.getValueClass() == null) {
                    throw new ClassNotFoundException(
                            "Undefined value class. Use the 'value' command to set the class name");
                }
                value = padoShell.getValueClass().newInstance();
            }
            fieldSearch = false;
            continue;
        } else if (c == ')') {
            if (openQuote == false) {
                Logger.fine("v: field = " + fieldString);
                Logger.fine("v: value = " + valueString);
                Logger.fine("");

                if (valueEnumerated) {
                    Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                    if (k == null) {
                        PadoShell.printlnError(
                                "Error: value not found in the cache for the key number " + fieldString);
                        PadoShell.println("       run 'key -l' to view the enumerated keys.");
                        map.clear();
                        break;
                    }
                    value = gridMapBiz.get(k);
                    if (key == null) {
                        PadoShell.printlnError("Error: value not in the cache - " + fieldString);
                        map.clear();
                        break;
                    }
                    Logger.fine("k = " + k);
                    Logger.fine("key = " + key);
                    Logger.fine("value = " + value);
                } else {
                    if (valueString.length() == 0) {
                        // primitive
                        value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                    } else {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                    }
                }

                map.put(key, value);

                fieldSearch = true;
                quoted = false;
                fieldString = "";
                valueString = "";
                key = null;
                and = "";
                continue;
            }
        } else if (c == '\\') {
            // ignore and treat the next character as a character
            delimiter = true;
            continue;
        } else if (c == '\'') {
            if (delimiter) {
                delimiter = false;
            } else {
                if (openQuote) {
                    quoted = true;
                }
                openQuote = !openQuote;
                continue;
            }
        } else if (c == ' ') {
            if (openQuote == false) {
                boolean andExpected = false;
                if (keySearch) {
                    Logger.fine("k: field = " + fieldString);
                    Logger.fine("k: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(keySetterMap, key, fieldString, valueString);
                        andExpected = true;
                    }
                } else {
                    Logger.fine("v: field = " + fieldString);
                    Logger.fine("v: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                        andExpected = true;
                    }
                }

                if (andExpected) {
                    and = "";
                    int index = -1;
                    for (int j = i; j < buffer.length(); j++) {
                        and += buffer.charAt(j);
                        and = and.trim().toLowerCase();
                        if (and.equals("and")) {
                            index = j;
                            break;
                        } else if (and.length() > 3) {
                            break;
                        }
                    }
                    if (index != -1) {
                        i = index;
                    }
                }

                fieldSearch = true;
                fieldString = "";
                valueString = "";
                and = "";
                quoted = false;
                continue;
            }
        }

        if (c == ',') {

            // if ',' is not enclosed in quotes...
            if (openQuote == false) {

                fieldString = fieldString.trim();
                valueString = valueString.trim();

                // end of key
                Logger.fine("k: field = " + fieldString);
                Logger.fine("k: value = " + valueString);
                Logger.fine("");

                if (keySearch) {
                    if (keyEnumerated) {
                        key = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        if (key == null) {
                            PadoShell.printlnError(
                                    "Error: value not found in the cache for the key number " + fieldString);
                            PadoShell.println("       run 'key -l' to view the enumerated keys.");
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            key = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {
                            updateObject(keySetterMap, key, fieldString, valueString);
                        }
                    }
                } else {

                    if (valueEnumerated) {
                        Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        value = gridMapBiz.get(k);
                        if (value == null) {
                            PadoShell.printlnError("Error: undefined value num " + fieldString);
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {

                            updateObject(valueSetterMap, value, fieldString, valueString);
                        }
                    }

                }

                fieldSearch = true;
                keySearch = false;
                quoted = false;
                fieldString = "";
                valueString = "";
                and = "";
                continue;
            }
        }

        if (fieldSearch) {
            fieldString += c;
        } else if (quoted == false) {
            valueString += c;
        }
    }

    return map;
}

From source file:org.sakaiproject.signup.tool.downloadEvents.EventWorksheet.java

private String getNames(List<SignupAttendee> attendees, boolean needSorting) {
    if (attendees == null)
        return "";

    StringBuffer sb = new StringBuffer();
    for (SignupAttendee s : attendees) {
        s.setDisplayName(sakaiFacade.getUserDisplayLastFirstName(s.getAttendeeUserId()));
    }//from   w  w  w.j  ava  2  s.c o m
    //sorting by last name Jira: Signup-204
    if (needSorting)
        Collections.sort(attendees);

    for (SignupAttendee att : attendees) {
        sb.append(att.getDisplayName());
        final String dateInscription = signupMeetingService
                .getUsersLocalDateTimeString(att.getInscriptionTime());
        if (StringUtils.isNotEmpty(dateInscription)) {
            sb.append(" - " + dateInscription);
        }
        sb.append("\n");
    }
    /* remove the last'\n' one */
    return sb.length() > 1 ? sb.substring(0, sb.length() - 1) : "";
}

From source file:org.wso2.carbon.is.migration.service.SchemaMigrator.java

/**
 * executes content in SQL script//from www .j a va  2s  .  c o m
 *
 * @return StringBuffer
 * @throws Exception
 */
private void executeSQLScript(String dbscriptName) throws Exception {

    String databaseType = DatabaseCreator.getDatabaseType(this.conn);
    boolean keepFormat = false;

    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;
    }

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbscriptName);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            //add the oracle database owner
            if ("oracle".equals(databaseType) && line.contains("databasename :=")) {
                if (dbscriptName.contains(IDENTITY_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getIdentityOracleUser() + "';";
                } else if (dbscriptName.contains(UM_DB_SCRIPT)) {
                    line = "databasename := '" + ISMigrationServiceDataHolder.getUmOracleUser() + "';";
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((DatabaseCreator.checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (Exception e) {
        log.error("Error occurred while executing SQL script for migrating database", e);
        throw new Exception("Error occurred while executing SQL script for migrating database", e);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}