Search in sources :

Example 11 with SienaException

use of siena.SienaException in project siena by mandubian.

the class SdbNativeSerializer method embed.

public static void embed(ReplaceableItem item, String embeddingColumnName, Object embeddedObj) {
    Class<?> clazz = embeddedObj.getClass();
    if (clazz.isArray() || Collection.class.isAssignableFrom(clazz)) {
        throw new SienaException("can't serializer Array/Collection in native mode");
    }
    for (Field f : ClassInfo.getClassInfo(clazz).updateFields) {
        String propValue = SdbMappingUtils.objectFieldToString(embeddedObj, f);
        if (propValue != null) {
            ReplaceableAttribute attr = new ReplaceableAttribute(getEmbeddedAttributeName(embeddingColumnName, f), propValue, true);
            item.withAttributes(attr);
        } else {
            if (ClassInfo.isEmbeddedNative(f)) {
                SdbNativeSerializer.embed(item, getEmbeddedAttributeName(embeddingColumnName, f), Util.readField(embeddedObj, f));
            }
        }
    }
}
Also used : Field(java.lang.reflect.Field) Collection(java.util.Collection) SienaException(siena.SienaException) ReplaceableAttribute(com.amazonaws.services.simpledb.model.ReplaceableAttribute)

Example 12 with SienaException

use of siena.SienaException in project siena by mandubian.

the class SdbMappingUtils method previousPage.

public static <T> void previousPage(QueryData<T> query) {
    QueryOptionPage pag = (QueryOptionPage) query.option(QueryOptionPage.ID);
    QueryOptionState state = (QueryOptionState) query.option(QueryOptionState.ID);
    QueryOptionSdbContext sdbCtx = (QueryOptionSdbContext) query.option(QueryOptionSdbContext.ID);
    if (sdbCtx == null) {
        sdbCtx = new QueryOptionSdbContext();
        query.options().put(sdbCtx.type, sdbCtx);
    }
    // if no more data before, doesn't try to go before
    if (sdbCtx.noMoreDataBefore) {
        return;
    }
    // if no more data after, removes flag to be able to go before
    if (sdbCtx.noMoreDataAfter) {
        // here the realoffset is not at the end of current pages
        // but at the beginning of the last page
        // so need to fake that we are at the end of the last page
        sdbCtx.realOffset += pag.pageSize;
        sdbCtx.noMoreDataAfter = false;
    }
    if (pag.isPaginating()) {
        if (sdbCtx.hasToken()) {
            // if tokenIdx is 0, it means at first page after beginning
            if (sdbCtx.tokenIdx == 0) {
                sdbCtx.previousToken();
                // follows the real offset
                sdbCtx.realOffset -= pag.pageSize;
                // uses offset
                if (sdbCtx.currentTokenOffset() <= sdbCtx.realOffset) {
                    QueryOptionOffset offset = (QueryOptionOffset) query.option(QueryOptionOffset.ID);
                    offset.activate();
                    offset.offset = sdbCtx.realOffset - sdbCtx.currentTokenOffset();
                } else // if currentokenoffset is greater than previous page realoffset
                // go to previous page again
                {
                    previousPage(query);
                }
            } else {
                if (sdbCtx.previousToken() == null) {
                    sdbCtx.realOffset -= pag.pageSize;
                    // so now uses realOffset
                    if (sdbCtx.realOffset >= 0) {
                        QueryOptionOffset offset = (QueryOptionOffset) query.option(QueryOptionOffset.ID);
                        offset.activate();
                        offset.offset = sdbCtx.realOffset;
                    } else {
                        // resets realOffset to 0 because it was negative
                        sdbCtx.realOffset = 0;
                        sdbCtx.noMoreDataBefore = true;
                    }
                } else {
                    // follows the real offset
                    sdbCtx.realOffset -= pag.pageSize;
                    // uses offset
                    if (sdbCtx.currentTokenOffset() <= sdbCtx.realOffset) {
                        QueryOptionOffset offset = (QueryOptionOffset) query.option(QueryOptionOffset.ID);
                        offset.activate();
                        offset.offset = sdbCtx.realOffset - sdbCtx.currentTokenOffset();
                    } else // if currentokenoffset is greater than previous page realoffset
                    // go to previous page again
                    {
                        previousPage(query);
                    }
                }
            }
        } else {
            QueryOptionOffset offset = (QueryOptionOffset) query.option(QueryOptionOffset.ID);
            // to simulate the nextPage as there was no token yet
            if (sdbCtx.realOffset != 0) {
                // follows the real offset
                sdbCtx.realOffset -= pag.pageSize;
                offset.activate();
                offset.offset = sdbCtx.realOffset;
            } else {
                sdbCtx.noMoreDataBefore = true;
            }
        /*if(offset.offset != 0){
					offset.offset -= pag.pageSize;
					offset.activate();

					// follows the real offset
					sdbCtx.realOffset -= pag.pageSize;
				}else {
					// if the realOffset is not null, it means we are not at the index 0 of the table
					// so now uses realOffset
					if(sdbCtx.realOffset != 0){
						offset.activate();
						offset.offset = sdbCtx.realOffset;
					}
					sdbCtx.noMoreDataBefore = true;
				}*/
        }
    } else {
        // throws exception because it's impossible to reuse nextPage when paginating has been interrupted, the cases are too many
        throw new SienaException("Can't use nextPage after pagination has been interrupted...");
    }
}
Also used : QueryOptionOffset(siena.core.options.QueryOptionOffset) QueryOptionPage(siena.core.options.QueryOptionPage) QueryOptionState(siena.core.options.QueryOptionState) SienaException(siena.SienaException)

