Example usage for java.lang Long intValue

List of usage examples for java.lang Long intValue

Introduction

In this page you can find the example usage for java.lang Long intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Long as an int after a narrowing primitive conversion.

Usage

From source file:com.abiquo.server.core.pricing.PricingTemplateDAO.java

public Collection<PricingTemplate> find(final String filter, final String orderBy, final boolean desc,
        final Integer offset, Integer numResults, final Integer startwith) {
    Criteria criteria = createCriteria(filter, orderBy, desc);

    Long total = count(criteria);

    criteria = createCriteria(filter, orderBy, desc);
    numResults = (int) (numResults != 0 ? numResults : total);
    criteria.setFirstResult(offset * numResults);
    if (startwith != -1) {
        criteria.setFirstResult(startwith);
    }//from  ww w.  java2  s .c  o m

    criteria.setMaxResults(numResults);

    List<PricingTemplate> result = getResultList(criteria);

    PagedList<PricingTemplate> page = new PagedList<PricingTemplate>();
    page.addAll(result);
    page.setCurrentElement(offset);
    if (startwith != -1) {
        page.setCurrentElement(startwith);
    }
    page.setPageSize(numResults);
    page.setTotalResults(total.intValue());

    return page;
}

From source file:it.geosolutions.opensdi2.mvc.BaseFileManager.java

/**
 * Download a file with a stream//from w  ww .j  av  a2s.  c om
 * 
 * @param contentType
 * @param contentDisposition
 * @param resp
 * @param fileName
 * @param filePath
 * @return
 */
protected ResponseEntity<byte[]> download(String contentType, String contentDisposition,
        HttpServletResponse resp, String fileName, String filePath) {

    final HttpHeaders headers = new HttpHeaders();
    File toServeUp = new File(filePath);
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(toServeUp);
    } catch (FileNotFoundException e) {

        // Also useful, this is a good was to serve down an error message
        String msg = "ERROR: Could not find the file specified.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

    }

    // content type
    if (contentType != null) {
        resp.setContentType(contentType);
    }

    // content disposition
    if (contentDisposition != null) {
        resp.setHeader("Content-Disposition", contentDisposition);
    }

    Long fileSize = toServeUp.length();
    resp.setContentLength(fileSize.intValue());

    OutputStream outputStream = null;

    try {
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        String msg = "ERROR: Could not generate output stream.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e1) {
                // nothing
            }
        }
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    byte[] buffer = new byte[1024];

    int read = 0;
    try {

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        // close the streams to prevent memory leaks
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    } catch (Exception e) {
        String msg = "ERROR: Could not read file.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    return null;
}

From source file:edu.fullerton.ldvw.LdvDispatcher.java

private boolean getImg() throws WebUtilException {
    boolean ret = true;
    try {/*from   www  .  j  ava2s  . c  o  m*/
        String imgIdStr = request.getParameter("imgId");
        String widthStr = request.getParameter("width");
        int width = 0;
        if (widthStr != null && !widthStr.isEmpty()) {
            if (widthStr.matches("^\\d+$")) {
                width = Integer.parseInt(widthStr);
            }
        }

        if (imgIdStr != null && !imgIdStr.isEmpty()) {
            if (imgIdStr.toLowerCase().matches("^\\d+$")) {
                int imgId = Integer.parseInt(imgIdStr);
                ImageTable itbl = new ImageTable(db);
                itbl.sendImg(response, imgId, width);
                ret = false;
                Long timeMs = System.currentTimeMillis() - startTime;
                vuser.logPage(String.format("Sent image #%1$d", imgId), itbl.getLastImageSize(),
                        timeMs.intValue());
            } else {
                vpage.add("getImg has an invalid id.");
            }
        } else {
            vpage.add("getImg has no image id.");
        }
    } catch (NumberFormatException | SQLException | IOException ex) {
        throw new WebUtilException("Get saved image", ex);
    }
    return ret;
}

From source file:it.geosolutions.opensdi2.mvc.BaseFileManager.java

/**
 * Download a file with a stream//  w w w  .ja va  2 s. c om
 * 
 * @param contentType
 * @param contentDisposition
 * @param resp
 * @param fileName
 * @param filePath
 * @return
 */
