Not getting data in response for JAXBRepresentation in restlet - jaxb

I am new to web services and currently trying to setup Restlet on Apache Karaf. My Core bundle starts component with Protocol: HTTP. And Port: 8081.
I have created a component in which uses HTTP Protocol and a port number configured via property.
Applications are attached to default host as
wsComponent.getDefaultHost().attach(restletApp.getURI(),restletApp);
In above getURI function returns URL to which application is attached.
I am trying to use JaxbRepresentation to get details. Server Resource class is as follows:
#Get
public Representation getAllUsers()
{
List<MyUser> allUsers = MyFactory.getInstance().getAllUsers();
MyUserListXML userListXML = new MyUserListXML(MyUserConverter.convertMyUserList(allUsers));
JaxbRepresentation<MyUserListXML> userReps = new JaxbRepresentation<MyUserListXML>(userListXML);
userReps.setFormattedOutput(true);
return userReps;
}
MyUserListXML.java:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder={"user"})
#XmlRootElement(name="myUsers")
public class MyUserListXML implements Serializable
{
private static final long serialVersionUID = 1L;
#XmlElement(name="user")
private List<MyUserXML> userList;
public MyUserListXML()
{
// Default Constructor
}
/**
* #param userList
*/
public MyUserListXML(List<MyUserXML> userList)
{
this.userList = userList;
}
/**
* #return the userList
*/
public List<MyUserXML> getUserList()
{
return userList;
}
/**
* #param userList the userList to set
*/
public void setUserList(List<MyUserXML> userList)
{
this.userList = userList;
}
}
MyUserXML.java
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder = {"id","userName","status","displayName","email"})
#XmlRootElement(name = "esmfUser")
public class MyUserXML implements Serializable
{
private static final long serialVersionUID = 1L;
#XmlElement(name= "id", required=true,type=Integer.class)
private Integer userId;
#XmlElement(required=true)
private String userName;
#XmlElement(name="status",required=true)
private String userStatus;
#XmlElement(required=true)
private String displayName;
#XmlElement(required=true)
private String email;
public MyUserXML()
{
// default constructor.
}
/**
* #param userId
* #param userName
* #param userStatus
* #param displayName
* #param email
*/
public MyUserXML(Integer userId, String userName, String userStatus, String displayName, String email)
{
this.userId = userId;
this.userName = userName;
this.userStatus = userStatus;
this.displayName = displayName;
this.email = email;
}
/**
* #return the userId
*/
public Integer getUserId()
{
return userId;
}
/**
* #param userId the userId to set
*/
public void setUserId(Integer userId)
{
this.userId = userId;
}
/**
* #return the userName
*/
public String getUserName()
{
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName)
{
this.userName = userName;
}
/**
* #return the userStatus
*/
public String getUserStatus()
{
return userStatus;
}
/**
* #param userStatus the userStatus to set
*/
public void setUserStatus(String userStatus)
{
this.userStatus = userStatus;
}
/**
* #return the displayName
*/
public String getDisplayName()
{
return displayName;
}
/**
* #param displayName the displayName to set
*/
public void setDisplayName(String displayName)
{
this.displayName = displayName;
}
/**
* #return the email
*/
public String getEmail()
{
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email)
{
this.email = email;
}
}
While testing using soapUI I am getting following request and response
Request:
GET http://localhost:8081/ws/users HTTP/1.1
Accept-Encoding: gzip,deflate
Host: localhost:8081
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Response:
HTTP/1.1 200 OK
Content-encoding: gzip, zip, deflate
Server: Restlet-Framework/2.3.5
Date: Sun, 15 Nov 2015 09:29:31 GMT
Transfer-encoding: chunked
Content-type: application/xml; charset=UTF-8
Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
Accept-ranges: bytes
I am not sure why I am not getting xml data out. Can any one help me or guide me what I am doing wrong.
Restlet version: 2.3.5

I was able to resolve this issue.
I have created ObjectFactory class but changed its name. Due to this JaxbContext was not able to find ObjectFactory class. And since I am using restlet in Osgi and not yet able to figure out how to make Restlet use Osgi Log Service was not seeing any error messages from restlet.