Example 13 with SienaException

use of siena.SienaException in project siena by mandubian.

the class SdbMappingUtils method setFromString.

public static void setFromString(Object obj, Field field, String val) {
    if (val == null)
        return;
    Class<?> fieldClass = field.getType();
    if (fieldClass == Integer.class || fieldClass == int.class) {
        Util.setField(obj, field, intFromString(val));
        return;
    }
    if (ClassInfo.isModel(fieldClass) && !ClassInfo.isEmbedded(field)) {
        try {
            Object relObj = Util.createObjectInstance(fieldClass);
            Field relIdField = ClassInfo.getIdField(fieldClass);
            setFromString(relObj, relIdField, val);
            Util.setField(obj, field, relObj);
            return;
        } catch (Exception e) {
            throw new SienaException(e);
        }
    } else {
        if (fieldClass == byte[].class) {
            try {
                Util.setField(obj, field, Base64.decode(val));
                return;
            } catch (Exception ex) {
                throw new SienaException(ex);
            }
        } else if (ClassInfo.isEmbeddedNative(field)) {
            return;
        } else if (fieldClass == BigDecimal.class) {
            DecimalPrecision ann = field.getAnnotation(DecimalPrecision.class);
            if (ann == null) {
                Util.setField(obj, field, new BigDecimal((String) val));
                return;
            } else {
                switch(ann.storageType()) {
                    case DOUBLE:
                        // TODO add bigdecimal double lexicographic storage
                        Util.setField(obj, field, new BigDecimal(val));
                        return;
                    case STRING:
                    case NATIVE:
                        Util.setField(obj, field, new BigDecimal(val));
                        return;
                }
            }
        }
    }
    Util.setFromObject(obj, field, val);
}
Also used : Field(java.lang.reflect.Field) DecimalPrecision(siena.core.DecimalPrecision) SienaException(siena.SienaException) SienaException(siena.SienaException) SienaRestrictedApiException(siena.SienaRestrictedApiException) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal)

Example 14 with SienaException

use of siena.SienaException in project siena by mandubian.

the class SdbMappingUtils method buildFilterOrder.

