Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

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

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:dylemator.DylematorUI.java

private void writeReport() {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
    String date = sdf.format(new Date());
    String[] questionsFile = this.file.getName().split("\\.");
    boolean newDate = false;
    File resultsFile = new File("Odpowiedzi_" + questionsFile[0] + "_" + date + ".csv");
    if (resultsFile.exists() == false) {
        newDate = true;// w w  w . ja  v a2s  . co  m
    }

    displayCenteredText("KONIEC BADANIA.\r\nDZIKUJEMY ZA UDZIA?.");

    try {

        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(resultsFile, true)));
        StringBuffer sb = new StringBuffer();
        if (newDate) {
            String[] fields = new String[] { "Kod osoby", "Data badania", "Imi", "Nazwisko", "Wiek", "Pe",
                    "Miejsce zamieszkania", "Praworczno", "Lata edukacji", "Urazy gowy",
                    "Leczenie neur.", "Leczenie psych.", "Zaywa leki psych.", "Kopoty z pam.",
                    "Uzalenienia", "Lek zamienny", "Brownie", "Malownicza trasa", "Prysznic", "Ankieta",
                    "Pocig czy autobus", "Kadka", "Typ decyzji", "?d podwodna", "Typ decyzji",
                    "Paczce dziecko", "Typ decyzji", "Wybr Zofii", "Typ decyzji", "Test szczepionki",
                    "Typ decyzji", "Zapobieganie zaraeniu", "Typ decyzji", "Wagonik (wersja standardowa)",
                    "Typ decyzji", "Trujcy dym (wersja standardowa)", "Typ decyzji", "Polityka szczepie",
                    "Typ decyzji", "Oczy", "Typ decyzji", "Podatki", "Typ decyzji",
                    "Wskazwka dotyczca inwestowania", "Typ decyzji" };
            String fieldStr = StringUtils.join(fields, ";");
            sb.append(fieldStr).append("\r\n");
        }
        String[] userData = new String[] { ud.getCode(), date, ud.getName(), ud.getSurname(),
                new Integer(ud.getAge()).toString(), new Integer(ud.getGender()).toString(),
                new Integer(ud.getPlace()).toString(), new Integer(ud.getHandedness()).toString(),
                new Integer(ud.getEducationYears()).toString(),
                // Interview
                new Integer(ud.getHeadInjuries()).toString(), new Integer(ud.getNeurotreatment()).toString(),
                new Integer(ud.getPsychotreatment()).toString(), new Integer(ud.getOnDrugs()).toString(),
                new Integer(ud.getMemoryPb()).toString(), new Integer(ud.getAddictions()).toString(),

                new Long(this.getResults("nonmoral", 0).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 1).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 2).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 3).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 4).getSeconds()).toString(),
                new Long(this.getResults("nonmoral", 5).getSeconds()).toString(),

                new Long(this.getResults("personal", 0).getSeconds()).toString(),
                this.getResults("personal", 0).getAnswerType(),
                new Long(this.getResults("personal", 1).getSeconds()).toString(),
                this.getResults("personal", 1).getAnswerType(),
                new Long(this.getResults("personal", 2).getSeconds()).toString(),
                this.getResults("personal", 2).getAnswerType(),
                new Long(this.getResults("personal", 3).getSeconds()).toString(),
                this.getResults("personal", 3).getAnswerType(),
                new Long(this.getResults("personal", 4).getSeconds()).toString(),
                this.getResults("personal", 4).getAnswerType(),
                new Long(this.getResults("personal", 5).getSeconds()).toString(),
                this.getResults("personal", 5).getAnswerType(),

                new Long(this.getResults("nonpersonal", 0).getSeconds()).toString(),
                this.getResults("nonpersonal", 0).getAnswerType(),
                new Long(this.getResults("nonpersonal", 1).getSeconds()).toString(),
                this.getResults("nonpersonal", 1).getAnswerType(),
                new Long(this.getResults("nonpersonal", 2).getSeconds()).toString(),
                this.getResults("nonpersonal", 2).getAnswerType(),
                new Long(this.getResults("nonpersonal", 3).getSeconds()).toString(),
                this.getResults("personal", 3).getAnswerType(),
                new Long(this.getResults("nonpersonal", 4).getSeconds()).toString(),
                this.getResults("nonpersonal", 4).getAnswerType(),
                new Long(this.getResults("nonpersonal", 5).getSeconds()).toString(),
                this.getResults("nonpersonal", 5).getAnswerType()

        };

        String userDataStr = StringUtils.join(userData, ";");
        sb.append(userDataStr);
        sb.append("\r\n");
        bufferedWriter.append(sb);
        bufferedWriter.flush();
        bufferedWriter.close();
        sb.delete(0, sb.length());
    } catch (IOException ex) {
        Logger.getLogger(DylematorUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    //this.textArea.append("\nCakowity czas: " + totalTimeStr + " sek.\n");
}

From source file:org.kuali.rice.kim.impl.role.RoleDaoOjb.java

public List<RoleMemberBo> getRoleMembersForRoleIds(Collection<String> roleIds, String memberTypeCode,
        Map<String, String> qualification) {
    JdbcTemplate template = new JdbcTemplate(dataSource);
    final List<String> roleIDs = new ArrayList<String>(roleIds);
    final String memberTypeCd = memberTypeCode;
    final Map<String, String> qual = qualification;
    final List<RoleMemberBo> roleMemberBos = new ArrayList<RoleMemberBo>();
    List<RoleMemberBo> results = template.execute(new PreparedStatementCreator() {

        /*/*  w w w  . j a  v a  2  s . co  m*/
         SAMPLE QUERY
                
        SELECT A0.ROLE_MBR_ID AS ROLE_MBR_ID,A0.ROLE_ID AS ROLE_ID,A0.MBR_ID AS MBR_ID,A0.MBR_TYP_CD AS MBR_TYP_CD,A0.VER_NBR AS ROLE_MBR_VER_NBR,A0.OBJ_ID AS ROLE_MBR_OBJ_ID,A0.ACTV_FRM_DT AS ROLE_MBR_ACTV_FRM_DT ,A0.ACTV_TO_DT AS ROLE_MBR_ACTV_TO_DT,
        BO.KIM_TYP_ID AS KIM_TYP_ID, BO.KIM_ATTR_DEFN_ID AS KIM_ATTR_DEFN_ID, BO.ATTR_VAL AS ATTR_VAL, BO.ATTR_DATA_ID AS ATTR_DATA_ID, BO.OBJ_ID AS ATTR_DATA_OBJ_ID, BO.VER_NBR AS ATTR_DATA_VER_NBR,
        CO.OBJ_ID AS ATTR_DEFN_OBJ_ID, CO.VER_NBR as ATTR_DEFN_VER_NBR, CO.NM AS ATTR_NAME, CO.LBL as ATTR_DEFN_LBL, CO.ACTV_IND as ATTR_DEFN_ACTV_IND, CO.NMSPC_CD AS ATTR_DEFN_NMSPC_CD, CO.CMPNT_NM AS ATTR_DEFN_CMPNT_NM
        FROM KRIM_ROLE_MBR_T A0 JOIN KRIM_ROLE_MBR_ATTR_DATA_T BO ON A0.ROLE_MBR_ID = BO.ROLE_MBR_ID  JOIN KRIM_ATTR_DEFN_T CO ON BO.KIM_ATTR_DEFN_ID = CO.KIM_ATTR_DEFN_ID
        WHERE A0.ROLE_ID in ('100000')
                
        UNION ALL
                
        SELECT D0.ROLE_MBR_ID AS ROLE_MBR_ID,D0.ROLE_ID AS ROLE_ID,D0.MBR_ID AS MBR_ID,D0.MBR_TYP_CD AS MBR_TYP_CD,D0.VER_NBR AS ROLE_MBR_VER_NBR,D0.OBJ_ID AS ROLE_MBR_OBJ_ID,D0.ACTV_FRM_DT AS ROLE_MBR_ACTV_FRM_DT ,D0.ACTV_TO_DT AS ROLE_MBR_ACTV_TO_DT,
        '' AS KIM_TYP_ID, '' AS KIM_ATTR_DEFN_ID, '' AS ATTR_VAL, '' AS ATTR_DATA_ID, '' AS ATTR_DATA_OBJ_ID, NULL AS ATTR_DATA_VER_NBR,
        '' AS ATTR_DEFN_OBJ_ID, NULL as ATTR_DEFN_VER_NBR, '' AS ATTR_NAME, '' as ATTR_DEFN_LBL, '' as ATTR_DEFN_ACTV_IND, '' AS ATTR_DEFN_NMSPC_CD, '' AS ATTR_DEFN_CMPNT_NM
        FROM KRIM_ROLE_MBR_T D0
        WHERE D0.ROLE_MBR_ID NOT IN (SELECT DISTINCT (E0.ROLE_MBR_ID) FROM KRIM_ROLE_MBR_ATTR_DATA_T E0)
        AND D0.ROLE_ID IN ('100000')
        */

        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            /*
             The query returns multiple lines for each role by joining a role with each of its members. This allows us to get all the role member
             and role data in a single query (even though we are duplicating the role information across the role members). The cost of this
             comes out to be cheaper than firing indiviudual queries for each role in cases where there are over 500 roles
            */
            StringBuffer sql1 = new StringBuffer("SELECT "
                    + " A0.ROLE_MBR_ID AS ROLE_MBR_ID,A0.ROLE_ID AS ROLE_ID,A0.MBR_ID AS MBR_ID,A0.MBR_TYP_CD AS MBR_TYP_CD,A0.VER_NBR AS ROLE_MBR_VER_NBR,A0.OBJ_ID AS ROLE_MBR_OBJ_ID,A0.ACTV_FRM_DT AS ROLE_MBR_ACTV_FRM_DT ,A0.ACTV_TO_DT AS ROLE_MBR_ACTV_TO_DT, "
                    + " BO.KIM_TYP_ID AS KIM_TYP_ID, BO.KIM_ATTR_DEFN_ID AS KIM_ATTR_DEFN_ID, BO.ATTR_VAL AS ATTR_VAL, BO.ATTR_DATA_ID AS ATTR_DATA_ID, BO.OBJ_ID AS ATTR_DATA_OBJ_ID, BO.VER_NBR AS ATTR_DATA_VER_NBR,  "
                    + " C0.KIM_ATTR_DEFN_ID AS KIM_ATTR_DEFN_ID, C0.OBJ_ID AS ATTR_DEFN_OBJ_ID, C0.VER_NBR as ATTR_DEFN_VER_NBR, C0.NM AS ATTR_NAME, C0.LBL as ATTR_DEFN_LBL, C0.ACTV_IND as ATTR_DEFN_ACTV_IND, C0.NMSPC_CD AS ATTR_DEFN_NMSPC_CD, C0.CMPNT_NM AS ATTR_DEFN_CMPNT_NM "
                    + " FROM KRIM_ROLE_MBR_T A0 JOIN KRIM_ROLE_MBR_ATTR_DATA_T BO ON A0.ROLE_MBR_ID = BO.ROLE_MBR_ID "
                    + " JOIN KRIM_ATTR_DEFN_T C0 ON BO.KIM_ATTR_DEFN_ID = C0.KIM_ATTR_DEFN_ID  ");

            StringBuffer sql2 = new StringBuffer("SELECT"
                    + " D0.ROLE_MBR_ID AS ROLE_MBR_ID,D0.ROLE_ID AS ROLE_ID,D0.MBR_ID AS MBR_ID,D0.MBR_TYP_CD AS MBR_TYP_CD,D0.VER_NBR AS ROLE_MBR_VER_NBR,D0.OBJ_ID AS ROLE_MBR_OBJ_ID,D0.ACTV_FRM_DT AS ROLE_MBR_ACTV_FRM_DT ,D0.ACTV_TO_DT AS ROLE_MBR_ACTV_TO_DT, "
                    + " '' AS KIM_TYP_ID, '' AS KIM_ATTR_DEFN_ID, '' AS ATTR_VAL, '' AS ATTR_DATA_ID, '' AS ATTR_DATA_OBJ_ID, NULL AS ATTR_DATA_VER_NBR,"
                    + " '' AS KIM_ATTR_DEFN_ID,'' AS ATTR_DEFN_OBJ_ID, NULL as ATTR_DEFN_VER_NBR, '' AS ATTR_NAME, '' as ATTR_DEFN_LBL, '' as ATTR_DEFN_ACTV_IND, '' AS ATTR_DEFN_NMSPC_CD, '' AS ATTR_DEFN_CMPNT_NM "
                    + " FROM KRIM_ROLE_MBR_T D0 "
                    + " WHERE D0.ROLE_MBR_ID NOT IN (SELECT DISTINCT (E0.ROLE_MBR_ID) FROM KRIM_ROLE_MBR_ATTR_DATA_T E0)");

            StringBuffer criteria = new StringBuffer();

            List<String> params1 = new ArrayList<String>();
            List<String> params2 = new ArrayList<String>();

            if (roleIDs != null && !roleIDs.isEmpty()) {
                criteria.append("A0.ROLE_ID IN (");

                for (String roleId : roleIDs) {
                    criteria.append("?,");
                    params1.add(roleId);
                    params2.add(roleId);
                }
                criteria.deleteCharAt(criteria.length() - 1);
                criteria.append(")");
            }

            if (memberTypeCd != null) {
                if (criteria.length() > 0) {
                    criteria.append(" AND ");
                }

                criteria.append("A0.MBR_TYP_CD = ?");
                params1.add(memberTypeCd);
                params2.add(memberTypeCd);
            }

            // Assuming that at least a role id or role member type code is specified
            if (criteria.length() > 0) {
                sql1.append(" WHERE ");
                sql2.append(" AND ");
                sql1.append(criteria);
                sql2.append(criteria.toString().replaceAll("A0", "D0"));
            }

            if (qual != null && CollectionUtils.isNotEmpty(qual.keySet())) {

                // If Qualifiers present then sql2 should not be returning any result as it finds
                // rolemembers with now attributes
                sql2 = new StringBuffer();

                if (criteria.length() > 0) {
                    sql1.append(" AND ");
                } else {
                    sql1.append(" WHERE ");
                }

                sql1.append(" EXISTS (SELECT B1.ROLE_MBR_ID FROM KRIM_ROLE_MBR_ATTR_DATA_T B1 WHERE (");
                for (Map.Entry<String, String> qualifier : qual.entrySet()) {
                    if (StringUtils.isNotEmpty(qualifier.getValue())) {
                        String value = (qualifier.getValue()).replace('*', '%');
                        sql1.append(" (B1.ATTR_VAL LIKE ? AND B1.KIM_ATTR_DEFN_ID = ? ) ");
                        params1.add(value);
                        params1.add(qualifier.getKey());
                    }
                    sql1.append("OR");
                }
                sql1.delete(sql1.length() - 2, sql1.length());
                sql1.append(") AND B1.ROLE_MBR_ID = A0.ROLE_MBR_ID )");

            }

            StringBuffer sql = new StringBuffer(sql1.toString());

            if (sql2.length() > 0) {
                sql.append(" UNION ALL ");
                sql.append(sql2.toString());
            }

            sql.append(" ORDER BY ROLE_MBR_ID ");

            PreparedStatement statement = connection.prepareStatement(sql.toString());
            int i = 1;
            for (String param : params1) {
                statement.setString(i, param);
                i++;
            }

            if (sql2.length() > 0) {
                for (String param : params2) {
                    statement.setString(i, param);
                    i++;
                }
            }

            return statement;
        }
    }, new PreparedStatementCallback<List<RoleMemberBo>>() {
        public List<RoleMemberBo> doInPreparedStatement(PreparedStatement statement)
                throws SQLException, DataAccessException {
            ResultSet rs = statement.executeQuery();
            try {
                RoleMemberBo lastRoleMember = null;
                while (rs.next()) {
                    boolean processRolemember = true;

                    String roleId = rs.getString("ROLE_ID");
                    String id = rs.getString("ROLE_MBR_ID");
                    String memberId = rs.getString("MBR_ID");

                    MemberType memberType = MemberType.fromCode(rs.getString("MBR_TYP_CD"));
                    DateTime activeFromDate = rs.getDate("ROLE_MBR_ACTV_FRM_DT") == null ? null
                            : new DateTime(rs.getDate("ROLE_MBR_ACTV_FRM_DT"));
                    DateTime activeToDate = rs.getDate("ROLE_MBR_ACTV_TO_DT") == null ? null
                            : new DateTime(rs.getDate("ROLE_MBR_ACTV_TO_DT"));

                    // Since we are joining role members and attributes we would have multiple role member rows
                    // but one row per attribute so check if its the first time we are seeing the role member
                    if (lastRoleMember == null || !id.equals(lastRoleMember.getId())) {
                        RoleMember roleMember = RoleMember.Builder.create(roleId, id, memberId, memberType,
                                activeFromDate, activeToDate, new HashMap<String, String>(), "", "").build();
                        Long roleVersionNbr = rs.getLong("ROLE_MBR_VER_NBR");
                        String roleObjId = rs.getString("ROLE_MBR_OBJ_ID");

                        RoleMemberBo roleMemberBo = RoleMemberBo.from(roleMember);
                        roleMemberBo.setVersionNumber(roleVersionNbr);
                        roleMemberBo.setObjectId(roleObjId);
                        List<RoleMemberAttributeDataBo> roleMemAttrBos = new ArrayList<RoleMemberAttributeDataBo>();

                        roleMemberBo.setAttributeDetails(roleMemAttrBos);
                        if (roleMemberBo.isActive(new Timestamp(System.currentTimeMillis()))) {
                            roleMemberBos.add(roleMemberBo);
                        } else {
                            processRolemember = false;
                        }

                        lastRoleMember = roleMemberBo;
                    }

                    String kimTypeId = rs.getString("KIM_TYP_ID");
                    String attrKey = rs.getString("KIM_ATTR_DEFN_ID");
                    String attrVal = rs.getString("ATTR_VAL");
                    if (processRolemember && StringUtils.isNotEmpty(kimTypeId)) {
                        KimType theType = KimApiServiceLocator.getKimTypeInfoService().getKimType(kimTypeId);
                        // Create RoleMemberAttributeDataBo for this row
                        RoleMemberAttributeDataBo roleMemAttrDataBo = new RoleMemberAttributeDataBo();

                        KimAttribute.Builder attrBuilder = KimAttribute.Builder.create(
                                rs.getString("ATTR_DEFN_CMPNT_NM"), rs.getString("ATTR_NAME"),
                                rs.getString("ATTR_DEFN_NMSPC_CD"));
                        attrBuilder.setActive(Truth.strToBooleanIgnoreCase(rs.getString("ATTR_DEFN_ACTV_IND")));
                        attrBuilder.setAttributeLabel(rs.getString("ATTR_DEFN_LBL"));
                        attrBuilder.setId(rs.getString("KIM_ATTR_DEFN_ID"));
                        attrBuilder.setObjectId(rs.getString("ATTR_DEFN_OBJ_ID"));
                        attrBuilder.setVersionNumber(rs.getLong("ATTR_DEFN_VER_NBR"));

                        roleMemAttrDataBo.setId(rs.getString("ATTR_DATA_ID"));
                        roleMemAttrDataBo.setAssignedToId(id);
                        roleMemAttrDataBo.setKimTypeId(kimTypeId);
                        roleMemAttrDataBo.setKimType(KimTypeBo.from(theType));
                        roleMemAttrDataBo.setKimAttributeId(attrBuilder.getId());
                        roleMemAttrDataBo.setAttributeValue(attrVal);
                        roleMemAttrDataBo.setVersionNumber(rs.getLong("ATTR_DATA_VER_NBR"));
                        roleMemAttrDataBo.setObjectId(rs.getString("ATTR_DATA_OBJ_ID"));

                        roleMemAttrDataBo.setKimAttribute(KimAttributeBo.from(attrBuilder.build()));
                        lastRoleMember.getAttributeDetails().add(roleMemAttrDataBo);
                    }

                }
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
            return roleMemberBos;
        }
    });
    return roleMemberBos;
}

From source file:com.glaf.core.db.TransformTable.java

protected void transform(QueryDefinition queryDefinition, Map<String, ColumnDefinition> columnMap,
        List<String> aggregationKeys, Map<String, TableModel> resultMap) {
    Map<String, Object> params = SystemConfig.getContextMap();
    StringBuffer sb = new StringBuffer(1000);
    String sql = queryDefinition.getSql();
    sql = QueryUtils.replaceSQLVars(sql);
    sql = QueryUtils.replaceSQLParas(sql, params);
    logger.debug("sql=" + sql);
    logger.debug("columnMap=" + columnMap.keySet());
    Long databaseId = queryDefinition.getDatabaseId();
    String systemName = Environment.getCurrentSystemName();

    List<ColumnModel> cellModelList = new java.util.ArrayList<ColumnModel>();
    try {//from  w  ww .j av  a2s .c  o  m
        Database database = getDatabaseService().getDatabaseById(databaseId);
        if (database != null) {
            Environment.setCurrentSystemName(database.getName());
        }
        List<Map<String, Object>> rows = getTablePageService().getListData(sql, params);
        if (rows != null && !rows.isEmpty()) {
            logger.debug(queryDefinition.getTitle() + " " + rows.size());
            logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag());
            logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn());
            /**
             * ????
             */
            if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")
                    && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && rows.size() == 1) {
                Map<String, Object> dataMap = rows.get(0);
                logger.debug("?dataMap?:" + dataMap);
                ColumnDefinition idField = columnMap.get(aggregationKeys.get(0).toLowerCase());
                ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase());
                if (idField != null && field != null) {
                    String javaType = field.getJavaType();
                    List<TableModel> list = new ArrayList<TableModel>();
                    Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (key == null || value == null) {
                            continue;
                        }
                        TableModel tableModel = new TableModel();
                        tableModel.setTableName(queryDefinition.getTargetTableName());
                        ColumnModel cell = new ColumnModel();
                        cell.setColumnName(queryDefinition.getRotatingColumn());
                        cell.setType(javaType);

                        // logger.debug(cell.getColumnName()+"->"+javaType);

                        if ("String".equals(javaType)) {
                            cell.setStringValue(ParamUtils.getString(dataMap, key));
                            cell.setValue(cell.getStringValue());
                        } else if ("Integer".equals(javaType)) {
                            cell.setIntValue(ParamUtils.getInt(dataMap, key));
                            cell.setValue(cell.getIntValue());
                        } else if ("Long".equals(javaType)) {
                            cell.setLongValue(ParamUtils.getLong(dataMap, key));
                            cell.setValue(cell.getLongValue());
                        } else if ("Double".equals(javaType)) {
                            cell.setDoubleValue(ParamUtils.getDouble(dataMap, key));
                            cell.setValue(cell.getDoubleValue());
                        } else if ("Date".equals(javaType)) {
                            cell.setDateValue(ParamUtils.getDate(dataMap, key));
                            cell.setValue(cell.getDateValue());
                        } else {
                            cell.setValue(value);
                        }

                        tableModel.addColumn(cell);

                        ColumnModel idColumn = new ColumnModel();
                        idColumn.setColumnName(aggregationKeys.get(0));
                        idColumn.setJavaType(idField.getJavaType());
                        idColumn.setValue(key);
                        tableModel.setIdColumn(idColumn);
                        list.add(tableModel);
                    }
                    logger.debug("update datalist:" + list);
                    Environment.setCurrentSystemName(systemName);
                    getTableDataService().updateTableData(list);
                }
            } else {
                Set<String> cols = new HashSet<String>();
                for (Map<String, Object> dataMap : rows) {
                    sb.delete(0, sb.length());
                    cols.clear();
                    cellModelList.clear();
                    logger.debug("dataMap:" + dataMap);
                    Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                    for (Entry<String, Object> entry : entrySet) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (key == null || value == null) {
                            continue;
                        }
                        /**
                         * ????
                         */
                        if (cols.contains(key.toLowerCase())) {
                            continue;
                        }
                        if (columnMap.get(key.toLowerCase()) == null) {
                            logger.debug(key + " definition is null");
                            continue;
                        }

                        if (aggregationKeys.contains(key.toLowerCase())) {
                            sb.append(value).append("_");
                        }

                        ColumnDefinition column = columnMap.get(key.toLowerCase());
                        String javaType = column.getJavaType();

                        ColumnModel cell = new ColumnModel();
                        cell.setColumnName(column.getColumnName());
                        cell.setType(javaType);

                        // logger.debug(cell.getColumnName()+"->"+javaType);

                        if ("String".equals(javaType)) {
                            cell.setStringValue(ParamUtils.getString(dataMap, key));
                            cell.setValue(cell.getStringValue());
                        } else if ("Integer".equals(javaType)) {
                            cell.setIntValue(ParamUtils.getInt(dataMap, key));
                            cell.setValue(cell.getIntValue());
                        } else if ("Long".equals(javaType)) {
                            cell.setLongValue(ParamUtils.getLong(dataMap, key));
                            cell.setValue(cell.getLongValue());
                        } else if ("Double".equals(javaType)) {
                            cell.setDoubleValue(ParamUtils.getDouble(dataMap, key));
                            cell.setValue(cell.getDoubleValue());
                        } else if ("Date".equals(javaType)) {
                            cell.setDateValue(ParamUtils.getDate(dataMap, key));
                            cell.setValue(cell.getDateValue());
                        } else {
                            cell.setValue(value);
                        }

                        cellModelList.add(cell);
                        cols.add(cell.getColumnName());

                        // logger.debug(cell.getColumnName()+"->"+javaType+":"+cell.getValue());
                    }

                    // logger.debug(sb.toString());

                    /**
                     * ??
                     */
                    if (sb.toString().endsWith("_")) {
                        sb.delete(sb.length() - 1, sb.length());
                        String rowKey = sb.toString();
                        logger.debug("rowKey=" + rowKey);
                        TableModel rowModel = resultMap.get(rowKey);
                        if (rowModel == null) {
                            rowModel = new TableModel();
                            ColumnModel cell01 = new ColumnModel();
                            cell01.setColumnName("ID");
                            cell01.setType("String");
                            cell01.setValueExpression(ExpressionConstants.ID_EXPRESSION);
                            cols.add("ID");
                            rowModel.addColumn(cell01);
                            rowModel.setIdColumn(cell01);

                            ColumnModel cell04 = new ColumnModel();
                            cell04.setColumnName("AGGREGATIONKEY");
                            cell04.setType("String");
                            cols.add("AGGREGATIONKEY");
                            rowModel.addColumn(cell04);

                            resultMap.put(rowKey, rowModel);
                        }

                        for (ColumnModel cell : cellModelList) {
                            /**
                             * ??
                             */
                            if (columnMap.get(cell.getColumnName().toLowerCase()) != null) {
                                rowModel.addColumn(cell);
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    } finally {
        Environment.setCurrentSystemName(systemName);
    }
}

From source file:stg.pr.engine.CProcessRequestEngine.java

/**
 * The RPE sends a mail if the pre is unable to execute the schedule
 * associated with the request.//from   ww  w.  j  a v  a 2s  .c  o m
 * 
 * @param plRequestId
 *            long Request Id
 * @param plScheduleId
 *            long Schedule Id
 * @param pstrJobId
 *            String Process Name
 * @param objThrowable
 *            Throwable
 * @param pstrAdditionalEmailRecipients
 */
private void sendScheduleUnExecutedMail(long plRequestId, long plScheduleId, String pstrJobId,
        String pstrJobName, Throwable objThrowable, String pstrAdditionalEmailRecipients) {
    try {
        // CMailer mailer = CMailer.getInstance(CSettings.get("pr.mailtype",
        // "SMTP"));
        EMail email = new EMail();
        if (pstrAdditionalEmailRecipients != null) {
            try {
                email.setTORecipient(CSettings.get("mail.recepientTO") + "," + pstrAdditionalEmailRecipients);
            } catch (AddressException e) {
                objEngineLogger_.warn("Invalid Email Address of recepients. Schedule #" + plScheduleId
                        + " Email(s) #" + pstrAdditionalEmailRecipients, e);
                objEngineLogger_.info("Setting default recepient address...");
                email.setTORecipient(CSettings.get("mail.recepientTO"));
            }
        } else {
            email.setTORecipient(CSettings.get("mail.recepientTO"));
        }
        email.setEMailId("USR#" + plRequestId);
        email.setCCRecipient(CSettings.get("mail.recepientCC"));
        StringBuffer sbuf = new StringBuffer(100);
        sbuf.append("Request #");
        sbuf.append(plRequestId);
        sbuf.append(" Job Id #");
        sbuf.append(pstrJobId);
        sbuf.append(" :  Associated Schedule #");
        sbuf.append(plScheduleId);
        sbuf.append(" Could Not Be Executed !!");
        email.setSubject(sbuf.toString());

        sbuf.delete(0, sbuf.length());
        sbuf.append("Request  :");
        sbuf.append(plRequestId);
        sbuf.append(NEW_LINE);
        sbuf.append("Job Id   : ");
        sbuf.append(pstrJobId);
        sbuf.append(NEW_LINE);
        sbuf.append("Job Name : ");
        sbuf.append(pstrJobName);
        sbuf.append(NEW_LINE);
        sbuf.append(NEW_LINE);
        sbuf.append(
                "The schedule associated with the request could not be executed because of the following reason:");
        sbuf.append(NEW_LINE);
        sbuf.append(NEW_LINE);
        if (objThrowable instanceof ThreadDeath) {
            sbuf.append("Error Message: Process was killed from the Web Service.");
            sbuf.append(NEW_LINE);
            sbuf.append(NEW_LINE);
            sbuf.append("Stack Trace: Not available.");

        } else {
            sbuf.append("Error Message: " + objThrowable.getMessage());
            sbuf.append(NEW_LINE);
            sbuf.append(NEW_LINE);
            sbuf.append("Stack Trace: " + exceptionToString(objThrowable));
        }
        sbuf.append(NEW_LINE);
        sbuf.append(NEW_LINE);
        sbuf.append("Corrective Action:");
        sbuf.append(NEW_LINE);
        sbuf.append(NEW_LINE);
        sbuf.append("\t\t Contact Support Team or Help Desk.");
        if (objThrowable instanceof ThreadDeath) {
            sbuf.append(" Please do not execute this process till you have a word with the support team.");
        }
        sbuf.append(NEW_LINE);
        email.setMessageBody(sbuf.toString());

        CMailer.getInstance(CSettings.get("pr.mailtype")).sendAsyncMail(email);
    } catch (Throwable e) {
        objEngineLogger_.error("Unable to send the Mail Message due to : ", e);
        // Need not be thrown. Email is a facility but not a necessity. Log
        // this error.
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*from   w w w  .  j  a  v  a 2s  .c  o  m*/

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(Settings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(Settings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:cx.fbn.nevernote.gui.BrowserWindow.java

private void handleLocalAttachment(QMimeData mime, String mimeType) {
    logger.log(logger.EXTREME, "Attaching local file");
    List<QUrl> urlList = mime.urls();
    String script_start = new String("document.execCommand('insertHtml', false, '");
    String script_end = new String("');");
    StringBuffer buffer;

    String[] type = mimeType.split("/");
    String icon = findIcon(type[1]);
    if (icon.equals("attachment.png"))
        icon = findIcon(type[0]);/*from  www  .  j  a  v a 2  s.  c  o  m*/
    buffer = new StringBuffer(100);

    for (int i = 0; i < urlList.size(); i++) {
        String url = urlList.get(i).toString();

        // Start building the HTML
        if (icon.equals("attachment.png"))
            icon = findIcon(url.substring(url.lastIndexOf(".") + 1));
        String imageURL = FileUtils.toFileURLString(Global.getFileManager().getImageDirFile(icon));

        logger.log(logger.EXTREME, "Creating resource ");
        Resource newRes = createResource(url, i, mimeType, true);
        if (newRes == null)
            return;
        logger.log(logger.EXTREME, "New resource size: " + newRes.getData().getSize());
        currentNote.getResources().add(newRes);

        String fileName = newRes.getGuid() + Global.attachmentNameDelimeter
                + newRes.getAttributes().getFileName();
        // If we have a PDF, we need to setup the preview.
        if (icon.equalsIgnoreCase("pdf.png") && Global.pdfPreview()) {
            logger.log(logger.EXTREME, "Setting up PDF preview");
            if (newRes.getAttributes() != null && newRes.getAttributes().getFileName() != null
                    && !newRes.getAttributes().getFileName().trim().equals(""))
                fileName = newRes.getGuid() + Global.attachmentNameDelimeter
                        + newRes.getAttributes().getFileName();
            else
                fileName = newRes.getGuid() + ".pdf";
            QFile file = new QFile(Global.getFileManager().getResDirPath(fileName));
            QFile.OpenMode mode = new QFile.OpenMode();
            mode.set(QFile.OpenModeFlag.WriteOnly);
            file.open(mode);
            QDataStream out = new QDataStream(file);
            //              Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(newRes.getGuid(), true);
            QByteArray binData = new QByteArray(newRes.getData().getBody());
            //            resBinary = null;
            out.writeBytes(binData.toByteArray());
            file.close();

            PDFPreview pdfPreview = new PDFPreview();
            if (pdfPreview.setupPreview(Global.getFileManager().getResDirPath(fileName), "pdf", 0)) {
                imageURL = file.fileName() + ".png";
            }
        }

        logger.log(logger.EXTREME, "Generating link tags");
        buffer.delete(0, buffer.length());
        buffer.append("<a en-tag=\"en-media\" guid=\"" + newRes.getGuid() + "\" ");
        buffer.append(" onContextMenu=\"window.jambi.imageContextMenu(&apos;")
                .append(Global.getFileManager().getResDirPath(fileName)).append("&apos;);\" ");
        buffer.append("type=\"" + mimeType + "\" href=\"nnres://" + fileName + "\" hash=\""
                + Global.byteArrayToHexString(newRes.getData().getBodyHash()) + "\" >");
        buffer.append("<img src=\"" + imageURL + "\" title=\"" + newRes.getAttributes().getFileName());
        buffer.append("\"></img>");
        buffer.append("</a>");
        browser.page().mainFrame().evaluateJavaScript(script_start + buffer.toString() + script_end);
    }
    return;
}

From source file:com.sun.faces.generate.RenderKitSpecificationGenerator.java

public static void generateRenderersDocs() throws Exception {
    StringBuffer sb = null;
    RenderKitBean renderKit = null;//from  w  w  w  .j av  a2  s . co m
    DescriptionBean descBean = null;
    AttributeBean attribute = null;
    String description, rendererType, componentFamily, defaultValue, title, curAttr;

    // generate the docus for each renderer

    if (null == (renderKit = fcb.getRenderKit(renderKitId))) {
        RenderKitBean[] kits = null;
        if (null == (kits = fcb.getRenderKits())) {
            throw new IllegalStateException("no RenderKits");
        }
        if (null == (renderKit = kits[0])) {
            throw new IllegalStateException("no RenderKits");
        }
    }
    RendererBean[] renderers = renderKit.getRenderers();
    AttributeBean[] attributes = null;
    sb = new StringBuffer(2048);

    for (int i = 0, len = renderers.length; i < len; i++) {
        if (null == renderers[i]) {
            throw new IllegalStateException("null Renderer at index: " + i);
        }
        attributes = renderers[i].getAttributes();

        sb.append(DOCTYPE + "\n");
        sb.append("<html>\n");
        sb.append("<head>\n");
        // PENDING timestamp
        sb.append("<title>\n");
        title = "<font size=\"-1\">component-family:</font> "
                + (componentFamily = renderers[i].getComponentFamily())
                + " <font size=\"-1\">renderer-type:</font> " + (rendererType = renderers[i].getRendererType());
        sb.append(title + "\n");
        sb.append("</title>\n");
        // PENDING META tag
        sb.append("<link REL =\"stylesheet\" TYPE=\"text/css\" HREF=\"../stylesheet.css\" TITLE=\"Style\">\n");
        sb.append("</head>\n");
        sb.append("<script>\n");
        sb.append("function asd()\n");
        sb.append("{\n");
        sb.append("  parent.document.title=" + title + "\n");
        sb.append("}\n");
        sb.append("</SCRIPT>\n");
        sb.append("<body BGCOLOR=\"white\" onload=\"asd();\">\n");
        sb.append("\n");
        sb.append("<H2><font size=\"-1\">" + renderKitId + " render-kit</font>\n");
        sb.append("<br />\n");
        sb.append(title + "\n");
        sb.append("</H2>\n");
        sb.append("<HR />\n");
        descBean = renderers[i].getDescription("");
        description = (null == descBean) ? "" : descBean.getDescription();
        sb.append("<P>" + description + "</P>\n");
        // render our renders children status

        if (renderers[i].isRendersChildren()) {
            sb.append("<P>This renderer is responsible for rendering its children.</P>");
        } else {
            sb.append("<P>This renderer is not responsible for rendering its children.</P>");
        }

        // if we have attributes
        if ((null == attributes) || (0 < attributes.length)) {
            sb.append("<HR />\n");
            sb.append("<a NAME=\"attributes\"><!-- --></a>\n");
            sb.append("\n");
            sb.append("<h3>Note:</h3>\n");
            sb.append("\n");
            sb.append("<p>Attributes with a <code>pass-through</code> value of\n");
            sb.append("<code>true</code> are not interpreted by the renderer and are passed\n");
            sb.append(
                    "straight through to the rendered markup, without checking for validity.  Attributes with a\n");
            sb.append("<code>pass-through</code> value of <code>false</code> are interpreted\n");
            sb.append("by the renderer, and may or may not be checked for validity by the renderer.</p>\n");
            sb.append("\n");
            sb.append("<table BORDER=\"1\" CELLPADDING=\"3\" CELLSPACING=\"0\" WIDTH=\"100%\">\n");
            sb.append("<tr BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n");
            sb.append("<td COLSPAN=\"5\"><font SIZE=\"+2\">\n");
            sb.append("<b>Attributes</b></font></td>\n");
            sb.append("</tr>\n");
            sb.append("<tr BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">\n");
            sb.append("<th><b>attribute-name</b></th>\n");
            sb.append("<th><b>pass-through</b></th>\n");
            sb.append("<th><b>attribute-class</b></th>\n");
            sb.append("<th><b>description</b></th>\n");
            sb.append("<th><b>default-value</b></th>\n");
            sb.append("</tr>\n");
            sb.append("       \n");
            // output each attribute
            for (int j = 0, attrLen = attributes.length; j < attrLen; j++) {
                sb.append("<tr BGCOLOR=\"white\" CLASS=\"TableRowColor\">\n");
                sb.append("<td ALIGN=\"right\" VALIGN=\"top\" WIDTH=\"1%\"><code>\n");
                sb.append("&nbsp;" + attributes[j].getAttributeName() + "\n");
                sb.append("</td>\n");
                sb.append("<td ALIGN=\"right\" VALIGN=\"top\">" + attributes[j].isPassThrough() + "</td>\n");
                sb.append("<td><code>" + attributes[j].getAttributeClass() + "</code></td>\n");
                descBean = attributes[j].getDescription("");
                description = (null == descBean) ? "" : descBean.getDescription();
                sb.append("<td>" + description + "</td>\n");
                if (null == (defaultValue = attributes[j].getDefaultValue())) {
                    defaultValue = "undefined";
                }
                sb.append("<td>" + defaultValue + "<td>\n");
                sb.append("</tr>\n");
            }
            sb.append("</table>\n");
        } else {
            sb.append("<p>This renderer-type has no attributes</p>\n");
        }
        sb.append("<hr>\n");
        sb.append("Copyright (c) 2003-2004 Sun Microsystems, Inc. All Rights Reserved.\n");
        sb.append("</body>\n");
        sb.append("</html>\n");
        writeStringToFile(sb.toString(),
                new File(renderKitDirectory, componentFamily + rendererType + ".html"));
        sb.delete(0, sb.length());
    }
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSONgc(String host, String path, String params) {
    int httpCode = -1;
    String httpLocation = null;//from w w  w.j  a v  a2s  .co  m

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

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

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            // POST
            final URL u = new URL("http://" + host + path);
            uc = u.openConnection();

            uc.setRequestProperty("Host", host);
            uc.setRequestProperty("Cookie", cookiesDone);
            uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
            uc.setRequestProperty("Referer", host + "/" + path);

            if (settings.asBrowser == 1) {
                uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                uc.setRequestProperty("Accept-Language", "en-US");
                uc.setRequestProperty("User-Agent", idBrowser);
                uc.setRequestProperty("Connection", "keep-alive");
                uc.setRequestProperty("Keep-Alive", "300");
            }

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(timeout);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(params);
            wr.flush();
            wr.close();

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            Log.i(Settings.tag + " | JSON",
                    "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                            + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path + "?"
                            + paramsLog);

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSONgc: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:com.glaf.core.db.TransformTable.java

public void transformQueryToTable(String tableName, String queryId, String sourceSystemName) {
    TableDefinition tableDefinition = getTableDefinitionService().getTableDefinition(tableName);
    QueryDefinition queryDefinition = getQueryDefinitionService().getQueryDefinition(queryId);
    if (queryDefinition != null && tableDefinition != null
            && StringUtils.isNotEmpty(tableDefinition.getAggregationKeys())) {
        Map<String, Object> params = SystemConfig.getContextMap();
        List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tableName);
        Map<String, ColumnDefinition> columnMap = new java.util.HashMap<String, ColumnDefinition>();

        for (ColumnDefinition column : columns) {
            columnMap.put(column.getColumnName(), column);
            columnMap.put(column.getColumnName().toLowerCase(), column);
        }//from ww w  .  j  a v  a 2  s  .co  m

        List<String> keys = StringTools.split(tableDefinition.getAggregationKeys());
        StringBuffer sb = new StringBuffer(1000);

        List<ColumnModel> cellModelList = new java.util.ArrayList<ColumnModel>();
        Map<String, TableModel> resultMap = new java.util.HashMap<String, TableModel>();

        if (queryDefinition.getSql() != null) {
            String sql = queryDefinition.getSql();
            sql = QueryUtils.replaceSQLVars(sql);
            sql = QueryUtils.replaceSQLParas(sql, params);
            logger.debug("sql=" + sql);
            String systemName = Environment.getCurrentSystemName();
            try {
                Environment.setCurrentSystemName(sourceSystemName);
                List<Map<String, Object>> rows = getTablePageService().getListData(sql, params);
                if (rows != null && !rows.isEmpty()) {
                    logger.debug(queryDefinition.getTitle() + " " + rows.size());
                    logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag());
                    logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn());
                    /**
                     * ????
                     */
                    if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")
                            && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn())
                            && rows.size() == 1) {
                        Map<String, Object> dataMap = rows.get(0);
                        logger.debug("?dataMap?:" + dataMap);
                        ColumnDefinition idField = columnMap.get(keys.get(0).toLowerCase());
                        ColumnDefinition field = columnMap
                                .get(queryDefinition.getRotatingColumn().toLowerCase());
                        if (idField != null && field != null) {
                            String javaType = field.getJavaType();
                            List<TableModel> list = new ArrayList<TableModel>();
                            Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                            for (Entry<String, Object> entry : entrySet) {
                                String key = entry.getKey();
                                Object value = entry.getValue();
                                if (key == null || value == null) {
                                    continue;
                                }
                                TableModel tableModel = new TableModel();
                                tableModel.setTableName(queryDefinition.getTargetTableName());
                                ColumnModel cell = new ColumnModel();
                                cell.setColumnName(queryDefinition.getRotatingColumn());
                                cell.setType(javaType);

                                // logger.debug(cell.getColumnName()+"->"+javaType);

                                if ("String".equals(javaType)) {
                                    cell.setStringValue(ParamUtils.getString(dataMap, key));
                                    cell.setValue(cell.getStringValue());
                                } else if ("Integer".equals(javaType)) {
                                    cell.setIntValue(ParamUtils.getInt(dataMap, key));
                                    cell.setValue(cell.getIntValue());
                                } else if ("Long".equals(javaType)) {
                                    cell.setLongValue(ParamUtils.getLong(dataMap, key));
                                    cell.setValue(cell.getLongValue());
                                } else if ("Double".equals(javaType)) {
                                    cell.setDoubleValue(ParamUtils.getDouble(dataMap, key));
                                    cell.setValue(cell.getDoubleValue());
                                } else if ("Date".equals(javaType)) {
                                    cell.setDateValue(ParamUtils.getDate(dataMap, key));
                                    cell.setValue(cell.getDateValue());
                                } else {
                                    cell.setValue(value);
                                }

                                tableModel.addColumn(cell);

                                ColumnModel idColumn = new ColumnModel();
                                idColumn.setColumnName(keys.get(0));
                                idColumn.setJavaType(idField.getJavaType());
                                idColumn.setValue(key);
                                tableModel.setIdColumn(idColumn);
                                list.add(tableModel);
                            }
                            logger.debug("update datalist:" + list);
                            Environment.setCurrentSystemName(systemName);
                            getTableDataService().updateTableData(list);
                        }
                    } else {
                        Set<String> cols = new HashSet<String>();
                        for (Map<String, Object> dataMap : rows) {
                            sb.delete(0, sb.length());
                            cols.clear();
                            cellModelList.clear();

                            Set<Entry<String, Object>> entrySet = dataMap.entrySet();
                            for (Entry<String, Object> entry : entrySet) {
                                String key = entry.getKey();
                                Object value = entry.getValue();
                                if (key == null || value == null) {
                                    continue;
                                }
                                /**
                                 * ????
                                 */
                                if (cols.contains(key.toLowerCase())) {
                                    continue;
                                }
                                if (columnMap.get(key.toLowerCase()) == null) {
                                    continue;
                                }

                                if (keys.contains(key)) {
                                    sb.append(value).append("_");
                                }

                                ColumnDefinition column = columnMap.get(key.toLowerCase());
                                String javaType = column.getJavaType();

                                ColumnModel cell = new ColumnModel();
                                cell.setColumnName(column.getColumnName());
                                cell.setType(javaType);

                                if ("String".equals(javaType)) {
                                    cell.setStringValue(ParamUtils.getString(dataMap, key));
                                    cell.setValue(cell.getStringValue());
                                } else if ("Integer".equals(javaType)) {
                                    cell.setIntValue(ParamUtils.getInt(dataMap, key));
                                    cell.setValue(cell.getIntValue());
                                } else if ("Long".equals(javaType)) {
                                    cell.setLongValue(ParamUtils.getLong(dataMap, key));
                                    cell.setValue(cell.getLongValue());
                                } else if ("Double".equals(javaType)) {
                                    cell.setDoubleValue(ParamUtils.getDouble(dataMap, key));
                                    cell.setValue(cell.getDoubleValue());
                                } else if ("Date".equals(javaType)) {
                                    cell.setDateValue(ParamUtils.getDate(dataMap, key));
                                    cell.setValue(cell.getDateValue());
                                } else {
                                    cell.setValue(value);
                                }

                                cellModelList.add(cell);
                                cols.add(cell.getColumnName());
                            }

                            /**
                             * ??
                             */
                            if (sb.toString().endsWith("_")) {
                                sb.delete(sb.length() - 1, sb.length());
                                String rowKey = sb.toString();
                                logger.debug("rowKey=" + rowKey);
                                TableModel rowModel = resultMap.get(rowKey);
                                if (rowModel == null) {
                                    rowModel = new TableModel();
                                    ColumnModel cell01 = new ColumnModel();
                                    cell01.setColumnName("ID");
                                    cell01.setType("String");
                                    cell01.setValueExpression(ExpressionConstants.ID_EXPRESSION);
                                    cols.add("ID");
                                    rowModel.addColumn(cell01);
                                    rowModel.setIdColumn(cell01);

                                    ColumnModel cell04 = new ColumnModel();
                                    cell04.setColumnName("AGGREGATIONKEY");
                                    cell04.setType("String");
                                    cols.add("AGGREGATIONKEY");
                                    rowModel.addColumn(cell04);

                                    resultMap.put(rowKey, rowModel);
                                }

                                for (ColumnModel cell : cellModelList) {
                                    /**
                                     * ??
                                     */
                                    if (columnMap.get(cell.getColumnName().toLowerCase()) != null) {
                                        rowModel.addColumn(cell);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                throw new RuntimeException(ex);
            } finally {
                Environment.setCurrentSystemName(systemName);
            }
        }

        TableModel rowModel = new TableModel();
        rowModel.setTableName(tableName);
        rowModel.setAggregationKey(tableDefinition.getAggregationKeys());

        ColumnModel cell01 = new ColumnModel();
        cell01.setColumnName("ID");
        cell01.setType("String");
        cell01.setValueExpression(ExpressionConstants.ID_EXPRESSION);
        rowModel.addColumn(cell01);
        rowModel.setIdColumn(cell01);

        ColumnModel cell04 = new ColumnModel();
        cell04.setColumnName("AGGREGATIONKEY");
        cell04.setType("String");
        rowModel.addColumn(cell04);

        for (ColumnDefinition column : columns) {
            ColumnModel cell = new ColumnModel();
            cell.setColumnName(column.getColumnName());
            cell.setType(column.getJavaType());
            rowModel.addColumn(cell);
        }

        Collection<TableModel> rows = resultMap.values();
        logger.debug("fetch data list size:" + rows.size());
        if (rows.size() > 0) {
            String seqNo = rowModel.getTableName() + "-" + DateUtils.getDateTime(new Date());
            getTableDataService().saveAll(rowModel.getTableName(), seqNo, rows);
        }
    }
}

From source file:org.sakaiproject.tool.messageforums.PrivateMessagesTool.java

/**
 * navigate to "Reply to all" a private message
 * @return - pvtMsgForward// w  w  w  .jav  a  2s .c  o m
 */
public String processPvtMsgReplyAll() {
    LOG.debug("processPvtMsgReplyAll()");

    setDetailMsgCount = 0;

    if (getDetailMsg() == null)
        return null;

    PrivateMessage pm = getDetailMsg().getMsg();

    // To mark as replied when user send the reply
    this.setReplyingMessage(pm);

    String title = pm.getTitle();
    if (title != null && !title.startsWith(getResourceBundleString(ReplyAll_SUBJECT_PREFIX)))
        forwardSubject = getResourceBundleString(ReplyAll_SUBJECT_PREFIX) + ' ' + title;
    else
        forwardSubject = title;//forwardSubject

    // format the created date according to the setting in the bundle
    SimpleDateFormat formatter = new SimpleDateFormat(getResourceBundleString("date_format"),
            new ResourceLoader().getLocale());
    formatter.setTimeZone(TimeService.getLocalTimeZone());
    String formattedCreateDate = formatter.format(pm.getCreated());

    SimpleDateFormat formatter_date_time = new SimpleDateFormat(getResourceBundleString("date_format_time"),
            new ResourceLoader().getLocale());
    formatter_date_time.setTimeZone(TimeService.getLocalTimeZone());
    String formattedCreateTime = formatter_date_time.format(pm.getCreated());

    StringBuilder replyallText = new StringBuilder();

    // populate replyToBody with the reply text
    replyallText.append("<br /><br />");
    replyallText.append("<span style=\"font-weight:bold;font-style:italic;\">");
    replyallText.append(getResourceBundleString("pvt_msg_on"));
    replyallText.append(" " + formattedCreateDate + " ");
    replyallText.append(getResourceBundleString("pvt_msg_at"));
    replyallText.append(" " + formattedCreateTime);
    replyallText.append(getResourceBundleString("pvt_msg_comma"));
    replyallText.append(" " + pm.getAuthor() + " ");
    replyallText.append(getResourceBundleString("pvt_msg_wrote"));
    replyallText.append("</span>");

    String origBody = pm.getBody();
    if (origBody != null && origBody.trim().length() > 0) {
        replyallText.append("<br />" + pm.getBody() + "<br />");
    }

    List attachList = getDetailMsg().getAttachList();
    if (attachList != null && attachList.size() > 0) {
        for (Iterator attachIter = attachList.iterator(); attachIter.hasNext();) {
            DecoratedAttachment decoAttach = (DecoratedAttachment) attachIter.next();
            if (decoAttach != null) {
                replyallText.append("<span style=\"font-style:italic;\">");
                replyallText.append(getResourceBundleString("pvt_msg_["));
                replyallText.append(decoAttach.getAttachment().getAttachmentName());
                replyallText.append(getResourceBundleString("pvt_msg_]") + "  ");
                replyallText.append("</span>");
            }
        }
    }

    this.setForwardBody(replyallText.toString());

    String msgautherString = getDetailMsg().getAuthor();
    String msgCClistString = getDetailMsg().getRecipientsAsText();

    //remove the auther in Cc string        
    if (msgCClistString.length() >= msgautherString.length()) {
        String msgCClistStringwithoutAuthor = msgCClistString;

        String currentUserasAuther = getUserName();
        char letter = ';';
        int n = getNum(letter, msgCClistStringwithoutAuthor);

        int numberofAuther = 0;

        if (n == 0) {
            numberofAuther = 1;
        } else if (n >= 1) {
            numberofAuther = n + 1;
        } //add the end ";"
        String[] ccSS = new String[numberofAuther];
        ccSS = msgCClistStringwithoutAuthor.split(";");

        StringBuffer tmpCC = new StringBuffer("");

        if ((numberofAuther > 0) && (numberofAuther <= msgCClistStringwithoutAuthor.length())) {

            for (int indexCC = 0; indexCC < numberofAuther; indexCC++) //last for ";"   
            {

                if (!currentUserasAuther.replaceAll(" ", ", ").equals(msgautherString)) {

                    if (!ccSS[indexCC].trim().equals(currentUserasAuther.replaceAll(" ", ", "))
                            && (!ccSS[indexCC].trim().equals(msgautherString)))//not equal current auther and not equal old auther
                    {
                        tmpCC.append(ccSS[indexCC].trim()).append("; ");

                    }
                }

                else if (currentUserasAuther.replaceAll(" ", ", ").equals(msgautherString)) {

                    if (!ccSS[indexCC].trim().equals(currentUserasAuther.replaceAll(" ", ", "))
                            || (!ccSS[indexCC].trim().equals(msgautherString)))//not equal current auther and not equal old auther
                    {
                        tmpCC.append(ccSS[indexCC].trim()).append("; ");

                    }

                }

            }

            if (tmpCC.length() > 1) {
                tmpCC.delete(tmpCC.length() - 2, tmpCC.length());//remove the ";"
            }

            getDetailMsg().setSendToStringDecorated(tmpCC.toString());
            getDetailMsg().getMsg().setRecipientsAsText(tmpCC.toString());

        }

    }

    //remove the bcc undiclosed place holder:
    String ccList = getDetailMsg().getMsg().getRecipientsAsText();
    if (ccList.contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED) + "; ")) {
        ccList = ccList.replaceAll(getResourceBundleString(RECIPIENTS_UNDISCLOSED) + "; ", "");
    } else if (ccList.contains(getResourceBundleString(RECIPIENTS_UNDISCLOSED))) {
        ccList = ccList.replaceAll(getResourceBundleString(RECIPIENTS_UNDISCLOSED), "");
    }
    if (ccList.endsWith(" ")) {
        ccList = ccList.substring(0, ccList.length() - 1);
    }
    if (ccList.endsWith(";")) {
        ccList = ccList.substring(0, ccList.length() - 1);
    }
    getDetailMsg().getMsg().setRecipientsAsText(ccList);

    this.setDetailMsg(getDetailMsg());

    setDetailMsgCount++;

    return MESSAGE_ReplyAll_PG;//MESSAGE_FORWARD_PG;
}