protected ResponseEntity<byte[]> serveImageThumb(HttpServletResponse resp, String fileName, String filePath) {

    String contentType = "image/jpg";

    final HttpHeaders headers = new HttpHeaders();
    File toServeUp = new File(filePath);
    InputStream inputStream = null;
    String thumbPath = filePath + "_thumb";
    File fileThumb = new File(thumbPath);

    if (fileThumb.exists()) {
        try {
            inputStream = new FileInputStream(fileThumb);
        } catch (FileNotFoundException e) {

            // Also useful, this is a good was to serve down an error
            // message
            String msg = "ERROR: Could not find the file specified.";
            headers.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

        }
    } else {
        try {
            inputStream = getImageThumb(toServeUp, thumbPath);
            fileThumb = new File(thumbPath);
        } catch (Exception e) {

            // Also useful, this is a good was to serve down an error
            // message
            String msg = "ERROR: Could not find the file specified.";
            headers.setContentType(MediaType.TEXT_PLAIN);
            return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);

        }
    }

    // content type
    resp.setContentType(contentType);

    Long fileSize = fileThumb.length();
    resp.setContentLength(fileSize.intValue());

    OutputStream outputStream = null;

    try {
        outputStream = resp.getOutputStream();
    } catch (IOException e) {
        String msg = "ERROR: Could not generate output stream.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    byte[] buffer = new byte[1024];

    int read = 0;
    try {

        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        // close the streams to prevent memory leaks
        outputStream.flush();
        outputStream.close();
        inputStream.close();

    } catch (Exception e) {
        String msg = "ERROR: Could not read file.";
        headers.setContentType(MediaType.TEXT_PLAIN);
        return new ResponseEntity<byte[]>(msg.getBytes(), headers, HttpStatus.NOT_FOUND);
    }

    return null;
}

From source file:uk.org.funcube.fcdw.server.processor.WholeOrbitDataProcessorImpl.java

private void extractAndSaveWod(final Long satelliteId, final long seqNo, final List<String> frames,
        final Date receivedDate) {

    final Date frameTime = new Date(receivedDate.getTime() - 104 * 60 * 1000);

    final StringBuffer sb = new StringBuffer();

    for (int i = 0; i < 12; i++) {
        sb.append(StringUtils.right(frames.get(i), 400));
    }//  w w  w  .  ja va2  s .  c om

    int start = 0;
    int end = 46;

    for (int i = 0; i < 104; i++) {

        final long frameNumber = seqNo * 2 + i;

        if (wholeOrbitDataDao.findBySatelliteIdAndFrameNumber(satelliteId, frameNumber).size() == 0) {

            WholeOrbitDataEntity wod = null;

            switch (satelliteId.intValue()) {
            case 0:
                wod = new GomSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            case 1:
                wod = new ClydeSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            case 2:
                wod = new GomSpaceWODEntity(satelliteId, seqNo, frameNumber,
                        convertHexBytePairToBinary(sb.substring(start, end)), frameTime);
                break;
            default:
                break;
            }

            if (wod != null) {
                wholeOrbitDataDao.save(wod);
            }

            start += 46;
            end += 46;
        }

        // move the frame time forward a minute
        frameTime.setTime(frameTime.getTime() + 60 * 1000);
    }
}

From source file:com.pastekit.twist.gae.GaeUnmarshaller.java

