Example usage for java.lang ClassCastException getMessage

List of usage examples for java.lang ClassCastException getMessage

Introduction

In this page you can find the example usage for java.lang ClassCastException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.webguitoolkit.ui.util.export.ExcelTableExport.java

/**
 * @param table//w  w  w  .  ja  v a2s  . com
 * @param sheet
 * @param footer
 * @param header
 * @param headline
 * @return
 */
public HSSFSheet excelExport(Table table, HSSFSheet sheet) {
    HSSFRow row;
    HSSFCell cell;
    TableExportOptions exportOptions = table.getExportOptions();
    boolean showOnlyDisplayed = exportOptions.isShowOnlyDisplayedColumns();
    List<ITableColumn> columns = getTableColumns(showOnlyDisplayed, table);

    int colNr = columns.size();
    // first we add the headers
    int rownr = 0;

    if (StringUtils.isNotBlank(exportOptions.getHeadline())) {
        row = sheet.createRow(rownr);
        if (getExcelheadstyle() != null) {
            getExcelheadstyle().setWrapText(true);
        }

        double divider = 2;
        double putcol = Math.floor(colNr / divider) - 1;
        short shortCol = (short) putcol;
        cell = row.createCell(shortCol);
        if (getExcelheadstyle() != null) {
            cell.setCellStyle(getExcelheadstyle());
        }
        cell.setCellValue(new HSSFRichTextString(exportOptions.getHeadline()));

        rownr++;
        row = sheet.createRow(rownr);
        cell = row.createCell((short) 0);
        cell.setCellValue(new HSSFRichTextString(""));
        rownr++;
    }

    if (StringUtils.isNotBlank(exportOptions.getTableHeadline())) {
        row = sheet.createRow(rownr);
        getExcelheadstyle().setWrapText(true);
        cell = row.createCell((short) 0);
        cell.setCellValue(new HSSFRichTextString(exportOptions.getTableHeadline()));
        if (getExcelContentstyle() != null) {
            cell.setCellStyle(getExcelContentstyle());
        }
        rownr++;
    }

    row = sheet.createRow(rownr);
    for (int i = 0; i < columns.size(); i++) {
        cell = row.createCell((short) i);
        // remove html linebreaks from headline
        String tableTitle = TextService.getString(columns.get(i).getTitle());
        if (tableTitle.contains("<br/>") || tableTitle.contains("<br>")) {
            tableTitle = tableTitle.replaceAll("<br/>", " ");
            tableTitle = tableTitle.replaceAll("<br>", " ");
        }
        cell.setCellValue(new HSSFRichTextString(tableTitle));
        if (getExcelheadstyle() != null) {
            cell.setCellStyle(getExcelheadstyle());
        }
    }
    rownr++;
    List tabledata = table.getDefaultModel().getFilteredList();
    for (Iterator it = tabledata.iterator(); it.hasNext();) {
        row = sheet.createRow(rownr);
        DataBag dbag = (DataBag) it.next();
        for (int i = 0; i < columns.size(); i++) {
            logger.debug("property: " + columns.get(i).getProperty());
            IColumnRenderer renderer = columns.get(i).getRenderer();
            IConverter converter = columns.get(i).getConverter();
            Object obj = null;
            if (renderer != null && renderer instanceof ImageColumnRenderer) {
                // load image title, if available
                obj = dbag.get(columns.get(i).getProperty() + ".title");
            } else if (renderer != null && renderer instanceof CollectionToStringRenderer) {
                String objString = "";
                try {
                    ArrayList<String> listOfStrings = (ArrayList<String>) dbag
                            .get(columns.get(i).getProperty());
                    for (String string : listOfStrings) {
                        objString += string + ", ";
                    }
                } catch (ClassCastException e) { // ignore
                }

                // remove comma and blank from end of the string
                objString = StringUtils.removeEnd(objString, ", ");

                obj = objString;
            } else if (renderer != null && renderer instanceof PlainHtmlColumnRenderer) {
                obj = dbag.get(columns.get(i).getProperty() + ".title");
            } else {
                obj = dbag.get(columns.get(i).getProperty());
            }

            if (obj != null) {
                cell = row.createCell((short) i);
                try {
                    if (obj instanceof String) {
                        writeStringCell(cell, converter, obj, dbag);
                    } else if (obj instanceof Number) {
                        writeNumberCell(cell, converter, obj, dbag);
                    } else if (obj instanceof Date || obj instanceof java.sql.Date
                            || obj instanceof Timestamp) {
                        writeDateCell(cell, converter, obj, dbag);
                    } else {
                        wirteObjectCell(cell, converter, obj, dbag);
                    }
                } catch (Exception e) {
                    logger.error("row = " + rownr + ", column = " + i + ", error " + e.getMessage(), e);
                    cell.setCellValue(new HSSFRichTextString(""));
                }
            }
        }
        rownr++;
    }

    if (StringUtils.isNotBlank(exportOptions.getTableFooter())) {
        row = sheet.createRow(rownr);
        cell = row.createCell((short) 0);
        cell.setCellValue(new HSSFRichTextString(""));
        rownr++;
        row = sheet.createRow(rownr);
        getExcelheadstyle().setWrapText(true);
        cell = row.createCell((short) 0);

        cell.setCellValue(new HSSFRichTextString(exportOptions.getTableFooter()));
        if (getExcelContentstyle() != null) {
            cell.setCellStyle(getExcelContentstyle());
        }
    }
    return sheet;
}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

