Appending data to PrimeFaces' dataTable using Ajax - ajax

I'm trying to use another way of pagination in PrimeFaces' DataTable.
What I want to do is that new pages are shown "vertically", so the new loaded data has to be appended at the end of the previous DataTable.
Something like Facebook's home stream, in which clicking "Load old posts" will make them appear under the newest one.
Is this possible??
I've tried almost everything using paginator, but seems like there's no way to build a "vertical" dataTable.
If not with PrimeFaces, is there any component that does what I need?
The loading should be lazy, so, everytime that the user decides to load the new data, a query must be executed. No lists or something!
Thanks :)
EDIT:
JSF Page
<pou:dataTable scrollable="true" liveScroll="true" scrollHeight="400" scrollRows="100" value="#{postListBean_1.posts}" var="post">
<pou:column>
#{post.testo}
<hr/>
</pou:column>
</pou:dataTable>
BEAN
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ManagedBeans;
import ejb.PostManagerLocal;
import entity.Post;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
* La classe si occupa di gestire lo scambio di messaggi tra utenti. Da
* implementare ancora i metodi per l'invio e per la segnalazione dell'avvenuta
* lettura.
*
* #author stefano
*/
#ManagedBean
#RequestScoped
public class PostListBean_1 implements Serializable {
#EJB
private PostManagerLocal postManager;
private List<Post> posts;
private int limit = 0;
/**
* Get the value of posts
*
* #return the value of posts
*/
public List<Post> getPosts() {
limit+=4;
makePosts();
return posts;
}
/**
* Set the value of posts
*
* #param posts new value of posts
*/
public void setPosts(List<Post> posts) {
this.posts = posts;
}
/**
* Creates a new instance of PostListBean
*/
public PostListBean_1() {
}
/**
* Inizializza la lista dei posts, prendendoli in ordine inverso, in modo da
* avere prima i più recenti
*/
#PostConstruct
public void makePosts() {
int[] range = {0, limit};
posts = postManager.findRangeReverse(range);
}
}

Related

Sort awt Rectangle by Surface Area using Comparable

This code compares awt rectangles by surface area but I am getting an error when I use collections.sort. I want it to output a sorted ArrayList of awt rectangles based on their surface area.
surface area = width * height.
I have created a sorting class and extended the comparable interface and I am calling/invoking this class as a parameter in Collections.sort(rectangleList, new SortBySurfaceArea());, however when I put a cursor over collections.sort, I get this pop-up error.
no suitable method found for sort(List<Rectangle>,SortBySurfaceArea)
method Collections.<T#1>sort(List<T#1>) is not applicable
(cannot infer type-variable(s) T#1
(actual and formal argument lists differ in length))
method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(argument mismatch; SortBySurfaceArea cannot be converted to Comparator<? super T#2>))
where T#1,T#2 are type-variables:
T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
(Alt-Enter shows hints)
Code listing follows:
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author HP
*/
public class RectangleSurfaceAreaComparable {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Rectangle rectangle_0 = new Rectangle(50, 4);
Rectangle rectangle_1 = new Rectangle(80, 3);
Rectangle rectangle_2 = new Rectangle(90, 2);
System.out.println(surfaceArea(rectangle_0.getWidth(), rectangle_0.getHeight()));
List<Rectangle> rectangleList = new ArrayList<>();
rectangleList.add(rectangle_0);
rectangleList.add(rectangle_1);
rectangleList.add(rectangle_2);
for (Rectangle rectangle : rectangleList) {
System.out.println("" + rectangle);
}
Collections.sort(rectangleList, new SortBySurfaceArea());
for (Rectangle rectangle : rectangleList) {
System.out.println("" + rectangle);
}
}
/**
*
* #param width
* #param height
* #return
*/
public static double surfaceArea(double width, double height) {
double sa = width * height;
return sa;
}
}
SortBySurfaceArea.java
import java.awt.Rectangle;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author HP
*/
public class SortBySurfaceArea implements Comparable<Rectangle> {
#Override
public int compareTo(Rectangle o) {
return (o.height * o.width);
}
}
Collections.sort needs a Comparator, not a Comparable, so your SortBySurfaceArea could be:
import java.awt.Rectangle;
import java.util.Comparator;
public class SortBySurfaceArea implements Comparator<Rectangle>
{
public int compare(Rectangle o1, Rectangle o2)
{ return o1.height*o1.width-o2.height*o2.width; }
}
No I want to use comparable
How about this? (You might want to call SortBySurfaceArea differently, e. g. SortableRectangle.)
import java.awt.Rectangle;
public class SortBySurfaceArea extends Rectangle implements Comparable<Rectangle>
{
public SortBySurfaceArea(Rectangle r) { super(r); }
public int compareTo(Rectangle o) { return height*width-o.height*o.width; }
}
…
List<SortBySurfaceArea> rectangleList = new ArrayList<>();
rectangleList.add(new SortBySurfaceArea(rectangle_0));
rectangleList.add(new SortBySurfaceArea(rectangle_1));
rectangleList.add(new SortBySurfaceArea(rectangle_2));
…
Collections.sort(rectangleList);