public static <T> StringBuilder buildFilterOrder(Query<T> query, StringBuilder q) {
    List<QueryFilter> filters = query.getFilters();
    Set<Field> filteredFields = new HashSet<Field>();
    boolean first = true;
    if (!filters.isEmpty()) {
        q.append(WHERE);
        for (QueryFilter filter : filters) {
            if (QueryFilterSimple.class.isAssignableFrom(filter.getClass())) {
                QueryFilterSimple qf = (QueryFilterSimple) filter;
                Field f = qf.field;
                Object value = qf.value;
                String op = qf.operator;
                // for order verification in case the order is not on a filtered field
                filteredFields.add(f);
                if (!first) {
                    q.append(AND);
                }
                first = false;
                String[] columns = ClassInfo.getColumnNames(f);
                if ("IN".equals(op)) {
                    if (!Collection.class.isAssignableFrom(value.getClass()))
                        throw new SienaException("Collection needed when using IN operator in filter() query");
                    StringBuilder s = new StringBuilder();
                    Collection<?> col = (Collection<?>) value;
                    for (Object object : col) {
                        // TO BE VERIFIED: SHOULD BE MANAGED by toString!!!
                        if (object != null) {
                            s.append("," + SimpleDB.quote(toString(f, object)));
                        } else {
                            throw new SienaException("Can't use NULL in collection for IN operator");
                        }
                    }
                    String column = null;
                    if (ClassInfo.isId(f)) {
                        column = ITEM_NAME;
                    } else {
                        column = ClassInfo.getColumnNames(f)[0];
                    }
                    q.append(column + " in(" + s.toString().substring(1) + ")");
                } else if (ClassInfo.isModel(f.getType())) {
                    // TODO could manage other ops here
                    if (!op.equals("=")) {
                        throw new SienaException("Unsupported operator for relationship: " + op);
                    }
                    ClassInfo relInfo = ClassInfo.getClassInfo(f.getType());
                    int i = 0;
                    for (Field key : relInfo.keys) {
                        if (value == null) {
                            q.append(columns[i++] + IS_NULL);
                        } else {
                            q.append(columns[i++] + op + SimpleDB.quote(objectFieldToString(value, key)));
                        }
                    }
                } else {
                    String column = null;
                    if (ClassInfo.isId(f)) {
                        column = "itemName()";
                        if (value == null && op.equals("=")) {
                            throw new SienaException("SDB filter on @Id field with 'IS NULL' is not possible");
                        }
                    } else {
                        column = ClassInfo.getColumnNames(f)[0];
                    }
                    if (value == null && op.equals("=")) {
                        q.append(column + IS_NULL);
                    } else if (value == null && op.equals("!=")) {
                        q.append(column + IS_NOT_NULL);
                    } else {
                        q.append(column + op + SimpleDB.quote(toString(f, value)));
                    }
                }
            } else if (QueryFilterSearch.class.isAssignableFrom(filter.getClass())) {
                Class<T> clazz = query.getQueriedClass();
                QueryFilterSearch qf = (QueryFilterSearch) filter;
                // throw new SienaException("Search not possible for several fields in SDB: only one field");
                try {
                    // Field field = Util.getField(clazz, qf.fields[0]);
                    // if(field.isAnnotationPresent(Unindexed.class)){
                    // throw new SienaException("Cannot search the @Unindexed field "+field.getName());
                    // }
                    // cuts match into words
                    String[] words = qf.match.split("\\s");
                    // if several words, then only OR operator represented by IN GAE
                    Pattern pNormal = Pattern.compile("[\\%]*(\\w+)[\\%]*");
                    if (!first) {
                        q.append(AND);
                    }
                    // forces true
                    first = true;
                    q.append(" ( ");
                    for (String f : qf.fields) {
                        Field field = Util.getField(clazz, f);
                        if (!first) {
                            q.append(OR);
                        }
                        first = false;
                        q.append(" ( ");
                        String column = null;
                        if (ClassInfo.isId(field)) {
                            column = "itemName()";
                        } else {
                            column = ClassInfo.getColumnNames(field)[0];
                        }
                        first = true;
                        for (String word : words) {
                            if (!first) {
                                q.append(OR);
                            }
                            first = false;
                            if (!pNormal.matcher(word).matches()) {
                                throw new SienaException("'" + word + "' doesn't match pattern [\\%]*(\\w+)[\\%]*");
                            }
                            if (word.contains("%")) {
                                q.append(column + LIKE + SimpleDB.quote(word));
                            } else {
                                q.append(column + EQ + SimpleDB.quote(word));
                            }
                        }
                        q.append(" ) ");
                    }
                    q.append(" ) ");
                } catch (Exception e) {
                    throw new SienaException(e);
                }
            }
        }
    }
    List<QueryOrder> orders = query.getOrders();
    if (!orders.isEmpty()) {
        QueryOrder last = orders.get(orders.size() - 1);
        Field field = last.field;
        if (ClassInfo.isId(field)) {
            if (!filteredFields.contains(field)) {
                if (filters.isEmpty()) {
                    q.append(WHERE);
                } else {
                    q.append(AND);
                }
                q.append(ITEM_NAME + IS_NOT_NULL);
            }
            q.append(ORDER_BY + ITEM_NAME);
        } else {
            String column = ClassInfo.getColumnNames(field)[0];
            if (!filteredFields.contains(field)) {
                if (filters.isEmpty()) {
                    q.append(WHERE);
                } else {
                    q.append(AND);
                }
                q.append(column + IS_NOT_NULL);
            }
            q.append(ORDER_BY + column);
        }
        if (!last.ascending)
            q.append(DESC);
    }
    QueryOptionSdbContext sdbCtx = (QueryOptionSdbContext) query.option(QueryOptionSdbContext.ID);
    QueryOptionOffset off = (QueryOptionOffset) query.option(QueryOptionOffset.ID);
    if (sdbCtx != null && sdbCtx.realPageSize != 0) {
        if (off != null && off.isActive()) {
            // if offset is active, adds it to the page size to be sure to retrieve enough elements
            q.append(LIMIT + (sdbCtx.realPageSize + off.offset));
        } else {
            q.append(LIMIT + sdbCtx.realPageSize);
        }
    }
    return q;
}
Also used : Pattern(java.util.regex.Pattern) QueryOptionOffset(siena.core.options.QueryOptionOffset) SienaException(siena.SienaException) SienaRestrictedApiException(siena.SienaRestrictedApiException) IOException(java.io.IOException) QueryFilterSearch(siena.QueryFilterSearch) QueryOrder(siena.QueryOrder) Field(java.lang.reflect.Field) QueryFilter(siena.QueryFilter) QueryFilterSimple(siena.QueryFilterSimple) Collection(java.util.Collection) SienaException(siena.SienaException) HashSet(java.util.HashSet) ClassInfo(siena.ClassInfo)