Regarding the issue with JaxB, you should at least see a Warning log trace, and probably a IOException. I have a look at the issue you created (https://github.com/restlet/restlet-framework-java/issues/1166).
If you want to list all log traces from Restlet framework, and actually from any other kind of library that you include in your project and that don't rely on the OSGi LogService, you must configure the logs according to each library requirements (JUL, Log4j, slf4j, etc). As an OSGi container is basically a JVM, there is no issue to configure each logger.
Regarding Restlet Framework, you can read this page: http://restlet.com/technical-resources/restlet-framework/guide/2.3/editions/jse/logging
Some technologies such as slf4j helps to mutualize the different log systems. You should be able to pour all logs into the OSGi LogService, if you want to.

Related

Accessing AzureAD API using google OAuth2 client library for java

My project requires integration with G-Suite and AzureAD directory. Both of them supports OAuth2 as explained here and here.
I want to access G-Suite and AzueAD API with Google OAuth2 client. I have few questions for the same
Is it possible to access AzureAD API using google-oauth-api-client?
Is there any library which can be used with G-Suite SDK and AzureAD?
I don't want to separate library for each provider I integrate. Be it G-Suite or AzureAD or SalesForce or something else which supports OAuth2.
The Google OAuth2 client library can be used to authenticate against any OAuth2 provider by adding the following two classes:
public class ClientUsernamePasswordTokenRequest extends TokenRequest {
/**
* #param transport HTTP transport
* #param jsonFactory JSON factory
* #param tokenServerUrl token server URL
* #param grantType grant type ({#code "authorization_code"}, {#code "password"},
* {#code "client_credentials"}, {#code "refresh_token"} or absolute URI of the extension
*/
public ClientUsernamePasswordTokenRequest(HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, String grantType) {
super(transport, jsonFactory, tokenServerUrl, grantType);
}
#Override
public TokenResponse execute() throws IOException {
return convertStringToObject(executeUnparsed().parseAs(Map.class));
}
private TokenResponse convertStringToObject(Map content) {
TokenResponse tokenResponse = new TokenResponse();
String tokenType = (String) content.get("token_type");
tokenResponse.setTokenType(tokenType);
String scope = (String) content.get("scope");
tokenResponse.setScope(scope);
String accessToken = (String) content.get("access_token");
tokenResponse.setAccessToken(accessToken);
String refreshToken = (String) content.get("refresh_token");
tokenResponse.setRefreshToken(refreshToken);
return tokenResponse;
}
}
and
package com.identityforge.idfserver.backend.rest.auth;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.UrlEncodedContent;
import com.google.api.client.util.Data;
import com.google.api.client.util.Preconditions;
import java.util.Map;
public class ClientParametersAuthentication implements HttpRequestInitializer, HttpExecuteInterceptor {
/**
* Client identifier issued to the client during the registration process.
*/
private final String clientId;
/**
* Client password or {#code null} for none.
*/
private final String password;
/**
* Client username
*/
private final String username;
/**
* Resource for which access is requested
*/
private final String resource;
private final String clientSecret;
/**
* #param clientId client identifier issued to the client during the registration process
* #param password password or {#code null} for none
* #param username
* #param resource
* #param clientSecret
*/
public ClientParametersAuthentication(String clientId, String password, String username, String resource, String clientSecret) {
this.clientId = Preconditions.checkNotNull(clientId);
this.password = Preconditions.checkNotNull(password);
this.username = Preconditions.checkNotNull(username);
this.resource = resource;
this.clientSecret = clientSecret;
}
public void initialize(HttpRequest request) {
request.setInterceptor(this);
}
public void intercept(HttpRequest request) {
Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
data.put("client_id", clientId);
data.put("password", password);
data.put("username", username);
if (resource != null)
data.put("resource", resource);
if (clientSecret != null) {
data.put("client_secret", clientSecret);
}
}
}
Now access token can be requested by providing credentials values in the following code
private void fetchToken() throws IOException {
TokenResponse tokenResponse;
if (genericUrl == null) {
genericUrl = new GenericUrl(tokenUrl);
}
if (authentication == null) {
authentication = new ClientParametersAuthentication(clientId, passwd, username, resource, clientSecret);
}
if (tokenRequest == null) {
tokenRequest = new ClientUsernamePasswordTokenRequest(new ApacheHttpTransport(), JacksonFactory.getDefaultInstance(), genericUrl, grantType);
tokenRequest.setClientAuthentication(authentication);
}
tokenResponse = tokenRequest.execute();
String accessToken = tokenResponse.getAccessToken();
}
Here tokenUrl is the authentication endpoint.

parse json and get attributes with rest controller java

I have this code, the entity is persistable I want to make it non persistable so I parse json file and get name and icon values and display them instead of getting this values from database so that is why I want to change this code
/**
* A Pcomponent.
*/
#Entity
#Table(name = "pcomponent")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Pcomponent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "icon")
private String icon;
#Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public Pcomponent icon(String icon) {
this.icon = icon;
return this;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public Pcomponent name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pcomponent pcomponent = (Pcomponent) o;
if (pcomponent.id == null || id == null) {
return false;
}
return Objects.equals(id, pcomponent.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Pcomponent{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Spring Data JPA repository for the Pcomponent entity.
*/
public interface PcomponentRepository extends
JpaRepository<Pcomponent,Long> {
}
/**
* A DTO for the Pcomponent entity.
*/
public class PcomponentDTO implements Serializable {
private Long id;
private String icon;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PcomponentDTO pcomponentDTO = (PcomponentDTO) o;
if ( ! Objects.equals(id, pcomponentDTO.id)) {
return false;
}
return true;
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "PcomponentDTO{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Mapper for the entity Pcomponent and its DTO PcomponentDTO.
*/
#Mapper(componentModel = "spring", uses = {})
public interface PcomponentMapper {
PcomponentDTO pcomponentToPcomponentDTO(Pcomponent pcomponent);
List<PcomponentDTO> pcomponentsToPcomponentDTOs(List<Pcomponent> pcomponents);
Pcomponent pcomponentDTOToPcomponent(PcomponentDTO pcomponentDTO);
List<Pcomponent> pcomponentDTOsToPcomponents(List<PcomponentDTO> pcomponentDTOs);
/**
* generating the fromId for all mappers if the databaseType is sql, as the class has relationship to it might need it, instead of
* creating a new attribute to know if the entity has any relationship from some other entity
*
* #param id id of the entity
* #return the entity instance
*/
default Pcomponent pcomponentFromId(Long id) {
if (id == null) {
return null;
}
Pcomponent pcomponent = new Pcomponent();
pcomponent.setId(id);
return pcomponent;
}
}
/**
* Service Implementation for managing Pcomponent.
*/
#Service
#Transactional
public class PcomponentService {
private final Logger log =
LoggerFactory.getLogger(PcomponentService.class);
private final PcomponentRepository pcomponentRepository;
private final PcomponentMapper pcomponentMapper;
public PcomponentService(PcomponentRepository pcomponentRepository, PcomponentMapper pcomponentMapper) {
this.pcomponentRepository = pcomponentRepository;
this.pcomponentMapper = pcomponentMapper;
}
/**
* Save a pcomponent.
*
* #param pcomponentDTO the entity to save
* #return the persisted entity
*/
public PcomponentDTO save(PcomponentDTO pcomponentDTO) {
log.debug("Request to save Pcomponent : {}", pcomponentDTO);
Pcomponent pcomponent = pcomponentMapper.pcomponentDTOToPcomponent(pcomponentDTO);
pcomponent = pcomponentRepository.save(pcomponent);
PcomponentDTO result = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return result;
}
/**
* Get all the pcomponents.
*
* #param pageable the pagination information
* #return the list of entities
*/
#Transactional(readOnly = true)
public Page<PcomponentDTO> findAll(Pageable pageable) {
log.debug("Request to get all Pcomponents");
Page<Pcomponent> result = pcomponentRepository.findAll(pageable);
return result.map(pcomponent -> pcomponentMapper.pcomponentToPcomponentDTO(pcomponent));
}
/**
* Get one pcomponent by id.
*
* #param id the id of the entity
* #return the entity
*/
#Transactional(readOnly = true)
public PcomponentDTO findOne(Long id) {
log.debug("Request to get Pcomponent : {}", id);
Pcomponent pcomponent = pcomponentRepository.findOne(id);
PcomponentDTO pcomponentDTO = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return pcomponentDTO;
}
/**
* Delete the pcomponent by id.
*
* #param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete Pcomponent : {}", id);
pcomponentRepository.delete(id);
}
}
/**
* REST controller for managing Pcomponent.
*/
#RestController
#RequestMapping("/api")
public class PcomponentResource {
private final Logger log =
LoggerFactory.getLogger(PcomponentResource.class);
private static final String ENTITY_NAME = "pcomponent";
private final PcomponentService pcomponentService;
public PcomponentResource(PcomponentService pcomponentService) {
this.pcomponentService = pcomponentService;
}
/**
* POST /pcomponents : Create a new pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to create
* #return the ResponseEntity with status 201 (Created) and with body the new pcomponentDTO, or with status 400 (Bad Request) if the pcomponent has already an ID
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PostMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> createPcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to save Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new pcomponent cannot already have an ID")).body(null);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.created(new URI("/api/pcomponents/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /pcomponents : Updates an existing pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to update
* #return the ResponseEntity with status 200 (OK) and with body the updated pcomponentDTO,
* or with status 400 (Bad Request) if the pcomponentDTO is not valid,
* or with status 500 (Internal Server Error) if the pcomponentDTO couldnt be updated
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PutMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> updatePcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to update Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() == null) {
return createPcomponent(pcomponentDTO);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, pcomponentDTO.getId().toString()))
.body(result);
}
/**
* GET /pcomponents : get all the pcomponents.
*
* #param pageable the pagination information
* #return the ResponseEntity with status 200 (OK) and the list of pcomponents in body
*/
#GetMapping("/pcomponents")
#Timed
public ResponseEntity<List<PcomponentDTO>> getAllPcomponents(#ApiParam Pageable pageable) {
log.debug("REST request to get a page of Pcomponents");
Page<PcomponentDTO> page = pcomponentService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/pcomponents");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /pcomponents/:id : get the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to retrieve
* #return the ResponseEntity with status 200 (OK) and with body the pcomponentDTO, or with status 404 (Not Found)
*/
#GetMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<PcomponentDTO> getPcomponent(#PathVariable Long id) {
log.debug("REST request to get Pcomponent : {}", id);
PcomponentDTO pcomponentDTO = pcomponentService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(pcomponentDTO));
}
/**
* DELETE /pcomponents/:id : delete the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to delete
* #return the ResponseEntity with status 200 (OK)
*/
#DeleteMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<Void> deletePcomponent(#PathVariable Long id) {
log.debug("REST request to delete Pcomponent : {}", id);
pcomponentService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}

java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean

I got some isses when try to use a login filter for my JSF, PrimeFaces web application.
Here is the stacktrace:
WARNING: StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean
at com.rdb.filter.AuthorizationFilter.doFilter(AuthorizationFilter.java:50)
AuthorizationFilter class:
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
UserManagedBean auth = (UserManagedBean) req.getSession().getAttribute("staff");
if (auth != null && auth.isLoggedIn()) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/frontend/login.xhtml?faces-redirect=true");
}
}
}
My LoginBean
#ManagedBean
#SessionScoped
public class UserManagedBean extends TblStaff implements Serializable {
private TblStaff staff = null;
private String currentLogin;
private String username;
private String password;
private boolean loggedIn;
private ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
#ManagedProperty(value="#{navigationBean}")
private NavigationBean navigationBean;
/**
* Creates a new instance of UserManagedBean
*
*/
public UserManagedBean() {
super();
}
public String login() {
int isValid = doLogin();
if (isValid == 1) {
StaffBLL staffBLL = new StaffBLL();
staff = staffBLL.getStaffByUsername(username);
setSession("staff", staff);
String destinationUrl = null;
if (staff.getRoleId() == 1) {
loggedIn = true;
setCurrentLogin("admin");
destinationUrl = navigationBean.redirectToBackend();
} else if (staff.getRoleId() == 2) {
loggedIn = true;
setCurrentLogin("manager");
destinationUrl = navigationBean.redirectToManager();
} else if (staff.getRoleId() == 3) {
loggedIn = true;
setCurrentLogin("faculty");
destinationUrl = navigationBean.redirectToFaculty();
}
return destinationUrl;
} else {
return navigationBean.toLogin();
}
}
/**
* Set new session if try to logged in
*
* #param key
* #param value
*/
public static void setSession(String key, Object value) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
session.setAttribute(key, value);
}
/**
* Get session if logged in
*
* #param key
* #return Session
*/
public static Object getSession(String key) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
return session.getAttribute(key);
}
public String logout() {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
return navigationBean.toFrontend();
}
public void logoutAdmin(ActionEvent actionEvent) throws IOException {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
ec.redirect(ec.getRequestContextPath() + "/frontend/index.xhtml?faces-redirect=true");
}
public int doLogin() {
CallableStatement objCall;
SHAConverter hash = new SHAConverter();
int result = -1;
String[] params = new String[3];
params[0] = username;
params[1] = hash.hashBasic(password);
params[2] = null;
try {
objCall = SQLHelper.execute("procLogin", params);
result = objCall.getInt("Result");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return result;
}
#Override
public String getPassword() {
return password;
}
#Override
public void setPassword(String password) {
this.password = password;
}
#Override
public String getUsername() {
return username;
}
#Override
public void setUsername(String username) {
this.username = username;
}
public String getCurrentLogin() {
return currentLogin;
}
public void setCurrentLogin(String currentLogin) {
this.currentLogin = currentLogin;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public void setNavigationBean(NavigationBean navigationBean) {
this.navigationBean = navigationBean;
}
}
And NavigationBean
#ManagedBean
#SessionScoped
public class NavigationBean implements Serializable {
// private static final long serialVersionUID = 1520318172495977648L;
/**
* Redirect to login page.
*
* #return Login page name.
*/
public String redirectToLogin() {
return "/frontend/login.xhtml?faces-redirect=true";
}
/**
* Go to login page.
*
* #return Login page name.
*/
public String toLogin() {
return "/frontend/login.xhtml";
}
/**
* Redirect to backend.
*
* #return Backend page name.
*/
public String redirectToBackend() {
return "/backend/AdminHome.xhtml?faces-redirect=true";
}
/**
* Go to backend page.
*
* #return Backend page name.
*/
public String toBackend() {
return "/backend/AdminHome.xhtml";
}
/**
* Redirect to faculty.
*
* #return Faculty page name.
*/
public String redirectToFaculty() {
return "/frontend/faculty/index.xhtml?faces-redirect=true";
}
/**
* Go to faculty.
*
* #return Faculty page name.
*/
public String toFaculty() {
return "/frontend/faculty/index.xhtml";
}
/**
* Redirect to manager.
*
* #return Manager page name.
*/
public String redirectToManager() {
return "/frontend/manager/index.xhtml?faces-redirect=true";
}
/**
* Go to manager.
*
* #return Manager page name.
*/
public String toManager() {
return "/frontend/manager/index.xhtml";
}
/**
* Redirect to frontend.
*
* #return Frontend page name.
*/
public String redirectToFrontend() {
return "/frontend/index.xhtml?faces-redirect=true";
}
/**
* Go to frontend page.
*
* #return Frontend page name.
*/
public String toFrontend() {
return "/frontend/index.xhtml";
}
}
The stacktrace told me that I can't cast entities to a bean, but I MUST extend TblStaff in my login bean.
Can anyone give me a solution for this?

JSF h:selectonemenu convertor Validation error value is not valid [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I know this has been discussed a lot, and I also tried most of resolution, but I still got this error:
sourceId=comboNewTaskParent[severity=(ERROR 2), summary=(comboNewTaskParent: Validation Error: Value is not valid), detail=(comboNewTaskParent: Validation Error: Value is not valid)]
Here is the code for HTML:
<h:outputLabel value="Parent task" for="comboNewTaskParent" />
<div class="formRight">
<h:selectOneMenu id="comboNewTaskParent" value="#{taskController.parentTask}" converter="#{taskConverter}"
<f:selectItems value="#{comboTaskByProject}" var="task" itemValue="#{task}" itemLabel="#{task.taskName}" />
</h:selectOneMenu>
</div>
Here is the code of my entity bean:
package com.projectportal.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the Task database table.
*
*/
#Entity
#Table(name="Task")
public class Task implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(unique=true, nullable=false, length=36)
private String taskId;
#Column(length=1000)
private String taskDesc;
#Column(nullable=false)
private int taskDurationHour;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskEstimated;
#Column(nullable=false, length=200)
private String taskName;
#Column(nullable=false)
private float taskPercentComplete;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable=false)
private Date taskStartDate;
//bi-directional many-to-one association to Priority
#ManyToOne
#JoinColumn(name="priorityId", nullable=false)
private Priority priority;
//bi-directional many-to-one association to Project
#ManyToOne
#JoinColumn(name="projectId")
private Project project;
//bi-directional many-to-one association to Status
#ManyToOne
#JoinColumn(name="statusId", nullable=false)
private Status status;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="parentTaskId")
private Task parentTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="parentTask")
private List<Task> childTasks;
//bi-directional many-to-one association to Task
#ManyToOne
#JoinColumn(name="preTaskId")
private Task preTask;
//bi-directional many-to-one association to Task
#OneToMany(mappedBy="preTask")
private List<Task> dependentTasks;
//bi-directional many-to-one association to UserXTask
#OneToMany(mappedBy="task")
private List<UserXTask> userXtasks;
public Task() {
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskDesc() {
return this.taskDesc;
}
public void setTaskDesc(String taskDesc) {
this.taskDesc = taskDesc;
}
public int getTaskDurationHour() {
return this.taskDurationHour;
}
public void setTaskDurationHour(int taskDurationHour) {
this.taskDurationHour = taskDurationHour;
}
public Date getTaskEstimated() {
return this.taskEstimated;
}
public void setTaskEstimated(Date taskEstimated) {
this.taskEstimated = taskEstimated;
}
public String getTaskName() {
return this.taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public float getTaskPercentComplete() {
return this.taskPercentComplete;
}
public void setTaskPercentComplete(float taskPercentComplete) {
this.taskPercentComplete = taskPercentComplete;
}
public Date getTaskStartDate() {
return this.taskStartDate;
}
public void setTaskStartDate(Date taskStartDate) {
this.taskStartDate = taskStartDate;
}
public Priority getPriority() {
return this.priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
public Status getStatus() {
return this.status;
}
public void setStatus(Status status) {
this.status = status;
}
public Task getParentTask() {
return this.parentTask;
}
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
public List<Task> getChildTasks() {
return this.childTasks;
}
public void setChildTasks(List<Task> childTasks) {
this.childTasks = childTasks;
}
public Task getPreTask() {
return this.preTask;
}
public void setPreTask(Task preTask) {
this.preTask = preTask;
}
public List<Task> getDependentTasks() {
return this.dependentTasks;
}
public void setDependentTasks(List<Task> dependentTasks) {
this.dependentTasks = dependentTasks;
}
public List<UserXTask> getUserXtasks() {
return this.userXtasks;
}
public void setUserXtasks(List<UserXTask> userXtasks) {
this.userXtasks = userXtasks;
}
}
The controller:
public #Model class TaskController {
#Inject private EntityManager em;
#Inject Identity identity;
#Inject Logger log;
#Inject Event<Task> taskEventSrc;
#Named
#Produces
private List<Task> requestTaskList;
private Task parentTask;
private Task newTask;
#Produces
#Named
public Task getNewTask(){
return this.newTask;
}
/**
*
*/
public TaskController() {
// TODO Auto-generated constructor stub
}
#PostConstruct
public void loadSelfTasks(){
// Init
newTask = new Task();
// Get user from DB.
User user = em.find(User.class, identity.getUser().getId());
requestTaskList = new ArrayList<Task>();
// Loop user's tasks.
for(UserXTask userTask : user.getUserXtasks()){
requestTaskList.add(userTask.getTask());
}
log.info("Tasks for user: " + user.getFirstname() + " loaded.");
}
/**
* Create task.
* #throws Exception
*/
public void createTask() throws Exception{
log.info("Persistencing task: " + newTask.getParentTask().getTaskId());
em.persist(newTask);
taskEventSrc.fire(newTask);
newTask = new Task();
}
/**
* #return the parentTask
*/
public Task getParentTask() {
return parentTask;
}
/**
* #param parentTask the parentTask to set
*/
public void setParentTask(Task parentTask) {
this.parentTask = parentTask;
}
}
And of course the converter:
#Named
/**
* #author lastcow
*
*/
public class TaskConverter implements Converter {
#Inject EntityManager em;
#Inject Logger log;
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String)
*/
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
log.info("=========== Convert to Object " + value);
if(value.equals("0")){
return null;
}
Task t = em.find(Task.class, value);
log.info("======== Got : " + t.getTaskName());
return t;
}
/* (non-Javadoc)
* #see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
*/
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
log.info("=========== Convert to String " + value);
return ((Task)value).getTaskId();
}
}
from what logged, the convert are working as it, but when I try to submit the form, always throw 'Validation Error: Value is not valid' ERROR, I have struck here for almost 2 days.
Anyone please give some suggestions.
BTW, I tried put equals and hashCode in Task.java, doesn't working either.
Thanks in advance.
Validation Error: Value is not valid
This error will be thrown when the equals() method of the selected item hasn't returned true for any of the available items in <f:selectItem(s)>. Thus, this can technically have only 2 causes:
The equals() method of your Task class is missing or broken.
The <f:selectItems value="#{comboTaskByProject}"> has incompatibly changed during the postback request of the form submit as compared to during the initial request of the form display.
To fix cause #1, make sure that you understand how to implement equals() properly. You can find kickoff examples here: Right way to implement equals contract
To fix cause #2, make sure that the #{comboTaskByProject} never canges during postback. Best is to put it in the view scope or broader, or to make sure that request based conditions for populating that list are preserved in the postback request by e.g. using <f:viewParam>.
See also:
Our selectOneMenu wiki page
Validation Error: Value is not valid
I am not sure which version of JSF you are using. As far as I know, the converter in HTML should be used like this converter="javax.faces.DateTime". Where this part javax.faces.DateTime is converter name defined in faces-config.xml or in converter class with #FacesConverter.