/**
 * MUST be overridden/*  w w w .  java 2  s .co m*/
 */
protected <T> boolean baseDelete(Class<T> type, Serializable id) {
    String idColumn = getIdColumn(type);
    String sql = makeSQL(getDeleteTemplate(type), getTableNameFromClass(type), StatementMapper.WHERE,
            "where " + idColumn + " = ?");
    // convert the type if needed
    try {
        id = (Serializable) convertColumn(type, idColumn, id);
    } catch (ClassCastException e) {
        throw new IllegalArgumentException(
                "all ids must be Serializable, change the property type defined in the names record for the id to be a Serializable type: "
                        + e.getMessage(),
                e);
    }
    Object[] params = new Object[] { id };
    if (showSQL) {
        logInfo("SQL=" + sql + ":\n Params=" + ArrayUtils.arrayToString(params));
    }
    int rows = getSpringJdbcTemplate().update(sql, params);
    return rows > 0;
}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

/**
 * MUST be overridden//  w  w w . j  a  va2  s .  c o  m
 */
@SuppressWarnings("unchecked")
protected <T> T baseFindById(Class<T> type, Serializable id) {
    String idColumn = getIdColumn(type);
    String sql = makeSQL(getSelectTemplate(type), getTableNameFromClass(type), StatementMapper.WHERE,
            "where " + getIdColumn(type) + " = ?");
    T entity = null;
    try {
        // convert the type if needed
        try {
            id = (Serializable) convertColumn(type, idColumn, id);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "all ids must be Serializable, change the property type defined in the names record for the id to be a Serializable type: "
                            + e.getMessage(),
                    e);
        }
        // get the map of values
        Object[] params = new Object[] { id };
        if (showSQL) {
            logInfo("SQL=" + sql + ":\n Params=" + ArrayUtils.arrayToString(params));
        }
        Map<String, Object> data = getSpringJdbcTemplate().queryForMap(sql, params);
        entity = makeEntityFromMap(type, data);
    } catch (IncorrectResultSizeDataAccessException e) {
        entity = null;
    }

    return entity;
}

From source file:org.fosstrak.epcis.repository.query.QueryOperationsModule.java