private void doUnmarshall(Object destination, Transaction transaction, Entity entity) {
    //        Preconditions.checkNotNull(destination, "Destination object cannot be null");
    //        Preconditions.checkNotNull(entity, "Source entity cannot be null");
    assert validator.validate(destination) == true;

    Map<String, Object> props = entity.getProperties();
    Key key = entity.getKey();//from  w w w  .j a v a  2s . c o  m
    String name = entity.getKey().getName();

    if (destination instanceof PrimitiveWrapper) {
        PrimitiveWrapper wrapper = (PrimitiveWrapper) destination;
        Object wrapped = wrapper.getValue();
        if (wrapped.getClass().isPrimitive() || wrapped.getClass().equals(String.class)
                || wrapped.getClass().equals(Integer.class) || wrapped.getClass().equals(Long.class)
                || wrapped.getClass().equals(Double.class) || wrapped.getClass().equals(Float.class)
                || wrapped.getClass().equals(Boolean.class)) {
            if (entity.getProperties().size() > 1) {
                LOG.warn(
                        "Unmarshalling entity with multiple properties into primitive type will be serialized");
                // TODO: Implement XStream serializer
                throw new RuntimeException(
                        "Serializing multiple properties into primitives not yet implemented");
            } else if (entity.getProperties().size() == 1) {
                String entityKey = entity.getProperties().keySet().iterator().next();
                wrapper.setValue(entity.getProperty(entityKey));
            }
        }
        return;
    } else if (destination instanceof Map) {
        Iterator<Map.Entry<String, Object>> it = entity.getProperties().entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String entryKey = entry.getKey();
            Object entryVal = entry.getValue();
            if (entryVal instanceof EmbeddedEntity) {
                EmbeddedEntity ee = (EmbeddedEntity) entryVal;
                Object mapOrList = GaeMarshaller.getMapOrList(ee);
                ((Map) destination).put(entryKey, mapOrList);
            } else {
                ((Map) destination).put(entryKey, entryVal);
            }
        }
        ((Map) destination).put(Entity.KEY_RESERVED_PROPERTY, key.getName());
        return;
    }

    AnnotatedField parentKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.parent(), destination);
    if (parentKeyField != null) {
        if (parentKeyField.getFieldType().equals(Key.class)) {
            parentKeyField.setFieldValue(entity.getParent());
        } else {
            //                throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField ancestorKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.ancestor(),
            destination);
    if (ancestorKeyField != null) {
        if (ancestorKeyField.getFieldType().equals(Key.class)) {
            ancestorKeyField.setFieldValue(getAncestor(entity));
        } else {
            throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField idField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.key(), destination);
    if (idField != null) {
        if (idField.getFieldType().equals(String.class)) {
            idField.setFieldValue(key.getName());
        } else if (idField.getFieldType().equals(Long.class)) {
            idField.setFieldValue(key.getId());
        } else if (idField.getFieldType().equals(long.class)) {
            idField.setFieldValue(key.getId());
        } else {
            throw new RuntimeException("Invalid key was retrieved with type " + idField.getFieldType());
        }
    }

    AnnotatedField kindField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.kind(), destination);
    if (kindField != null) {
        if (kindField.getFieldType().equals(String.class)) {
            kindField.setFieldValue(entity.getKind());
        } else {
            throw new RuntimeException("Invalid @Kind field is found for " + destination.getClass().getName());
        }
    }

    AnnotatedField flatField = AnnotationUtil.getFieldWithAnnotation(Flat.class, destination);
    if (flatField != null) {
        if (flatField.getFieldType().equals(Map.class)) {
            Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
            Map map = new LinkedHashMap();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                // TODO: How about when by change a Map key would be the same with the POJO field name
                // TODO: Fix this or do not allow that to happen!
                boolean ok = true;
                Field[] fields = destination.getClass().getDeclaredFields();
                for (Field field : list(fields)) {
                    if (field.getName().equals(fieldName)) {
                        ok = false;
                    }
                }
                if (ok) {
                    map.put(fieldName, fieldValue);
                }
            }
            Field field = flatField.getField();
            setFieldValue(field, destination, map);
        } else {
            throw new RuntimeException("Only java.util.Map should be used for @Flat fields");
        }

    }

    Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
    Class<?> clazz = destination.getClass();
    List<Field> fields = list(clazz.getDeclaredFields());

    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String fieldName = entry.getKey();
        Object fieldValue = entry.getValue();
        try {
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    if (fieldValue == null) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Key) { // child
                        try {
                            Entity e = store.getDatastoreService()
                                    .get((com.google.appengine.api.datastore.Key) fieldValue);
                            AnnotatedField annotatedField = AnnotationUtil
                                    .getFieldWithAnnotation(GaeObjectStore.child(), destination);
                            Object childInstance = store.createInstance(annotatedField.getFieldType());
                            unmarshall(childInstance, e);
                            setFieldValue(field, destination, childInstance);
                        } catch (EntityNotFoundException e) {
                            fieldValue = null;
                        }
                    } else if (fieldValue instanceof String || fieldValue instanceof Boolean
                            || fieldValue instanceof Number || fieldValue instanceof Blob) {
                        if (field.getName().equals(fieldName)) {
                            Class<?> fieldType = field.getType();
                            if (field.getType().equals(String.class)) {
                                setFieldValue(field, destination, String.valueOf(fieldValue));
                            } else if (field.getType().equals(Boolean.class)) {
                                setFieldValue(field, destination, (Boolean) fieldValue);
                            } else if (field.getType().equals(Long.class)) {
                                setFieldValue(field, destination, (Long) fieldValue);
                            } else if (field.getType().equals(Integer.class)) {
                                if (fieldValue.getClass().equals(Long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, (Integer) fieldValue);
                                }
                            } else if (field.getType().equals(int.class)) {
                                if (fieldValue.getClass().equals(Long.class)
                                        || fieldValue.getClass().equals(long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, ((Integer) fieldValue).intValue());
                                }
                            } else if (field.getType().equals(long.class)) {
                                if (fieldValue.getClass().equals(Integer.class)
                                        || fieldValue.getClass().equals(int.class)) {
                                    Integer value = (Integer) fieldValue;
                                    setFieldValue(field, destination, value.longValue());
                                } else {
                                    setFieldValue(field, destination, ((Long) fieldValue).longValue());
                                }
                            } else if (field.getType().equals(boolean.class)) {
                                setFieldValue(field, destination, ((Boolean) fieldValue).booleanValue());
                            } else if (field.getType().equals(byte.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    // TODO: Need to have a second look with this code
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes()[0]);
                                }
                            } else if (field.getType().equals(byte[].class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes());
                                }
                            } else if (field.getType().equals(Date.class)) {
                                if (fieldValue.getClass().equals(String.class)) {
                                    Date date = DateUtil.parseDate((String) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Long.class)) {
                                    Date date = new Date((Long) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Date.class)) {
                                    setFieldValue(field, destination, fieldValue);
                                } else {
                                    throw new RuntimeException(
                                            "Unable to unmarshall " + fieldValue.getClass().getName() + " to "
                                                    + field.getType().getName());
                                }
                            }
                        }
                    } else if (fieldValue instanceof Text) {
                        Text textField = (Text) fieldValue;
                        setFieldValue(field, destination, textField.getValue());
                    } else if (fieldValue instanceof Date) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof User) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof EmbeddedEntity) { // List or Java  primitive types and standard types, Map or  POJO's
                        Class<?> fieldValueType = fieldValue.getClass();
                        EmbeddedEntity ee = (EmbeddedEntity) fieldValue;
                        Map<String, Object> map = ee.getProperties();
                        store.createInstance(fieldValueType);
                        if (field.getType().equals(List.class) || field.getType().equals(Map.class)) {
                            Object mapOrList = getMapOrList((EmbeddedEntity) fieldValue);
                            setFieldValue(field, destination, mapOrList);
                        } else { // Must be a POJO
                            Map<String, Object> getMap = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue);
                            Object pojo = Maps.fromMap(getMap, field.getType());
                            setFieldValue(field, destination, pojo);
                        }
                    } else if (fieldValue instanceof GeoPt) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof List) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue.getClass().isPrimitive()) {
                        throw new RuntimeException("Not yet implemented");
                    }
                }
            }
        } catch (ClassCastException e) {
            if (fieldName != null && fieldValue != null) {
                LOG.error("Exception while unmarshalling GAE Entity field name=" + fieldName + " type="
                        + fieldValue.getClass().getName() + " value=" + fieldValue);
            }
            throw e;
        }
    }
    AnnotatedField aliasField = AnnotationUtil.getFieldWithAnnotation(Alias.class, destination);
    if (aliasField != null) {
        Alias alias = aliasField.getField().getAnnotation(Alias.class);
        String fieldName = alias.field();
        Object value = props.get(fieldName);

        String actualField = aliasField.getFieldName();
        Object actualValue = props.get(actualField);

        if (value != null) {
            setFieldValue(aliasField.getField(), destination, value);
        } else {
            setFieldValue(aliasField.getField(), destination, actualValue);
        }
    }
}