Example 15 with SienaException

use of siena.SienaException in project siena by mandubian.

the class RemoteStub method process.

@SuppressWarnings("unchecked")
public Document process(Document doc) {
    try {
        Element root = doc.getRootElement();
        if (key != null) {
            // TODO: cutom exception message if time is null
            long time = Long.parseLong(root.attributeValue("time"));
            String hash = root.attributeValue("hash");
            if (!Util.sha1(time + key).equals(hash)) {
                throw new SienaException("Invalid hash");
            }
            long diff = Math.abs(time - System.currentTimeMillis());
            if (diff > 10000) {
                throw new SienaException("Invalid time");
            }
        }
        String action = root.getName();
        if ("insert".equals(action)) {
            Model obj = parseEntity(root, classLoader);
            obj.insert();
            return simpleResponse(obj, true);
        } else if ("update".equals(action)) {
            parseEntity(root, classLoader).update();
        } else if ("delete".equals(action)) {
            parseEntity(root, classLoader).delete();
        } else if ("get".equals(action)) {
            Model obj = parseEntity(root, classLoader);
            obj.get();
            return simpleResponse(obj, false);
        } else if ("query".equals(action)) {
            // TODO: convert document to QueryBase
            String clazzName = root.attributeValue("class");
            Class<? extends Model> clazz = (Class<? extends Model>) Common.classForName(clazzName, classLoader);
            Query<? extends Model> query = Model.all(clazz);
            List<Element> list = root.elements();
            for (Element element : list) {
                String name = element.getName();
                String fieldName = element.attributeValue("field");
                if ("filter".equals(name)) {
                    // TODO: operator attribute
                    Field field = clazz.getField(fieldName);
                    Object value = null;
                    if (element.hasContent()) {
                        if (ClassInfo.isModel(field.getType())) {
                            value = Common.parseEntity(element, classLoader);
                        } else {
                            value = Util.fromString(field.getType(), element.getText());
                        }
                    }
                    query.filter(fieldName, value);
                } else if ("order".equals(name)) {
                    // TODO: ascending attribute
                    query.order(fieldName);
                }
            }
            String limit = root.attributeValue("limit");
            String offset = root.attributeValue("offset");
            List<? extends Model> result = null;
            if (limit != null && offset != null) {
                result = query.fetch(Integer.parseInt(limit), Integer.parseInt(offset));
            } else if (limit != null) {
                result = query.fetch(Integer.parseInt(limit));
            } else {
                result = query.fetch();
            }
            Document response = DocumentHelper.createDocument();
            Element r = response.addElement("result");
            for (Model obj : result) {
                Element object = r.addElement("object");
                fillRequestElement(obj, object, false);
            }
            // TODO add nextOffset to response
            return response;
        }
    } catch (Throwable e) {
        return error(e);
    }
    return newDocument("ok");
}
Also used : Common.fillRequestElement(siena.remote.Common.fillRequestElement) Element(org.dom4j.Element) Document(org.dom4j.Document) Field(java.lang.reflect.Field) Model(siena.Model) SienaException(siena.SienaException)

Aggregations

SienaException (siena.SienaException)214 Field (java.lang.reflect.Field)65 TransactionAccountFrom (siena.base.test.model.TransactionAccountFrom)52 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)40 SQLException (java.sql.SQLException)38 TransactionAccountTo (siena.base.test.model.TransactionAccountTo)34 SienaRestrictedApiException (siena.SienaRestrictedApiException)33 PreparedStatement (java.sql.PreparedStatement)25 ClassInfo (siena.ClassInfo)21 HashMap (java.util.HashMap)19 List (java.util.List)18 Discovery (siena.base.test.model.Discovery)18 Entity (com.google.appengine.api.datastore.Entity)15 Key (com.google.appengine.api.datastore.Key)14 ResultSet (java.sql.ResultSet)14 Id (siena.Id)14 AmazonClientException (com.amazonaws.AmazonClientException)12 Collection (java.util.Collection)10 DiscoveryStringId (siena.base.test.model.DiscoveryStringId)9