/**
 * Create an SQL query string from the given query parameters.
 * <p>/*  w w w  .j  av a  2s. c o  m*/
 * Note: the CXF framework always returns an instance of org.w3c.dom.Element
 * for the query parameter value given in the <code>queryParams</code>
 * argument, because the spec defines this value to be of type
 * <code>anyType</code>. CXF <i>does not</i> resolve the type of the
 * query parameter value from the query name as Axis does! However, if the
 * user specifies the XML type in the request, then CXF returns an instance
 * of the corresponding type.
 * <p>
 * Consider the following example of a query parameter:
 * 
 * <pre>
 * &lt;param&gt;
 *   &lt;name&gt;GE_eventTime&lt;/name&gt;
 *   &lt;value&gt;2007-07-07T07:07:07+02:00&lt;/value&gt;
 * &lt;/param&gt;
 * </pre>
 * 
 * For the query parameter value, CXF will return an instance of
 * org.w3c.dom.Element containing the text value
 * "2007-07-07T07:07:07+02:00". However, if the user provides the following
 * instead, CXF will return an instance of
 * javax.xml.datatype.XMLGregorianCalendar.
 * 
 * <pre>
 * &lt;param&gt;
 *   &lt;name&gt;GE_eventTime&lt;/name&gt;
 *   &lt;value
 *       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 *       xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;
 *       xsi:type=&quot;xs:dateTime&quot;&gt;
 *     2007-07-07T07:07:07+02:00
 *   &lt;/value&gt;
 * &lt;/param&gt;
 * </pre>
 * 
 * As a consequence, we always first need to check if the value is an
 * instance of Element, and if so, we need to parse it manually according to
 * the semantics of the parameter name.
 * 
 * @param queryParams
 *            The query parameters.
 * @param eventType
 *            Has to be one of the four basic event types "ObjectEvent",
 *            "AggregationEvent", "QuantityEvent", "TransactionEvent".
 * @return The prepared sql statement.
 * @throws SQLException
 *             Whenever something goes wrong when querying the db.
 * @throws QueryParameterException
 *             If one of the given QueryParam is invalid.
 * @throws ImplementationException
 *             If an error in the implementation occurred.
 */