From source file:com.hunchee.twist.gae.GaeUnmarshaller.java

private void doUnmarshall(Object destination, Transaction transaction, Entity entity) {
    //        Preconditions.checkNotNull(destination, "Destination object cannot be null");
    //        Preconditions.checkNotNull(entity, "Source entity cannot be null");
    assert validator.validate(destination) == true;

    Map<String, Object> props = entity.getProperties();
    Key key = entity.getKey();//from   w ww .ja va 2  s  .  c o m
    String name = entity.getKey().getName();

    if (destination instanceof PrimitiveWrapper) {
        PrimitiveWrapper wrapper = (PrimitiveWrapper) destination;
        Object wrapped = wrapper.getValue();
        if (wrapped.getClass().isPrimitive() || wrapped.getClass().equals(String.class)
                || wrapped.getClass().equals(Integer.class) || wrapped.getClass().equals(Long.class)
                || wrapped.getClass().equals(Double.class) || wrapped.getClass().equals(Float.class)
                || wrapped.getClass().equals(Boolean.class)) {
            if (entity.getProperties().size() > 1) {
                LOG.warn(
                        "Unmarshalling entity with multiple properties into primitive type will be serialized");
                // TODO: Implement XStream serializer
                throw new RuntimeException(
                        "Serializing multiple properties into primitives not yet implemented");
            } else if (entity.getProperties().size() == 1) {
                String entityKey = entity.getProperties().keySet().iterator().next();
                wrapper.setValue(entity.getProperty(entityKey));
            }
        }
        return;
    } else if (destination instanceof Map) {
        Iterator<Map.Entry<String, Object>> it = entity.getProperties().entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String entryKey = entry.getKey();
            Object entryVal = entry.getValue();
            if (entryVal instanceof EmbeddedEntity) {
                EmbeddedEntity ee = (EmbeddedEntity) entryVal;
                Object mapOrList = GaeMarshaller.getMapOrList(ee);
                ((Map) destination).put(entryKey, mapOrList);
            } else {
                ((Map) destination).put(entryKey, entryVal);
            }
        }
        ((Map) destination).put(Entity.KEY_RESERVED_PROPERTY, key.getName());
        return;
    }

    AnnotatedField parentKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.parent(), destination);
    if (parentKeyField != null) {
        if (parentKeyField.getFieldType().equals(Key.class)) {
            parentKeyField.setFieldValue(entity.getParent());
        } else {
            //                throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField ancestorKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.ancestor(),
            destination);
    if (ancestorKeyField != null) {
        if (ancestorKeyField.getFieldType().equals(Key.class)) {
            ancestorKeyField.setFieldValue(getAncestor(entity));
        } else {
            throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField idField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.key(), destination);
    if (idField != null) {
        if (idField.getFieldType().equals(String.class)) {
            idField.setFieldValue(key.getName());
        } else if (idField.getFieldType().equals(Long.class)) {
            idField.setFieldValue(key.getId());
        } else if (idField.getFieldType().equals(long.class)) {
            idField.setFieldValue(key.getId());
        } else {
            throw new RuntimeException("Invalid key was retrieved with type " + idField.getFieldType());
        }
    }

    AnnotatedField kindField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.kind(), destination);
    if (kindField != null) {
        if (kindField.getFieldType().equals(String.class)) {
            kindField.setFieldValue(entity.getKind());
        } else {
            throw new RuntimeException("Invalid @Kind field is found for " + destination.getClass().getName());
        }
    }

    AnnotatedField flatField = AnnotationUtil.getFieldWithAnnotation(Flat.class, destination);
    if (flatField != null) {
        if (flatField.getFieldType().equals(Map.class)) {
            Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
            Map map = new LinkedHashMap();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                // TODO: How about when by change a Map key would be the same with the POJO field name
                // TODO: Fix this or do not allow that to happen!
                boolean ok = true;
                Field[] fields = destination.getClass().getDeclaredFields();
                for (Field field : list(fields)) {
                    if (field.getName().equals(fieldName)) {
                        ok = false;
                    }
                }
                if (ok) {
                    map.put(fieldName, fieldValue);
                }
            }
            Field field = flatField.getField();
            setFieldValue(field, destination, map);
        } else {
            throw new RuntimeException("Only java.util.Map should be used for @Flat fields");
        }

    }

    Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
    Class<?> clazz = destination.getClass();
    List<Field> fields = list(clazz.getDeclaredFields());

    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String fieldName = entry.getKey();
        Object fieldValue = entry.getValue();
        try {
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    if (fieldValue == null) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Key) { // child
                        try {
                            Entity e = store.getDatastoreService()
                                    .get((com.google.appengine.api.datastore.Key) fieldValue);
                            AnnotatedField annotatedField = AnnotationUtil
                                    .getFieldWithAnnotation(GaeObjectStore.child(), destination);
                            Object childInstance = store.createInstance(annotatedField.getFieldType());
                            unmarshall(childInstance, e);
                            setFieldValue(field, destination, childInstance);
                        } catch (EntityNotFoundException e) {
                            fieldValue = null;
                        }
                    } else if (fieldValue instanceof String || fieldValue instanceof Boolean
                            || fieldValue instanceof Number || fieldValue instanceof Blob) {
                        if (field.getName().equals(fieldName)) {
                            if (field.getType().isEnum()) {
                                setFieldValue(field, destination,
                                        Enum.valueOf((Class<Enum>) field.getType(), (String) fieldValue));
                            }
                            if (field.getType().equals(String.class)) {
                                setFieldValue(field, destination, String.valueOf(fieldValue));
                            } else if (field.getType().equals(Boolean.class)) {
                                setFieldValue(field, destination, (Boolean) fieldValue);
                            } else if (field.getType().equals(Long.class)) {
                                setFieldValue(field, destination, (Long) fieldValue);
                            } else if (field.getType().equals(Integer.class)) {
                                if (fieldValue.getClass().equals(Long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, (Integer) fieldValue);
                                }
                            } else if (field.getType().equals(int.class)) {
                                if (fieldValue.getClass().equals(Long.class)
                                        || fieldValue.getClass().equals(long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, ((Integer) fieldValue).intValue());
                                }
                            } else if (field.getType().equals(long.class)) {
                                if (fieldValue.getClass().equals(Integer.class)
                                        || fieldValue.getClass().equals(int.class)) {
                                    Integer value = (Integer) fieldValue;
                                    setFieldValue(field, destination, value.longValue());
                                } else {
                                    setFieldValue(field, destination, ((Long) fieldValue).longValue());
                                }
                            } else if (field.getType().equals(boolean.class)) {
                                setFieldValue(field, destination, ((Boolean) fieldValue).booleanValue());
                            } else if (field.getType().equals(byte.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    // TODO: Need to have a second look with this code
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes()[0]);
                                }
                            } else if (field.getType().equals(byte[].class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes());
                                }
                            } else if (field.getType().equals(Date.class)) {
                                if (fieldValue.getClass().equals(String.class)) {
                                    Date date = DateUtil.parseDate((String) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Long.class)) {
                                    Date date = new Date((Long) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Date.class)) {
                                    setFieldValue(field, destination, fieldValue);
                                } else {
                                    throw new RuntimeException(
                                            "Unable to unmarshall " + fieldValue.getClass().getName() + " to "
                                                    + field.getType().getName());
                                }
                            } else if (field.getType().equals(Blob.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob);
                                }
                            }
                        }
                    } else if (fieldValue instanceof Blob) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Text) {
                        Text textField = (Text) fieldValue;
                        setFieldValue(field, destination, textField.getValue());
                    } else if (fieldValue instanceof Date) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof User) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof EmbeddedEntity) { // List or Java  primitive types and standard types, Map or  POJO's
                        Class<?> fieldValueType = fieldValue.getClass();
                        EmbeddedEntity ee = (EmbeddedEntity) fieldValue;
                        Map<String, Object> map = ee.getProperties();
                        store.createInstance(fieldValueType);
                        if (field.getType().equals(List.class) || field.getType().equals(Map.class)) {
                            Object mapOrList = getMapOrList((EmbeddedEntity) fieldValue);
                            setFieldValue(field, destination, mapOrList);
                        } else { // Must be a POJO
                            Map<String, Object> getMap = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue);
                            Object pojo = Maps.fromMap(getMap, field.getType());
                            setFieldValue(field, destination, pojo);
                        }
                    } else if (fieldValue instanceof GeoPt) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof List) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue.getClass().isPrimitive()) {
                        throw new RuntimeException("Not yet implemented");
                    }
                }
            }
        } catch (ClassCastException e) {
            if (fieldName != null && fieldValue != null) {
                LOG.error("Exception while unmarshalling GAE Entity field name=" + fieldName + " type="
                        + fieldValue.getClass().getName() + " value=" + fieldValue);
            }
            throw e;
        }
    }
    AnnotatedField aliasField = AnnotationUtil.getFieldWithAnnotation(Alias.class, destination);
    if (aliasField != null) {
        Alias alias = aliasField.getField().getAnnotation(Alias.class);
        String fieldName = alias.field();
        Object value = props.get(fieldName);

        String actualField = aliasField.getFieldName();
        Object actualValue = props.get(actualField);

        if (value != null) {
            setFieldValue(aliasField.getField(), destination, value);
        } else {
            setFieldValue(aliasField.getField(), destination, actualValue);
        }
    }
}