how to connect to couchdb database using couchdb4j api with username and password?

I am using couchdb4j api to establish a connection through session object with couchdb(version 0.11.2).
Couchdb database is protected with username and password,
trying to establish connection with
Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) constructor by providing host,port,user,pass and usersAuth true, secure false,
but it is unable to establish a connection with username and password and giving a warning Authentication error: Unable to respond to any of these challenges: {}.
I used correct username and password.
Try a CouchDB lib that is actively maintained http://www.ektorp.org/ instead.
I solved the same issue by writing a simple Curl class that simplified the communication and return JSON in String form, since that is what is returned.
It should be self explanatory and you can read the main method for hints.
package path.to.the.class;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import Log;
/**
* This class takes on the simple task of doing http calls to any http web service like a web page or alike. Since the
* class is streamlined for JSON use this is the most easiest to set up.
*
* #author mikael.p.larsson#epsilon.nu
*
*/
public class Curl {
private Map<String, String> requestProperties = null;
private String charsetName = "UTF8";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String POST = "POST";
public static final String HEAD = "HEAD";
public static final String DELETE = "DELETE";
/**
* This is the default constructor for Curl which takes it for granted that you want to communicate and read JSON.
* Most of the times this approach works even if plain html or text is requested.
*/
public Curl() {
requestProperties = new HashMap<String, String>();
requestProperties.put("Content-Type", "application/json");
}
/**
* With this alternate constructor a map containing header strings can be provided, useful if something apart from
* JSON is to be consumed.
*
* #param requestProperties
* a Map containing the header strings.
*/
public Curl(Map<String, String> requestProperties) {
this.requestProperties = requestProperties;
}
/**
* Public setter to enable setting charsetName.
*
* #param charsetName
* #return this instance to enable on liners.
*/
public Curl setCharsetName(String charsetName) {
this.charsetName = charsetName;
return this;
}
/**
* In the world of the web this is the command that a web browser does for you after you have entered an url into
* the address field. When using GET there should be no side effects on the site the data was requested from; the
* get method only consumes data and sends nothing.
*
* #param urlAsString
* the url to fetch from the internet.
* #return The response from the server
*/
public String get(String urlAsString) {
return doHttpCall(urlAsString, GET, null);
}
/**
* Put should be used when a resource should be sent to a server.
*
* #param urlAsString
* the url to the resource.
* #param doc
* the content to put
* #return The response from the server.
*/
public String put(String urlAsString, String doc) {
return doHttpCall(urlAsString, "PUT", doc);
}
/**
* Post should be used when a resource should be posted to a server.
*
* #param urlAsString
* the url to the resource.
* #param doc
* the content to put
* #return The response from the server.
*/
public String post(String urlAsString, String doc) {
return doHttpCall(urlAsString, "POST", doc);
}
/**
* Mostly to be considered as a get without the contents, Here implemented as an is the resource available function.
*
* #param urlAsString
* the url to the resource.
* #return The responseMessage from the server.
*/
public String head(String urlAsString) {
return doHttpCall(urlAsString, "HEAD", null);
}
/**
* Deletes a resource from an url. Be careful!
*
* #param urlAsString
* The url to the resource to delete.
* #return The response from the server.
*/
public String delete(String urlAsString) {
try {
return doHttpCall(urlAsString, "DELETE", null);
} catch (Exception e) {
Log.warn("No object to delete found at " + urlAsString + ".");
return "No object to delete found at " + urlAsString + ".";
}
}
/**
* This method does the actual HTTP communication to simplify the methods above.
*
* #param urlAsString
* The url to resource in question.
* #param method
* The method to be used.
* #param doc
* The resource to send or null if none.
* #return The response from the server.
*/
private String doHttpCall(String urlAsString, String method, String doc) {
StringBuffer result = new StringBuffer();
HttpURLConnection httpUrlConnection = null;
try {
URL url = new URL(urlAsString);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod(method);
if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
httpUrlConnection.setRequestProperty("Authorization", basicAuth);
}
httpUrlConnection.setRequestProperty("Content-Length", "0");
for (String key : requestProperties.keySet()) {
httpUrlConnection.setRequestProperty(key, requestProperties.get(key));
}
if (doc != null && !doc.isEmpty()) {
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestProperty("Content-Length", "" + doc.getBytes(charsetName));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpUrlConnection.getOutputStream(),
charsetName);
outputStreamWriter.write(doc);
outputStreamWriter.close();
}
readInputStream(result, httpUrlConnection.getInputStream());
} catch (RuntimeException e) {
Log.info(e.getMessage());
} catch (MalformedURLException e) {
Log.warn("The url '" + urlAsString + "' is malformed.");
} catch (IOException e) {
try {
result.append(e.getMessage());
readInputStream(result, httpUrlConnection.getErrorStream());
if ("".equals(result.toString())) {
result.append("Error ");
result.append(httpUrlConnection.getResponseCode());
result.append(" : ");
result.append(httpUrlConnection.getResponseMessage());
result.append(". Exception message is: [");
result.append(e.getMessage());
result.append("]");
}
} catch (IOException e1) {
}
} finally {
if ("HEAD".equalsIgnoreCase(method)) {
try {
result.append(httpUrlConnection.getResponseMessage());
} catch (IOException e) {
Log.fatal("This is as low as we can get, nothing worked!");
e.printStackTrace();
}
}
if (httpUrlConnection != null)
httpUrlConnection.disconnect();
}
return result.toString();
}
/**
* Local helper method that reads data from an inputstream.
*
* #param result
* The read text.
* #param inputStream
* The stream to read.
* #throws UnsupportedEncodingException
* #throws IOException
*/
private void readInputStream(StringBuffer result, InputStream inputStream) throws UnsupportedEncodingException,
IOException {
if (inputStream == null)
throw new IOException("No working inputStream.");
InputStreamReader streamReader = new InputStreamReader(inputStream, charsetName);
BufferedReader bufferedReader = new BufferedReader(streamReader);
String row;
while ((row = bufferedReader.readLine()) != null) {
result.append(row);
result.append("\n");
}
bufferedReader.close();
streamReader.close();
}
/**
* A main method to provide the possibility to use this exact class from the command line.
* <p>
* usage:
* <code>java -cp target/classes/. path.to.the.class.Curl http://server.domain.nu:port/path/to/resource method [data]</code>
* </p>
*
* #param args
* in order: url method data
*/
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("usage: Curl path method [data]");
System.exit(0);
}
String url = args[0];
String method = args[1];
String data = args.length == 3 ? args[2] : null;
Curl curl = new Curl();
if (method.equals("head")) {
System.out.println(curl.head(url));
System.exit(0);
}
if (method.equals("put")) {
System.out.println(curl.put(url, data));
System.exit(0);
}
System.out.println(curl.doHttpCall(url, method, data));
}
}
Try change configuration parameter required_valid_user to true

Resources