private List<SimpleEventQueryDTO> constructSimpleEventQueries(final QueryParams queryParams)
        throws SQLException, QueryParameterExceptionResponse {
    SimpleEventQueryDTO aggrEventQuery = new SimpleEventQueryDTO(EpcisConstants.AGGREGATION_EVENT);
    SimpleEventQueryDTO objEventQuery = new SimpleEventQueryDTO(EpcisConstants.OBJECT_EVENT);
    SimpleEventQueryDTO quantEventQuery = new SimpleEventQueryDTO(EpcisConstants.QUANTITY_EVENT);
    SimpleEventQueryDTO transEventQuery = new SimpleEventQueryDTO(EpcisConstants.TRANSACTION_EVENT);

    boolean includeAggrEvents = true;
    boolean includeObjEvents = true;
    boolean includeQuantEvents = true;
    boolean includeTransEvents = true;

    String orderBy = null;
    OrderDirection orderDirection = null;
    int eventCountLimit = -1;
    int maxEventCount = -1;

    // a sorted List of query parameter names - keeps track of the processed
    // names in order to cope with duplicates
    List<String> sortedParamNames = new ArrayList<String>();

    int nofEventFieldExtensions = 0;
    for (QueryParam param : queryParams.getParam()) {
        String paramName = param.getName();
        Object paramValue = param.getValue();

        // check for null values
        if (paramName == null || "".equals(paramName)) {
            String msg = "Missing name for a query parameter";
            throw queryParameterException(msg, null);
        }
        if (paramValue == null) {
            String msg = "Missing value for query parameter '" + paramName + "'";
            throw queryParameterException(msg, null);
        }
        // check if the current query parameter has already been provided
        int index = Collections.binarySearch(sortedParamNames, paramName);
        if (index < 0) {
            // we have not yet seen this query parameter name - ok
            sortedParamNames.add(-index - 1, paramName);
        } else {
            // we have already handled this query parameter name - not ok
            String msg = "Query parameter '" + paramName + "' provided more than once";
            throw queryParameterException(msg, null);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Handling query parameter: " + paramName);
        }
        try {
            if (paramName.equals("eventType")) {
                // by default all event types will be included
                List<String> eventTypes = parseAsArrayOfString(paramValue).getString();
                if (!eventTypes.isEmpty()) {
                    // check if valid event types are provided
                    checkEventTypes(eventTypes);

                    // check for excluded event types
                    if (!eventTypes.contains(EpcisConstants.AGGREGATION_EVENT)) {
                        includeAggrEvents = false;
                    }
                    if (!eventTypes.contains(EpcisConstants.OBJECT_EVENT)) {
                        includeObjEvents = false;
                    }
                    if (!eventTypes.contains(EpcisConstants.QUANTITY_EVENT)) {
                        includeQuantEvents = false;
                    }
                    if (!eventTypes.contains(EpcisConstants.TRANSACTION_EVENT)) {
                        includeTransEvents = false;
                    }
                }
            } else if (paramName.equals("GE_eventTime") || paramName.equals("LT_eventTime")
                    || paramName.equals("GE_recordTime") || paramName.equals("LT_recordTime")) {
                Calendar cal = parseAsCalendar(paramValue, paramName);
                Operation op = Operation.valueOf(paramName.substring(0, 2));
                String eventField = paramName.substring(3, paramName.length()) + "Ms";
                aggrEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis());
                objEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis());
                quantEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis());
                transEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis());

            } else if (paramName.equals("EQ_action")) {
                // QuantityEvents have no "action" field, thus exclude them
                includeQuantEvents = false;
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    checkActionValues(aos.getString());
                    aggrEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString());
                    objEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString());
                    transEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString());
                }

            } else if (paramName.equals("EQ_bizStep") || paramName.equals("EQ_disposition")
                    || paramName.equals("EQ_readPoint") || paramName.equals("EQ_bizLocation")) {
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    String eventField = paramName.substring(3, paramName.length());
                    aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                    objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                    quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                    transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                }

            } else if (paramName.equals("WD_readPoint") || paramName.equals("WD_bizLocation")) {
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    // append a "*" to each of the parameter values - this
                    // should implement the semantics of "With Descendant"
                    // TODO: should???
                    CollectionUtils.transform(aos.getString(), new StringTransformer());
                    String eventField = paramName.substring(3, paramName.length());
                    aggrEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString());
                    objEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString());
                    quantEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString());
                    transEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString());
                }

            } else if (paramName.startsWith("EQ_bizTransaction_")) {
                // type extracted from parameter name
                String bizTransType = paramName.substring(18);
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    aggrEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType);
                    objEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType);
                    quantEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType);
                    transEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType);
                    aggrEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString());
                    objEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString());
                    quantEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString());
                    transEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString());
                }

            } else if (paramName.equals("MATCH_epc") || paramName.equals("MATCH_anyEPC")) {
                // QuantityEvents have no field for EPCs, thus exclude them
                includeQuantEvents = false;
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    aggrEventQuery.addEventQueryParam("childEPCs", Operation.MATCH, aos.getString());
                    objEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString());
                    transEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString());
                    if (paramName.equals("MATCH_anyEPC")) {
                        // AggregationEvent and TransactionEvent need
                        // special treatment ("parentID" field)
                        aggrEventQuery.setIsAnyEpc(true);
                        transEventQuery.setIsAnyEpc(true);
                    }
                }

            } else if (paramName.equals("MATCH_parentID")) {
                includeQuantEvents = false;
                includeObjEvents = false;
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    aggrEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString());
                    transEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString());
                }

            } else if (paramName.equals("MATCH_epcClass")) {
                includeAggrEvents = false;
                includeObjEvents = false;
                includeTransEvents = false;
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                if (!aos.getString().isEmpty()) {
                    quantEventQuery.addEventQueryParam("epcClass", Operation.MATCH, aos.getString());
                }

            } else if (paramName.endsWith("_quantity")) {
                includeAggrEvents = false;
                includeObjEvents = false;
                includeTransEvents = false;
                Operation op = Operation.valueOf(paramName.substring(0, paramName.indexOf('_')));
                quantEventQuery.addEventQueryParam("quantity", op, parseAsInteger(paramValue));

            } else if (paramName.startsWith("GT_") || paramName.startsWith("GE_") || paramName.startsWith("EQ_")
                    || paramName.startsWith("LE_") || paramName.startsWith("LT_")) {
                // must be an event field extension
                String fieldname = paramName.substring(3);
                String[] parts = fieldname.split("#");
                if (parts.length != 2) {
                    String msg = "Invalid parameter " + paramName;
                    throw queryParameterException(msg, null);
                }
                nofEventFieldExtensions++;
                String eventFieldExtBase = "extension" + nofEventFieldExtensions;
                EventQueryParam queryParam = parseExtensionField(eventFieldExtBase, paramName, paramValue);
                aggrEventQuery.addEventQueryParam(queryParam);
                objEventQuery.addEventQueryParam(queryParam);
                quantEventQuery.addEventQueryParam(queryParam);
                transEventQuery.addEventQueryParam(queryParam);
                String eventFieldExt = eventFieldExtBase + ".fieldname";
                aggrEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                objEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                quantEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                transEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);

            } else if (paramName.startsWith("EXISTS_")) {
                String fieldname = paramName.substring(7);
                if (fieldname.equals("childEPCs")) {
                    includeObjEvents = false;
                    includeQuantEvents = false;
                    includeTransEvents = false;
                    aggrEventQuery.addEventQueryParam("childEPCs", Operation.EXISTS, null);
                } else if (fieldname.equals("epcList")) {
                    includeAggrEvents = false;
                    includeQuantEvents = false;
                    objEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null);
                    transEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null);
                } else if (fieldname.equals("action")) {
                    includeQuantEvents = false;
                    aggrEventQuery.addEventQueryParam("action", Operation.EXISTS, null);
                    objEventQuery.addEventQueryParam("action", Operation.EXISTS, null);
                    transEventQuery.addEventQueryParam("action", Operation.EXISTS, null);
                } else if (fieldname.equals("parentID")) {
                    includeObjEvents = false;
                    includeQuantEvents = false;
                    aggrEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null);
                    transEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null);
                } else if (fieldname.equals("quantity") || fieldname.equals("epcClass")) {
                    includeAggrEvents = false;
                    includeObjEvents = false;
                    includeTransEvents = false;
                    quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null);
                } else if (fieldname.equals("eventTime") || fieldname.equals("recordTime")
                        || fieldname.equals("eventTimeZoneOffset") || fieldname.equals("bizStep")
                        || fieldname.equals("disposition") || fieldname.equals("readPoint")
                        || fieldname.equals("bizLocation") || fieldname.equals("bizTransList")) {
                    aggrEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null);
                    objEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null);
                    quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null);
                    transEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null);
                } else {
                    // lets see if we have an extension fieldname
                    String[] parts = fieldname.split("#");
                    if (parts.length != 2) {
                        String msg = "Invalid parameter " + paramName;
                        throw queryParameterException(msg, null);
                    }
                    nofEventFieldExtensions++;
                    String eventFieldExt = "extension" + nofEventFieldExtensions + ".fieldname";
                    aggrEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                    objEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                    quantEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                    transEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname);
                }

            } else if (paramName.startsWith("HASATTR_")) {
                // restrict by attribute name
                String fieldname = paramName.substring(8);
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                String eventField = fieldname + ".attribute";
                aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());

            } else if (paramName.startsWith("EQATTR_")) {
                String fieldname = paramName.substring(7);
                String attrname = null;
                String[] parts = fieldname.split("_");
                if (parts.length > 2) {
                    String msg = "Query parameter has invalid format: " + paramName
                            + ". Expected: EQATTR_fieldname_attrname";
                    throw queryParameterException(msg, null);
                } else if (parts.length == 2) {
                    fieldname = parts[0];
                    attrname = parts[1];
                }
                // restrict by attribute name
                String eventField = fieldname + ".attribute";
                aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname);
                objEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname);
                quantEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname);
                transEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname);
                // restrict by attribute value
                ArrayOfString aos = parseAsArrayOfString(paramValue);
                eventField = eventField + ".value";
                aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());
                transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString());

            } else if (paramName.equals("orderBy")) {
                orderBy = parseAsString(paramValue);
                if (!"eventTime".equals(orderBy) && !"recordTime".equals(orderBy)
                        && !"quantity".equals(orderBy)) {
                    String[] parts = orderBy.split("#");
                    if (parts.length != 2) {
                        String msg = "orderBy must be one of eventTime, recordTime, quantity, or an extension field";
                        throw queryParameterException(msg, null);
                    }
                }

            } else if (paramName.equals("orderDirection")) {
                orderDirection = OrderDirection.valueOf(parseAsString(paramValue));

            } else if (paramName.equals("eventCountLimit")) {
                eventCountLimit = parseAsInteger(paramValue).intValue();

            } else if (paramName.equals("maxEventCount")) {
                maxEventCount = parseAsInteger(paramValue).intValue();

            } else {
                String msg = "Unknown query parameter: " + paramName;
                throw queryParameterException(msg, null);
            }
        } catch (ClassCastException e) {
            String msg = "Type of value invalid for query parameter '" + paramName + "': " + paramValue;
            throw queryParameterException(msg, e);
        } catch (IllegalArgumentException e) {
            String msg = "Unparseable value for query parameter '" + paramName + "'. " + e.getMessage();
            throw queryParameterException(msg, e);
        }
    }

    // some more user input checks
    if (maxEventCount > -1 && eventCountLimit > -1) {
        String msg = "Paramters 'maxEventCount' and 'eventCountLimit' are mutually exclusive";
        throw queryParameterException(msg, null);
    }
    if (orderBy == null && eventCountLimit > -1) {
        String msg = "'eventCountLimit' may only be used when 'orderBy' is specified";
        throw queryParameterException(msg, null);
    }
    if (orderBy == null && orderDirection != null) {
        String msg = "'orderDirection' may only be used when 'orderBy' is specified";
        throw queryParameterException(msg, null);
    }
    if (orderBy != null) {
        aggrEventQuery.setOrderBy(orderBy);
        objEventQuery.setOrderBy(orderBy);
        quantEventQuery.setOrderBy(orderBy);
        transEventQuery.setOrderBy(orderBy);
        if (orderDirection != null) {
            aggrEventQuery.setOrderDirection(orderDirection);
            objEventQuery.setOrderDirection(orderDirection);
            quantEventQuery.setOrderDirection(orderDirection);
            transEventQuery.setOrderDirection(orderDirection);
        }
    }
    if (eventCountLimit > -1) {
        aggrEventQuery.setLimit(eventCountLimit);
        objEventQuery.setLimit(eventCountLimit);
        quantEventQuery.setLimit(eventCountLimit);
        transEventQuery.setLimit(eventCountLimit);
    }
    if (maxEventCount > -1) {
        aggrEventQuery.setMaxEventCount(maxEventCount);
        objEventQuery.setMaxEventCount(maxEventCount);
        quantEventQuery.setMaxEventCount(maxEventCount);
        transEventQuery.setMaxEventCount(maxEventCount);
    }

    List<SimpleEventQueryDTO> eventQueries = new ArrayList<SimpleEventQueryDTO>(4);
    if (includeAggrEvents) {
        eventQueries.add(aggrEventQuery);
    }
    if (includeObjEvents) {
        eventQueries.add(objEventQuery);
    }
    if (includeQuantEvents) {
        eventQueries.add(quantEventQuery);
    }
    if (includeTransEvents) {
        eventQueries.add(transEventQuery);
    }
    return eventQueries;
}