"Cannot resolve symbol" error while implementing method to get data from logged jhipster user

I am a newbie at Java programming and Jhipster framework and maybe my question is an annoying one, but despite the many topics I read on it I can't solve my question. So, I am asking for some help.
In this topic getting the current logged in user in JHipster I found this piece of code:
final Optional<User> isUser = userService.getUserWithAuthorities();
if(!isUser.isPresent()) {
log.error("User is not logged in");
return new Shinything()
}
final User user = isUser.get();
// continue with the user
which is exactly what I need in my class NjdUserConfiguration.java: this class contains a field (User) user and I aim to get NjdUserConfiguration retrieved by logged in user login.
So, firstly, I add to NjdUserConfigurationRepository.java this query annotation:
#Query("select njd_user_configuration from NjdUserConfiguration njd_user_configuration where njd_user_configuration.user =:user")
Optional<NjdUserConfiguration> findOneByUser(#Param("user") User user);
Secondly, I create NjdUserConfigurationService.java like this:
package it.tal.app.service;
import it.tal.app.domain.NjdUserConfiguration;
import it.tal.app.domain.User;
import it.tal.app.repository.NjdUserConfigurationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing NdjUserConfiguration.
*/
#Service
#Transactional
public class NjdUserConfigurationService {
private final Logger log = LoggerFactory.getLogger(NjdUserConfigurationService.class);
private final NjdUserConfigurationRepository NjdUserConfigurationRepository;
public NjdUserConfigurationService(NjdUserConfigurationRepository njdUserConfigurationRepository) {
this.NjdUserConfigurationRepository = njdUserConfigurationRepository;
}
/**
* Get one NdjUserConfiguration by user.
*
* #param user the user of the entity
* #return the entity
*/
#Transactional(readOnly = true)
public Optional<NjdUserConfiguration> findOneByUser(User user) {
log.debug("Request to get NdjUserConfiguration : {}", user);
return NjdUserConfigurationRepository.findOneByUser(user);
}
}
Thirdly, I tried to used it in NjdUserConfiguration.java mocking the original code in this new method:
public NjdUserConfiguration getCurrentUser() {
Optional<User> isUser = new UserService.getUserWithAuthorities();
if(isUser.isPresent()) {
//final User user = isUser.get();
return new NjdUserConfigurationService.getOneByUser(isUser.get());
} else {
return null;
}
}
No matter my efforts both getUserWithAuthorities() and getOneByUser(isUser.get()) result in "cannot resolve symbol getUserWithAuthorities()" and "cannot resolve symbol getOneByUser()", though both
import it.tal.app.service.NjdUserConfigurationService;
import it.tal.app.service.UserService;
are present. What did I do so badly or what am I missing?
Thank you
You misuse new operator. Instead of
return new UserService.getUserWithAuthorities();
use
return UserService.getUserWithAuthorities();
assuming UserService is an injected bean.
BTW, java code conventions recommend naming variables so they start with lowercase letter.

Create contracts in laravel 5.4

Documentation on laravel.com is not sufficient. Can any one guide me through how to How To Create contracts in Laravel from scratch.
I need implementation of Contracts in Laravel. Right now, I'm using Laravel 5.4
Contract is just a fancy name for php interfaces. We have being using them all along and its not a new thing.
Contracts/Interfaces help us to maintain a loosely coupled code base. See the example from doc below.
<?php
namespace App\Orders;
class Repository
{
/**
* The cache instance.
*/
protected $cache;
/**
* Create a new repository instance.
*
* #param \SomePackage\Cache\Memcached $cache
* #return void
*/
public function __construct(\SomePackage\Cache\Memcached $cache)
{
$this->cache = $cache;
}
/**
* Retrieve an Order by ID.
*
* #param int $id
* #return Order
*/
public function find($id)
{
if ($this->cache->has($id)) {
//
}
}
}
Here when ever the Repository instantiate we should give a \SomePackage\Cache\Memcached instance in order for code to work. Hence our code is tightly coupled with \SomePackage\Cache\Memcached. Now look at below code.
<?php
namespace App\Orders;
use Illuminate\Contracts\Cache\Repository as Cache;
class Repository
{
/**
* The cache instance.
*/
protected $cache;
/**
* Create a new repository instance.
*
* #param Cache $cache
* #return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}
Same thing but now we just need to provide some cache interface. And behind the scene you could have done something like this.
<?php
namespace App\Orders;
use Illuminate\Contracts\Cache\Repository as Cache;
class RedisCache implements Cache {
//
}
When above Repository instantiate, php will look at the Illuminate\Contracts\Cache\Repository and It has been implemented by RedisCache class.
I'm afraid Gayan's answer needs further elaboration to hit Rajan's question.
Yes Gayan is correct that creating a Contract class basically means creating a php interface.
Continuing the Cache example above, if we look into its source code (you can find it at this Github repo file), we can see something like this
<?php
namespace Illuminate\Contracts\Cache;
use Closure;
interface Repository
{
/**
* Determine if an item exists in the cache.
*
* #param string $key
* #return bool
*/
public function has($key);
/**
* Retrieve an item from the cache by key.
*
* #param string $key
* #param mixed $default
* #return mixed
*/
public function get($key, $default = null);
// the rest...
}
If we are using this interface in our laravel app, it is said to be a "Contract". It is declaring what methods/properties a class should have if it implements this interface. For example in our app...
<?php
namespace App\Whatever;
use Illuminate\Contracts\Cache\Repository;
class Foo implements Repository {
//
}
Then class Foo will need to have methods has and get in order to fulfil what has been stated in the Repository contract.

Geoserver source code: Where do the methods in classProperties.java come from

I try to understand the geoserver source code and therefore play around with it. For my task I want to find out where I can find the "methods" stated in the code below from the ClassProperties.java class in the org.geoserver.ows.util package. When printing the methods.getname() out I get this response:
List item
indexOf
indexOf
isFrozen
getMap
map
getCapabilities
getStyles
getLegendGraphic
capabilities
Although clazz.getMethods() gets these methods I can't find them in the code. where does Class clazz.getMethods() get them from?
ClassProperties.java
/* (c) 2014 Open Source Geospatial Foundation - all rights reserved
* (c) 2001 - 2013 OpenPlans
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.ows.util;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Provides lookup information about java bean properties in a class.
*
* #author Justin Deoliveira, OpenGEO
* #author Andrea Aime, OpenGEO
*
*/
public class ClassProperties {
private static final List<Method> EMPTY = new ArrayList<Method>(0);
private static final Set<String> COMMON_DERIVED_PROPERTIES = new HashSet<>(
Arrays.asList("prefixedName"));
List<Method> methods;
List<Method> getters;
List<Method> setters;
public ClassProperties(Class clazz) {
methods = Arrays.asList(clazz.getMethods());
From the class that's passed as a parameter to ClassProperties(Class clazz).
Obviously depending on the class, you'll get different methods.
The usage is simple:
ClassProperties cp = new ClassProperties(String.class);
ClassProperties cp2 = new ClassProperties(cp.getClass());
The first one would access String's methods, the second one would access the class' own methods.
If you can't see the class name in any way, the only way to find the class would be to search for all classes and check whether they have the same methods (not a very good idea).

Model validation Symfony2

I have read how to validate forms in server side with sf2. The solution is by using the Constraints in the Entity as annotations, validation.yml or inside the EntityType (Form).
Everything is fine, however, all of these validations work just with the form. But when you instance a new object and try to persist, validation doesn't work.
I will give you an example.
Imagine I have a user entity:
/**
* #ORM\Entity
* #ORM\Table(name="sf_user")
*/
class User{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column( name="username", type="string", length=50, unique=true )
*/
protected $username;
/**
* #var string
* #ORM\Column( name="email", type="string", length=100, unique=true )
*/
protected $email;
public static function loadValidatorMetadata(\Symfony\Component\Validator\Mapping\ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('username', new \Symfony\Component\Validator\Constraints\NotBlank());
$metadata->addPropertyConstraint('email', new \Symfony\Component\Validator\Constraints\NotNull());
}
}
Then, in some controller I try to save my form with:
$this->form = $this->create(new UserType());
$this->form->setData(new User());
$this->form->bind($this->request);
if( $this->form->isValid())
{
//Persist with entity manager
}
Everything works perfectly because I have an association between my Entity and my form. But what happen if i need to instance an object without a form?. I should do something like this:
$user = new User();
$user->setUsername("username");
//Persist with entity manager
If I do that, entity is not validated and DB throws an error because the field "email" is required.
Should I always associate my entity with the form to validate? If that is the case, I don't agree at all because if I am working with web services, I don't wanna create a form just to validate on the server side.
So, how could I do this validation?. Thanks for your help.
You can use the validation service
$validator = $this->get('validator');
$validator->validate($user);
see the docs about this.
By the way there is a cleaner way to specify validation in you entity.
use Symfony\Component\Validator\Constraints as Assert;
class User{
/**
* #Assert\NotNull
*/
protected $username;
/**
* #Assert\NotBlank
* #Assert\Email
*/
protected $email;

Resources