From source file:com.autentia.wuija.persistence.impl.hibernate.HibernateDao.java

private <T> Pair<List<T>, Long> findAndCount(HibernateCallback queryCallback,
        HibernateCallback countQueryCallback, int maxResults) {
    final Pair<List<T>, Long> pair = new Pair<List<T>, Long>();

    // Si hay paginacin, hay que hacer un select count para saber el nmero de registros totales.
    if (maxResults > 0) {
        final Long rowCount = (Long) findByHibernateCallback(countQueryCallback).get(0);
        pair.setRight(rowCount);//from   w  ww .  ja va  2 s .c o  m

        // Pequeo shortcut: si no hay resultados, ni siquiera se hace la bsqueda.
        if (rowCount.intValue() == 0) {
            final List<T> emptyList = Collections.emptyList();
            pair.setLeft(emptyList);
            return pair;
        }
    }

    final List<T> list = findByHibernateCallback(queryCallback);
    pair.setLeft(list);

    // Si todava no se ha calculado el numero total de registros, se saca del tamao de la lista de resultados.
    if (pair.getRight() == null) {
        pair.setRight(Long.valueOf(list.size()));
    }

    return pair;
}

From source file:br.ufc.deti.ecgweb.domain.exam.EcgService.java

public List<EcgSignal> getSignalsByTimeIndex(Long channelId, Long idx, Long timeInSeconds) {
    EcgChannel channel = ecgChannelRepository.findOne(channelId);
    Long frequency = channel.getEcg().getSampleRate();
    Long firstIdx = frequency * timeInSeconds * idx;
    Long lastIndex = firstIdx + (frequency * timeInSeconds);

    List<EcgSignal> signals = channel.getSignals();

    if (lastIndex >= signals.size())
        lastIndex = (long) signals.size();

    return signals.subList(firstIdx.intValue(), lastIndex.intValue());
}