From source file:org.rifidi.edge.adapter.llrp.LLRPReaderSession.java

/**
 * This logic executes as soon as a socket is established to initialize the
 * connection. It occurs before any commands are scheduled
 *///from  w ww. j a  v  a  2 s  . c  o  m
private void onConnect() {
    logger.info("LLRP Session " + this.getID() + " on sensor " + this.getSensor().getID()
            + " attempting to log in to " + host + ":" + port);
    setStatus(SessionStatus.LOGGINGIN);
    executor = new ScheduledThreadPoolExecutor(1);

    try {
        SET_READER_CONFIG config = createSetReaderConfig();
        config.setMessageID(new UnsignedInteger(messageID++));

        SET_READER_CONFIG_RESPONSE config_response = (SET_READER_CONFIG_RESPONSE) connection.transact(config);

        StatusCode sc = config_response.getLLRPStatus().getStatusCode();
        if (sc.intValue() != StatusCode.M_Success) {
            if (config_response.getLLRPStatus().getStatusCode().toInteger() != 0) {
                try {
                    logger.error("Problem with SET_READER_CONFIG: \n" + config_response.toXMLString());
                } catch (InvalidLLRPMessageException e) {
                    logger.warn("Cannot print XML for " + "SET_READER_CONFIG_RESPONSE");
                }
            }
        }

        // BytesToEnd_HEX data = new BytesToEnd_HEX();
        // CUSTOM_MESSAGE msg = new CUSTOM_MESSAGE();
        // msg.setVendorIdentifier(new UnsignedInteger(25882));
        // msg.setMessageSubtype(new UnsignedByte(21));
        // data.add(new SignedByte(0));
        // data.add(new SignedByte(0));
        // data.add(new SignedByte(0));
        // data.add(new SignedByte(0));
        // msg.setData(data);
        // connection.transact(msg);

        if (!processing.compareAndSet(false, true)) {
            logger.warn("Executor was already active! ");
        }
        this.lastTagTimestamp = System.currentTimeMillis();
        submit(getTimeoutCommand(this), 10, TimeUnit.SECONDS);
        setStatus(SessionStatus.PROCESSING);

    } catch (TimeoutException e) {
        logger.error(e.getMessage());
        disconnect();
    } catch (ClassCastException ex) {
        logger.error(ex.getMessage());
        disconnect();
    }

}

