When trying to test with SOAP UI..I coudn't get correct output for :
public String registerUserByuser(String user)
public String getAllUsers(String userNames)
User.java
package com.ws.entity;
public class User implements java.io.Serializable{
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
private String userName;
private int userId;
}
===============================================================================
RegistrationService.java
package com.ws.Service;
import com.ws.entity.User;
public interface RegistrationService {
String registerUserByuser (String user);
User getuserNameById(int Id );
String getAllUsers (String userNames);
}
===============================================================================
RegistrationServiceImpl.java
package com.ws.test;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.ws.Service.RegistrationService;
import com.ws.entity.User;
#WebService(name = "UserWS", serviceName="RegService", portName = "CustomerPort", targetNamespace = "http://www.reg.com")
public class RegistrationServiceImpl implements RegistrationService {
#WebMethod
#Override
public String registerUserByuser(String user) {
// TODO Auto-generated method stub
User u = new User();
u.setUserId(555);
u.setUserName("Keith");
return user;
}
#WebMethod
#Override
public User getuserNameById(int Id) {
// TODO Auto-generated method stub
User a = new User();
a.setUserId(888);
a.setUserName("Seth");
return a;
}
#WebMethod
#Override
public String getAllUsers(String userNames) {
return userNames;
// TODO Auto-generated method stub
}
}
Requirement is to develop Bottom Up WebServices:
UserRegistration - Interface
method 1 - registerUser that takes user as input and sends String as output
method 2- getUser that takes id as input and returns back user object
method 3 - getAllusers that returns list of users back to user
Am I writing code in incorrect way?
Your code seems more a mockup than an actual implementation. You are hardcoding the user you return in the getuserNameById method and you also have the mistake pointed out by Invexity in the getAllUsers method.
You need some form of persistence. For prototyping, you could just add a List attribute to your class, to store the users you create. Something like:
private List<User> users = new ArrayList<User>();
and in the registerUserByUser method do something like:
this.users.add(user);
Finally, in the getAllUsers method, you could just:
return this.users;
However, if this is some sort of mockup or test, it would be alright I guess. But if you are building production code, you need to read some more about webservices, persistence and security (given the fact that your domain is about users). This code is definitely not suitable for production for many reasons (hardcoding, lack of actual persistence, security of data, to name a few).
Related
I have a class called User.java
public class User {
public User(Context context) {
}
public User() {
}
public void getUserId(){
}
public void getUserName(){
}
}
If I create an object of user class then I can reach to all methods such as getUserId and getUserName
User user_1 = new User(this);
user_1.getUserId();
user_1.getUserName();
User user_2 = new User();
user_2.getUserId();
user_2.getUserName();
The main question is can I get getUserName only if I called a constructor that has one parameter? But if I call a constructor that does not have a parameter then I can't get getUserName. Is it possible in Java?
There are multiple ways to achieve (roughly) what you want.
The easy, but possibly annoying way is to throw an Exception whenever a "forbidden" method is called:
public String getUserName(){
if (someRequiredContext == null) {
throw new IllegalStateException("method not allowed!");
}
// do stuff
}
This "works", but doesn't help the user avoid calling those methods, since there's no easy way for them to know if they can call getuserName on a given User object.
The more involved version would be to have two classes (for example User and UserWithContext), but then you can't instantiate them the right way. But you could use factory methods instead of constructors:
public abstract class User {
User() { ... };
public static User createUser() {
return new BasicUser();
};
public static UserWithContext createUser(Context context) {
return new UserWithContext(context);
}
public String getId() { ... }
}
class BasicUser extends User { // this class need not be public!
}
public class UserWithContext extends User {
UserWithContext(Context context) { ... }
public String getuserName() { ... };
}
This way the type will inform the users of your API which methods are allowed with a given User object.
No, it is not possible. But you could use interfaces to say for instance LimitedUser and FullUser
public interface LimitedUser {
int userId();
}
public interface FullUser extends LimitedUser {
String getUsername();
}
Then use factory methods on for instance the User implementation
public class User implements FullUser {
private final int id;
private final String username;
private User(int id, String username) {
this.id = id;
this.username = username;
}
public static LimitedUser createLimitedUser(int id) {
return new User(id, null);
}
public static FullUser createFullUser(int id, String username) {
return new User(id, username);
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
}
I'm writing a program which consists of multiple classes. One class is called "User" and the other one is called "userGroup". I'm trying to import a variable which is contained within a constructor from the User class and use it in the userGroup class.
I've tried the following code:
User userRetrieve = new User();
userRetrieve.User();
This code doesn't seem to work, although I have seen in various tutorials that this is how you would retrieve data from another class. The second line has ".User()" because the constructor is also called User but I am not sure if this is correct and even if it was the initial problem of the program not recognizing the first line would still remain.
I'll show the code form both classes for extra information which may show where I have gone wrong:
User class:
public class User {
String username;
String userType;
String name;
public User() {
username = "x";
userType = "y";
name = "z";
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
userGroup class:
import java.util.ArrayList;
public class userGroup {
String User;
ArrayList<User> userArray = new ArrayList<>();
Integer user0;
public void addSampleData() {
userArray.add(new User());
}
public void getUser(User user0) {
user0 = userArray.get(0);
}
public void printusername() {
System.out.println(user0.getUserName()); // x
}
}
I'm trying to use the username and userType variables in the constructor from the User class.
P.S Apologies for any formatting/indentation errors.
You have misunderstrood some concepts. Firstly the User() method is the constructor so when you do User user = new User() that method is called. I suggest this change to your user class
public class User {
private String username;
private String userType;
private String name;
// Use constructor to pass data to your class
public User(String username, String userType, String name) {
this.username = username;
this.userType = userType;
this.name = name;
}
public String getUsername() {
return username;
}
public String getUserType() {
return userType;
}
public String getName() {
return name;
}
public String setUserType(String admin) {
return userType = admin;
}
}
Now you can create your array and add a user, then retrieve its information
List<User> users = new ArrayList<User>();
users.add(new User("x", "y", "z"));
users.get(0).getUsername(); // returns "x"
Make a list of users
List<User> users = new ArrayList<User>()
Add a user
users.add(new User());
Get a user (lists and arrays are zero-indexed)
User user0 = users.get(0);
Print some properties
System.out.println(user0.getUserName()); // x
You could use the get methods you created in the constructor class?
So if you want to get the username and the userType just create a new variable using the get method
User userRetrieve = new User();
String username = userRetrieve.getUsername();
String userType = userRetrieve.getUserType();
Or alternatively you could just directly access the variables:
User userRetrieve = new User();
String username = userRetrieve.username;
String userType = userRetrieve.userType;
User userRetrieve = new User();
On this line you are instantiating a new object of type Person,
you do this by calling the constructor associated with this particular class.
After you have done this it is possible to acces parameters by calling the various methods you have defined in the Person class. So in your case you should use userRetrieve.getUsername() and so on.. you will however need to declare a variable in the calling class to store these values in.
I am developing a java-spring project and I have a packagegr.serafeim.domain which contains all my domain classes (for instance, Student, School etc - they are concrete classes). All these have relations between them through JPA annotations. Until now everything was fine, but now I need to implement methods to these classes that would need to query the database to get their results.
How should I implement these methods ? My first choice would be to put it inside the domain classes, however in order to do that I'd need to include references to the data repositories in all my domain classes. I don't like this very much -- is this a good design choice ? Should I implement interfaces that my domain classes would implement ? Can you propose a better solution -- what is the common practice in such cases ?
TIA
My answher: no, don't place references to repositories into you domain models. Place them into business services instead. And don't manage any security into domain at all. Security is refered to use cases, not domain logic, so security is placed over domain.
And I disagree with Sandhu. I'd use the following architecture:
Model classes. They don't get getters/setters for everything. It depends on model logic. Otherwise you get model where you can easily break consistency. Or where are many unobvious things. Suppose you have User.registrationDate field. When you construct a new User object, you should not forget to field registrationDate field by hands. So, just place registrationDate initialization in your constructor and remove setter!
Repository interface just inside your model. Suppose you have some business logic that depends on existing stored objects. You can't expliciltly refer from your domain logic into infrastructure dependencies like JPA, Hibernate, JDBC, etc. So you query this stored objects from interfaces.
Business services (optionally). They implement some complex logic, involving many different entities, not including security and transaction management. Your question is about it. Yes, if you need query for entities in your domain logic, place query into repository and call it from your business service.
Repository implementation inside infrastructure package. Implements repository interfaces using JPA or mockito or whatever else. They also don't include neither security nor transactions.
Application services (optionally). If there is some complex interaction with infrastructure or security checking.
Remote facade interface. Client and server communicate only through remote facade interface.
Remote facade implementation (controller). Transforms thick entity objects into thin DTOs (data transfer objects). All transaction demarcation and security is here (often using annotations).
This approach conforms DDD style, described by Martin Fowler. I think that JPA is musused in most of modern projects. It is used not as persistence provider, but as active record. Active record is not domain model implementation pattern, but database abstraction pattern. So if you really want transaction script approach, use some active record library or something like MyBatis instead of heavyweight JPA provider.
Also I don't understand the need of DAO. JPA providers do data abstraction themselves, don't they? Also data abstraction is not about model, but about infrastructure. So why is DAO placed over model? If you do really need DAO, you should place it under model (into repository implementation, I suppose).
Example of right usage:
package my.example.model;
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String login;
private String password;
#Temporal(TemporalType.TIMESTAMP)
private Date registrationDate;
User() {
// for persistence provider only
}
public User(String login, String password) {
this.login = login;
this.password = hashPassword(password);
this.registrationDate = new Date();
}
public String getLogin() {
return login;
}
public String setPassword(String password) {
this.password = hashPassword(password);
}
public boolean matchPassword(String password) {
return this.password.equals(hashPassword(password));
}
public Date getRegistrationDate() {
return registrationDate;
}
private static String hashPassword(String password) {
try {
MessageDigest digest = MessageDigest.getInstance("sha-1");
StringBuilder sb = new StringBuilder();
byte[] bytes = digest.digest(password.getBytes(charset));
for (byte b : bytes) {
sb.append(Character.forDigit((b >>> 4) & 0xF, 16)).append(Character.forDigit(b & 0xF, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}
package my.example.model;
public interface UserRepository {
User findByLogin(String login);
User findBySurrogateId(int id);
Integer getSurrogateId(User user);
boolean contains(User user);
void add(User user);
void delete(User user);
}
package my.example.infrastructure;
#Component
public class PersistentUserRepository implements UserRepository {
#PersistenceContext
private EntityManager em;
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override public User findByLogin(String login) {
// I'd use QueryDSL here
QUser qusr = new QUser("usr");
return new JPAQuery(em)
.from(qusr)
.where(qusr.login.eq(login))
.singleResult(qusr);
}
#Override public User findBySurrogateId(int id) {
return em.find(User.class, id);
}
#Override public Integer getSurrogateId(User user) {
return (Integer)em.getEntityManagerFactory().getPersistenceUnitUtil().getIdentity(user);
}
#Override public boolean contains(User user) {
return em.contains(user);
}
#Override public void add(User user) {
em.persist(user);
}
#Override public void delete(User user) {
em.remove(user);
}
}
package my.example.facade;
public interface UserRemoteFacade {
UserDTO getUser(String login);
UserDTO getUser(int id);
void changePassword(int userId, String newPassword);
void registerUser(String login, String password) throws LoginOccupiedException;
boolean authenticate(String login, String password);
}
package my.example.facade;
public class UserDTO implements Serializable {
private int id;
private String login;
private Date registrationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
}
package my.example.server;
#Transactional #Component
public class UserRemoteFacadeImpl imlements UserRemoteFacade {
private UserRepository repository;
private Security security;
#Autowired
public UserRemoteFacadeImpl(UserRepository repository, Security security) {
this.repository = repository;
this.security = security;
}
#Override public UserDTO getUser(String login) {
return mapUser(repository.findByLogin(login));
}
#Override public UserDTO getUser(int id) {
return mapUser(repository.findBySurrogateId(id));
}
private UserDTO mapUser(User user) {
if (user != security.getCurrentUser()) {
security.checkPermission("viewUser");
}
UserDTO dto = new UserDTO();
dto.setId(repository.getSurrogateId(user));
dto.setLogin(user.getLogin());
dto.setRegistrationDate(user.getRegistrationDate());
return dto;
}
#Override public void changePassword(int userId, String newPassword) {
User user = repository.findByLogin(login);
if (user != security.getCurrentUser()) {
security.checkPermission("changePassword");
}
user.setPassword(newPassword);
}
#Override public void registerUser(String login, String password) throws LoginOccupiedException {
if (repository.findByLogin(login) != null) {
throw new LoginOccupiedException(login);
}
User user = new User(login, password);
repository.add(user);
}
#Override public boolean authenticate(String login, String password) throws LoginOccupiedException {
User user = repository.findByLogin(login);
return user != null && user.matchPassword(password);
}
}
Also see this project: http://dddsample.sourceforge.net/
The best way to implement Spring is to have the following components in your project:
Model Classes (#Entity)- Exactly your domain classes
Dao Interfaces
Dao Implemetations (#Repository)
Service Interfaces
Service Implementations (#Service)
Controller classes (#Controller)
2 & 3 forms the Persistence Layer and 4 & 5 forms the Service Layer
Example:
Model class
#Entity
public class User implements Serializable {
private static final long serialVersionUID = -8034624922386563274L;
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "name")
private String name;
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
Dao Interface
public interface UserDao {
public User getUser(String username);
}
Dao Implementation
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
private Session openSession() {
return sessionFactory.getCurrentSession();
}
#Override
public User getUser(String username) {
List<User> userList = new ArrayList<User>();
Query query = openSession().createQuery(
"from User u where u.username = :username");
query.setParameter("username", username);
userList = query.list();
if (userList.size() > 0)
return userList.get(0);
else
return null;
}
}
Service Interface
public interface UserService {
public User getUser(String username);
}
Service Implementation
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private UserDao userDao;
#Override
public User getUser(final String username) {
return userDao.getUser(username);
}
}
I am coding in blueJ. My objectives are this: 1)Write a User class
A User:
has a username e.g 'fj3'
has a userType which can be: 'user', 'editor' or 'admin'
has a name e.g 'Francis'
has a constructor which takes the username, userType and name as parameters
has a getUsername() method
has a getUserType() method
has a getName() method
has a setUserType() method which takes one of the user types as a parameter
2)Write a UserGroup class
The UserGroup class must have an ArrayList of Users.
Write a constructor for the UserGroup class. It should instantiate the ArrayList.
In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList.
In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList.
In UserGroup write a printUsernames() method in UserGroup:
Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList.
What I have so far is:
package user;
public class User{
public enum UserType{
ADMIN, EDITOR, USER;
}
private String id;
private UserType userPermissions;
private String actualName;
public User(String username, UserType userType, String name){
id = username;
userPermissions = userType;
actualName= name;
}
public String getUsername(){
return id;
}
public UserType getUserType(){
return userPermissions;
}
public String getName(){
return actualName;
}
public void setUserType(UserType input){
userPermissions = input;
}
}
And my UserGroup class:
package user;
import java.util.*;
import user.User.UserType;
public class UserGroup{
private ArrayList<User> people;
public UserGroup(){
people = new Arraylist<User>();
}
public static void addSampleData(String username, UserType userType, String name){
people.add(new User(username, userType,name));
}
public User get(int){
return User;
}
public void printUsernames(){
for (User user: groupArray){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
}
This is obviously far from being complete but I am completely stuck. My first problem is that I am unsure how to write the get method for this. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere near completing all the objectives and I don't know how to do them!!
Looks good so far, some corrections:
The addSampleData()method should not be static, as it uses a non-static member of the class. The request also states it to add the sample data itself.
The getUser() is pretty straight forward then.
The printUsernames()method uses an unknown member.
public void addSampleData() {
people.add(new User("pe3", UserType.ADMIN,"Peter"));
people.add(new User("u987", UserType.EDITOR,"Udo"));
people.add(new User("frank123", UserType.USER,"Frank"));
// repeat ...
}
public User getUser(int idx) {
return people.get(idx);
}
public void printUsernames(){
for (User user: people){
System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
}
}
In a main method then:
UserGroup grp = new UserGroup();
grp.addSampleData();
grp.printUsernames();
User u1 = grp.getUser(0);
Suppose I have an interface API and classes FacebookAPI and FlickrAPI that implements this interface,
public interface API {
Photo getPhoto(int id);
Album getAlbum(int id);
}
package api;
import domainObjects.Album;
import domainObjects.Photo;
public class FacebookAPI implements API{
#Override
public Photo getPhoto(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public Album getAlbum(int id) {
// TODO Auto-generated method stub
return null;
}
}
import domainObjects.Album;
import domainObjects.Photo;
public class FlickrAPI implements API{
#Override
public Photo getPhoto(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public Album getAlbum(int id) {
// TODO Auto-generated method stub
return null;
}
}
The issue is that I only know that at minimum both APIs(facebook and flickr) requires the photoId. Now suppose that to get a photo FacebookAPI requires AccessToken in addition to Id while FlickAPI requires APIKey + UserId in addition to photoId.
What Design Pattern can i use to solve this issue?
Create a Credentials abstract class to be extended by concrete APi implementation and get that in method contracts.
public Album getAlbum(int id, Credentials c) {
and similarily
public FlickrCredentials extends Credentials {
String APIKey
String UserId
}
That is only feasible if the authentication method is similar with changing parameters (like URL parameters). The abstract class should specify the contract of the method actually using the values, something like:
public String buildToken();
that could be implemented for instance as:
#Override
public String buildToken() {
return "APIKey="+getAPIKey()+"&UserId="+getUserId();
}
Not sure which language you're using (objective c?) but if done it in C# then you'd want to use generics:
public interface API<TIdentifier> {
Photo getPhoto(TIdentifier id);
Album getAlbum(TIdentifier id);
}
Then your classes would look like this:
public class FlickrAPI implements API<FlickrIdentifier>
{
#Override
public Photo getPhoto(FlickrIdentifier id) {
// TODO Auto-generated method stub
return null;
}
#Override
public Album getAlbum(FlickrIdentifier id) {
// TODO Auto-generated method stub
return null;
}
}
Then you'd also need the FlickrIdentifier class:
public class FlickrIdentifier
{
public string ApiKey { get; set; }
public string UserId { get; set; }
}
Why cant you do something like this
public class FlickrAPI implements API{
private String key;
private UserId id;
public FlickrAPI(String key, UserId id){
this.key = key;
this.id = id;
//rest of initialzation
}
}
Similarly for the FacebookAPI class