From source file:com.dotweblabs.twirl.gae.GaeUnmarshaller.java

private void doUnmarshall(Object destination, Transaction transaction, Entity entity) {
    //        Preconditions.checkNotNull(destination, "Destination object cannot be null");
    //        Preconditions.checkNotNull(entity, "Source entity cannot be null");
    assert validator.validate(destination) == true;

    Map<String, Object> props = entity.getProperties();
    Key key = entity.getKey();//from w  w  w  .ja  v a  2s.c om
    String name = entity.getKey().getName();

    if (destination instanceof PrimitiveWrapper) {
        PrimitiveWrapper wrapper = (PrimitiveWrapper) destination;
        Object wrapped = wrapper.getValue();
        if (wrapped.getClass().isPrimitive() || wrapped.getClass().equals(String.class)
                || wrapped.getClass().equals(Integer.class) || wrapped.getClass().equals(Long.class)
                || wrapped.getClass().equals(Double.class) || wrapped.getClass().equals(Float.class)
                || wrapped.getClass().equals(Boolean.class)) {
            if (entity.getProperties().size() > 1) {
                LOG.warn(
                        "Unmarshalling entity with multiple properties into primitive type will be serialized");
                // TODO: Implement XStream serializer
                throw new RuntimeException(
                        "Serializing multiple properties into primitives not yet implemented");
            } else if (entity.getProperties().size() == 1) {
                String entityKey = entity.getProperties().keySet().iterator().next();
                wrapper.setValue(entity.getProperty(entityKey));
            }
        }
        return;
    } else if (destination instanceof Map) {
        Iterator<Map.Entry<String, Object>> it = entity.getProperties().entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String entryKey = entry.getKey();
            Object entryVal = entry.getValue();
            if (entryVal instanceof EmbeddedEntity) {
                EmbeddedEntity ee = (EmbeddedEntity) entryVal;
                Object mapOrList = GaeMarshaller.getMapOrList(ee);
                ((Map) destination).put(entryKey, mapOrList);
            } else {
                ((Map) destination).put(entryKey, entryVal);
            }
        }
        ((Map) destination).put(Entity.KEY_RESERVED_PROPERTY, key.getName());
        return;
    }

    AnnotatedField parentKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.parent(), destination);
    if (parentKeyField != null) {
        if (parentKeyField.getFieldType().equals(Key.class)) {
            parentKeyField.setFieldValue(entity.getParent());
        } else {
            //                throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField ancestorKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.ancestor(),
            destination);
    if (ancestorKeyField != null) {
        if (ancestorKeyField.getFieldType().equals(Key.class)) {
            ancestorKeyField.setFieldValue(getAncestor(entity));
        } else {
            throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField idField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.key(), destination);
    if (idField != null) {
        if (idField.getFieldType().equals(String.class)) {
            idField.setFieldValue(key.getName());
        } else if (idField.getFieldType().equals(Long.class)) {
            idField.setFieldValue(key.getId());
        } else if (idField.getFieldType().equals(long.class)) {
            idField.setFieldValue(key.getId());
        } else {
            throw new RuntimeException("Invalid key was retrieved with type " + idField.getFieldType());
        }
    }

    AnnotatedField objectIdField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.objectId(),
            destination);
    if (objectIdField != null) {
        if (objectIdField.getFieldType().equals(String.class)) {
            String objectId = KeyFactory.keyToString(key);
            objectIdField.setFieldValue(objectId);
        } else {
            throw new RuntimeException(
                    "Invalid ObjectId key was retrieved with type " + objectIdField.getFieldType());
        }
    }

    AnnotatedField kindField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.kind(), destination);
    if (kindField != null) {
        if (kindField.getFieldType().equals(String.class)) {
            kindField.setFieldValue(entity.getKind());
        } else {
            throw new RuntimeException("Invalid @Kind field is found for " + destination.getClass().getName());
        }
    }

    AnnotatedField flatField = AnnotationUtil.getFieldWithAnnotation(Flat.class, destination);
    if (flatField != null) {
        if (flatField.getFieldType().equals(Map.class)) {
            Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
            Map map = new LinkedHashMap();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                // TODO: How about when by change a Map key would be the same with the POJO field name
                // TODO: Fix this or do not allow that to happen!
                boolean ok = true;
                Field[] fields = destination.getClass().getDeclaredFields();
                for (Field field : list(fields)) {
                    if (field.getName().equals(fieldName)) {
                        ok = false;
                    }
                }
                if (ok) {
                    if (fieldValue instanceof EmbeddedEntity) {
                        Map m = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue);
                        fieldValue = m;
                    }
                    map.put(fieldName, fieldValue);
                }
            }
            Field field = flatField.getField();
            setFieldValue(field, destination, map);
        } else {
            throw new RuntimeException("Only java.util.Map should be used for @Flat fields");
        }

    }

    Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
    Class<?> clazz = destination.getClass();
    List<Field> fields = list(clazz.getDeclaredFields());

    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String fieldName = entry.getKey();
        Object fieldValue = entry.getValue();
        try {
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    if (fieldValue == null) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Key) { // child
                        try {
                            Entity e = store.getDatastoreService()
                                    .get((com.google.appengine.api.datastore.Key) fieldValue);
                            AnnotatedField annotatedField = AnnotationUtil
                                    .getFieldWithAnnotation(GaeObjectStore.child(), destination);
                            Object childInstance = store.createInstance(annotatedField.getFieldType());
                            unmarshall(childInstance, e);
                            setFieldValue(field, destination, childInstance);
                        } catch (EntityNotFoundException e) {
                            fieldValue = null;
                        }
                    } else if (fieldValue instanceof String || fieldValue instanceof Boolean
                            || fieldValue instanceof Number || fieldValue instanceof Blob) {
                        if (field.getName().equals(fieldName)) {
                            if (field.getType().isEnum()) {
                                setFieldValue(field, destination,
                                        Enum.valueOf((Class<Enum>) field.getType(), (String) fieldValue));
                            }
                            if (field.getType().equals(String.class)) {
                                setFieldValue(field, destination, String.valueOf(fieldValue));
                            } else if (field.getType().equals(Boolean.class)) {
                                setFieldValue(field, destination, (Boolean) fieldValue);
                            } else if (field.getType().equals(Long.class)) {
                                setFieldValue(field, destination, (Long) fieldValue);
                            } else if (field.getType().equals(Integer.class)) {
                                if (fieldValue.getClass().equals(Long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, (Integer) fieldValue);
                                }
                            } else if (field.getType().equals(int.class)) {
                                if (fieldValue.getClass().equals(Long.class)
                                        || fieldValue.getClass().equals(long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, ((Integer) fieldValue).intValue());
                                }
                            } else if (field.getType().equals(long.class)) {
                                if (fieldValue.getClass().equals(Integer.class)
                                        || fieldValue.getClass().equals(int.class)) {
                                    Integer value = (Integer) fieldValue;
                                    setFieldValue(field, destination, value.longValue());
                                } else {
                                    setFieldValue(field, destination, ((Long) fieldValue).longValue());
                                }
                            } else if (field.getType().equals(boolean.class)) {
                                setFieldValue(field, destination, ((Boolean) fieldValue).booleanValue());
                            } else if (field.getType().equals(byte.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    // TODO: Need to have a second look with this code
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes()[0]);
                                }
                            } else if (field.getType().equals(byte[].class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes());
                                }
                            } else if (field.getType().equals(Date.class)) {
                                if (fieldValue.getClass().equals(String.class)) {
                                    Date date = DateUtil.parseDate((String) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Long.class)) {
                                    Date date = new Date((Long) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Date.class)) {
                                    setFieldValue(field, destination, fieldValue);
                                } else {
                                    throw new RuntimeException(
                                            "Unable to unmarshall " + fieldValue.getClass().getName() + " to "
                                                    + field.getType().getName());
                                }
                            } else if (field.getType().equals(Blob.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob);
                                }
                            }
                        }
                    } else if (fieldValue instanceof Blob) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Text) {
                        Text textField = (Text) fieldValue;
                        setFieldValue(field, destination, textField.getValue());
                    } else if (fieldValue instanceof Date) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof User) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof EmbeddedEntity) { // List or Java  primitive types and standard types, Map or  POJO's
                        Class<?> fieldValueType = fieldValue.getClass();
                        EmbeddedEntity ee = (EmbeddedEntity) fieldValue;
                        Map<String, Object> map = ee.getProperties();
                        store.createInstance(fieldValueType);
                        if (field.getType().equals(List.class) || field.getType().equals(Map.class)) {
                            Object mapOrList = getMapOrList((EmbeddedEntity) fieldValue);
                            setFieldValue(field, destination, mapOrList);
                        } else { // Must be a POJO
                            Map<String, Object> getMap = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue);
                            Object pojo = Maps.fromMap(getMap, field.getType());
                            setFieldValue(field, destination, pojo);
                        }
                    } else if (fieldValue instanceof GeoPt) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof List) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue.getClass().isPrimitive()) {
                        throw new RuntimeException("Not yet implemented");
                    }
                }
            }
        } catch (ClassCastException e) {
            if (fieldName != null && fieldValue != null) {
                LOG.error("Exception while unmarshalling GAE Entity field name=" + fieldName + " type="
                        + fieldValue.getClass().getName() + " value=" + fieldValue);
            }
            throw e;
        }
    }
    AnnotatedField aliasField = AnnotationUtil.getFieldWithAnnotation(Alias.class, destination);
    if (aliasField != null) {
        Alias alias = aliasField.getField().getAnnotation(Alias.class);
        String fieldName = alias.field();
        Object value = props.get(fieldName);

        String actualField = aliasField.getFieldName();
        Object actualValue = props.get(actualField);

        if (value != null) {
            setFieldValue(aliasField.getField(), destination, value);
        } else {
            setFieldValue(aliasField.getField(), destination, actualValue);
        }
    }
}