From source file:com.agwego.fuzz.FuzzTester.java

/**
 * Get the test methods converting the JSON representation into FuzzTestCase(s)
 *
 * @param dirName List of JSONObjects containing tests
 * @param prefix Look for files that start like
 * @param suffix Look for files that end in
 * @param testClass the class we're are testing
 * @return the map of the TestCases/* ww w .  j  av a  2s .  c  om*/
 * @throws FuzzTestJsonError - for any semantic errors in the JSON formatted test case
 */
protected Map<String, List<FuzzTestCase>> getTestMethods(String dirName, String prefix, String suffix,
        Class testClass) throws FuzzTestJsonError {
    Map<String, List<FuzzTestCase>> testMethods = new HashMap<String, List<FuzzTestCase>>();
    List<JsonObject> tests = getTests(dirName, prefix, suffix);

    for (JsonObject test : tests) {
        JsonArray only = GsonHelper.getAsArray(test, "only");
        JsonArray testUnits;
        try {
            testUnits = test.getAsJsonArray(TEST_UNIT);
        } catch (ClassCastException ex) {
            throw new FuzzTestJsonError("The \"" + TEST_UNIT + "\" element is not an array, see file = "
                    + test.get(FuzzTester.TEST_FILE));
        }
        if (testUnits == null) {
            throw new FuzzTestJsonError(
                    "The \"" + TEST_UNIT + "\" element is missing check your JSON file, see file = "
                            + test.get(FuzzTester.TEST_FILE));
        } else if (testUnits.size() == 0) {
            throw new FuzzTestJsonError("The \"" + TEST_UNIT + "\" element contains no tests, see file = "
                    + test.get(FuzzTester.TEST_FILE));
        }
        for (JsonElement x : testUnits) {
            JsonObject unitTest = x.getAsJsonObject();
            // TODO add assertion of method_name existence
            boolean skip = GsonHelper.getAsBoolean(unitTest, TEST_SKIP, false);
            JsonArray testCases;
            try {
                testCases = unitTest.getAsJsonArray(TEST_CASES);
            } catch (ClassCastException ex) {
                throw new FuzzTestJsonError("The \"" + TEST_CASES + "\" element is not an array, see file = "
                        + test.get(FuzzTester.TEST_FILE));
            }
            int idx = 1;
            List<FuzzTestCase> fuzzTestCases = new ArrayList<FuzzTestCase>();
            for (JsonElement y : testCases) {
                JsonObject tcj = y.getAsJsonObject();
                tcj.addProperty(TEST_SKIP, skip || !in(unitTest.get(METHOD_NAME).getAsString(), only)
                        || GsonHelper.getAsBoolean(tcj, TEST_SKIP, false));
                FuzzTestCase fuzzTestCase;
                try {
                    fuzzTestCase = FuzzTestCase.deserialize(tcj, idx, unitTest.get(METHOD_NAME).getAsString(),
                            testClass);
                } catch (FuzzTestJsonError ex) {
                    throw new FuzzTestJsonError(
                            ex.getMessage() + ", see file: " + test.get(FuzzTester.TEST_FILE), ex);
                }
                fuzzTestCases.add(fuzzTestCase);
                idx++;
            }
            if (testMethods.containsKey(unitTest.get(METHOD_NAME).getAsString()))
                testMethods.get(unitTest.get(METHOD_NAME).getAsString()).addAll(fuzzTestCases);
            else
                testMethods.put(unitTest.get(METHOD_NAME).getAsString(), fuzzTestCases);
        }
    }

    return testMethods;
}

From source file:org.egov.egf.commons.EgovCommon.java

public EntityType getEntityType(final Accountdetailtype accountdetailtype, final Serializable detailkey)
        throws ApplicationException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("EgovCommon | getEntityType| Start");
    EntityType entity = null;/*from  ww w  .  j  a va 2  s . c  om*/
    try {
        final Class aClass = Class.forName(accountdetailtype.getFullQualifiedName());
        final java.lang.reflect.Method method = aClass.getMethod("getId");
        final String dataType = method.getReturnType().getSimpleName();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("data Type = " + dataType);
        if (dataType.equals("Long"))
            entity = (EntityType) persistenceService.getSession().load(aClass,
                    Long.valueOf(detailkey.toString()));
        else
            entity = (EntityType) persistenceService.getSession().load(aClass, detailkey);

    } catch (final ClassCastException e) {
        LOGGER.error(e);
        throw new ApplicationException(e.getMessage());
    } catch (final Exception e) {
        LOGGER.error("Exception to get EntityType=" + e.getMessage(), e);
        throw new ApplicationException(e.getMessage());
    }
    return entity;
}

From source file:org.openmrs.module.rheapocadapter.impl.HL7MessageTransformer.java

public Message processMessage(Message message) throws ApplicationException {

    if (message instanceof ORU_R01) {

        try {/*from  www . j a  v  a 2s  .c  o m*/
            ORU_R01 oru = (ORU_R01) message;
            return oru;
        } catch (ClassCastException e) {
            log.error("Error casting " + message.getClass().getName() + " to ORU_R01", e);
            throw new ApplicationException("Invalid message type for handler");
        }

    } else if (message instanceof ADT_A05) {
        try {
            ADT_A05 adt = (ADT_A05) message;
            log.info("ADT Message");
            return adt;

        } catch (ClassCastException e) {
            log.error("Error casting " + message.getClass().getName() + " to ADT_A05 : " + e.getMessage());
            throw new ApplicationException("Invalid message type for handler");
        }

    } else {
        throw new ApplicationException("Invalid message sent to ORU_R01/ADT_A05 handler");
    }
}

From source file:com.collabnet.ccf.core.recovery.HospitalArtifactReplayer.java

@SuppressWarnings("deprecation")
private void loadBeanDefinitionsFromUrl(String url, GenericApplicationContext context) {
    BeanDefinitionReader reader = null;/*ww  w  .ja  v  a  2s  . c  o  m*/
    if (url.endsWith(".xml")) {
        reader = new XmlBeanDefinitionReader(context);
    } else if (url.endsWith(".properties")) {
        reader = new PropertiesBeanDefinitionReader(context);
    }

    if (reader != null) {
        try {
            UrlResource urlResource = new UrlResource(url);
            InputStream is = urlResource.getInputStream();
            Document document = builder.parse(is);
            Element routerElement = this.getRouterElement(document);
            this.stripOffProcessors(routerElement);
            this.addGAImportComponents(document, routerElement);
            DOMImplementationRegistry registry = null;
            try {
                registry = DOMImplementationRegistry.newInstance();
            } catch (ClassCastException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (ClassNotFoundException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (InstantiationException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            } catch (IllegalAccessException e) {
                log.error("error", e);
                throw new CCFRuntimeException("error", e);
            }
            String originalConfigFileAbsolutePath = urlResource.getFile().getAbsolutePath();
            String componentName = entry.getSourceComponent();
            String configComponentIdentifier = "{" + originalConfigFileAbsolutePath + "}" + componentName;

            File outputFile = null;
            if (componentConfigFileMap.containsKey(configComponentIdentifier)) {
                outputFile = componentConfigFileMap.get(configComponentIdentifier);
            } else {
                outputFile = File.createTempFile(componentName, ".xml", replayWorkDir);
                DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
                LSSerializer writer = impl.createLSSerializer();
                LSOutput output = impl.createLSOutput();
                FileOutputStream bas = new FileOutputStream(outputFile.getAbsolutePath());
                output.setByteStream(bas);
                writer.write(document, output);
                bas.flush();
                bas.close();
                componentConfigFileMap.put(configComponentIdentifier, outputFile);
            }

            // FIXME Use of deprecated method
            UrlResource newUrlResource = new UrlResource(outputFile.toURL().toString());
            ((XmlBeanDefinitionReader) reader).registerBeanDefinitions(document, newUrlResource);
        } catch (BeansException e) {
            log.error("error", e);
            throw new RuntimeException("BeansException : " + e.getMessage(), e);
        } catch (MalformedURLException e) {
            log.error("error", e);
            throw new RuntimeException("MalformedUrlException : " + e.getMessage(), e);
        } catch (IOException e) {
            log.error("error", e);
            throw new RuntimeException("IOExceptionException : " + e.getMessage(), e);
        } catch (SAXException e) {
            log.error("error", e);
            throw new RuntimeException("SAXException : " + e.getMessage(), e);
        }
    } else {
        throw new RuntimeException("No BeanDefinitionReader associated with " + url);
    }
}