Getting Succes Page directly - struts2

DeleteAction.java
public class DeleteAction extends ActionSupport{
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String execute(){
UserManager um = new UserManagerImpl();
try {
um.deletestudent(email);
} catch (Exception e) {
return INPUT;
}
return SUCCESS;
}
}`
i am new to coding and i am getting success page directly..please help me to solve the problem. i want to delete the data from the database.

Related

th:checked throws exception

My Thymeleaf cant compile, i can't understand what's wrong. I need to create checkbox and make checked only roles, which user contains.
I reсeive this execption: Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "user.getRoles().contains(${role})" (template: "editUser" - line 19, col 54)
at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393) ~[attoparser-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.attoparser.MarkupParser.parse(MarkupParser.java:257) ~[attoparser-2.0.5.RELEASE.jar:2.0.5.RELEASE]
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230) ~[thymeleaf-3.0.15.RELEASE.jar:3.0.15.RELEASE]
... 89 common frames omitted
Role(entity):
#Entity
#Table(name = "sweater_roles")
public class Role implements GrantedAuthority {
public static List<Role> allRoles = Arrays.asList(new Role("USER"), new Role("ADMIN"));
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Role(String name) {
this.name = name;
}
public Role() {
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Role)) return false;
Role role = (Role) o;
return getName().equals(role.getName());
}
#Override
public int hashCode() {
return Objects.hash(getName());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String getAuthority() {
return getName();
}
}
User(entity):
#Entity
#Table(name = "sweater_user")
public class User implements UserDetails{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private boolean active;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(
name = "sweater_user_role",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id", referencedColumnName = "id")
)
private Collection<Role> roles;
public User(String username, String password, boolean active, Collection<Role> roles) {
this.username = username;
this.password = password;
this.active = active;
this.roles = roles;
}
public User() {
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return isActive();
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
}
Controller:
#GetMapping("{user}")
public String editUser(#PathVariable User user, Model model){
model.addAttribute("user", user);
model.addAttribute("roles", Role.allRoles);
return "editUser";
}
HTML file:
Roles:
<th:block th:each="role : ${roles}">
<div>
<label th:for="${role}" th:text="${role}"></label>
<input type="checkbox" th:name="${role}" th:checked="${user.getRoles().contains(${role})}">
</div>
</th:block>

Unable to read XML File stored in GCS Bucket

I have tried to follow this documentation in the most precise way I could:
https://beam.apache.org/documentation/sdks/javadoc/2.0.0/org/apache/beam/sdk/io/xml/XmlIO.html
Please find below my codes :
public static void main(String args[])
{
DataflowPipelineOptions options=PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setTempLocation("gs://balajee_test/stagging");
options.setProject("test-1-130106");
Pipeline p=Pipeline.create(options);
PCollection<XMLFormatter> record= p.apply(XmlIO.<XMLFormatter>read()
.from("gs://balajee_test/sample_3.xml")
.withRootElement("book")
.withRecordElement("author")
.withRecordElement("title")
.withRecordElement("genre")
.withRecordElement("price")
.withRecordElement("description")
.withRecordClass(XMLFormatter.class)
);
record.apply(ParDo.of(new DoFn<XMLFormatter,String>(){
#ProcessElement
public void processElement(ProcessContext c)
{
System.out.println(c.element().getAuthor());
}
}));
p.run();
}
I'm getting 'null' value for every XML component. Could you please review my code and suggest me the corrective course of action required?
package com.bitwise.cloud;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "book")
#XmlType(propOrder = {"author", "title","genre","price","description"})
public class XMLFormatter {
private String author;
private String title;
private String genre;
private String price;
private String description;
public XMLFormatter() { }
public XMLFormatter(String author, String title,String genre,String price,String description) {
this.author = author;
this.title = title;
this.genre = genre;
this.price = price;
this.description = description;
}
#XmlElement
public void setAuthor(String author) {
this.author = author;
}
public String getAuthor() {
return author;
}
#XmlElement
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
#XmlElement
public void setGenre(String genre) {
this.genre = genre;
}
public String getGenre() {
return genre;
}
#XmlElement
public void setPrice(String price) {
this.price = price;
}
public String getPrice() {
return price;
}
#XmlElement
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
XmlIO.Read PTransform doesn't support providing multiple record elements (author, title, genre, etc). You have to provide a single root element and a record element and your XML document has to contain records that have the same record element. See the example given in the following location.
https://github.com/apache/beam/blob/master/sdks/java/io/xml/src/main/java/org/apache/beam/sdk/io/xml/XmlIO.java#L59

Swagger springfox hide model property on POST

Would like to know how to hide a model property in Swagger on POST. I have tried both Swagger-springmvc (0.9.3) and Springfox (supports swagger spec 2.0) to no avail.
Problem being I would like to see this in the GET requests through Swagger. But not POST requests, since id is auto-assigned, I would like to hide it just for the POST request.
public class RestModel {
private int id;
#JsonProperty
private String name;
#JsonProperty
public int getId() {
return 0;
}
#JsonIgnore
public void setId(int customerId) {
this.customerId = customerId;
}
public int getName() {
return "abc";
}
public void setName(String name) {
this.name = name;
}
}
So on GET, I should see:
{
"id": 0,
"name" : "abc"
}
And on POST, I should see just:
{
"name"
}
Tried adding: #ApiModelProperty(readonly=true). But that didn't help.
I have solved this with simply extending the Object that I want to hide a property of when using as request parameter.
Example:
I have the object Person.java:
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import org.joda.time.DateTime;
import org.joda.time.Years;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import io.swagger.annotations.ApiModelProperty;
/**
* Simple Person pojo
*/
#Entity
public class Person {
#GeneratedValue(strategy = GenerationType.AUTO)
#Id
private Long dbId;
private String name;
private Long id;
#JsonFormat(pattern="yyyy-MM-dd")
private Date birthDate;
private String gender;
public Person() {
}
public Person(long dbId) {
this.dbId = dbId;
}
public Person(Long id, String name, Date birthDate, String gender) {
this.id = id;
this.name = name;
this.birthDate = birthDate;
this.gender = gender;
}
public Long getDbId() {
return dbId;
}
public String getName() {
return name;
}
public Date getBirthDate() {
return birthDate;
}
public String getGender() {
return gender;
}
public Integer getAge() {
return Years.yearsBetween(new DateTime(birthDate), new DateTime()).getYears();
}
public void setDbId(Long dbId) {
this.dbId = dbId;
}
public void setName(String name) {
this.name = name;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setGender(String gender) {
this.gender = gender;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
I have simply created another class: PersonRequest.java:
import com.fasterxml.jackson.annotation.JsonIgnore;
public class PersonRequest extends Person {
#Override
#JsonIgnore
public void setDbId(Long dbId) {
super.setDbId(dbId);
}
}
RequestMapping looks simply like:
#RequestMapping(value = "/KVFirstCare/application", method = RequestMethod.POST)
public ApplicationResult application(#RequestBody List<PersonRequest> persons,
HttpServletResponse response) {
}
Works like charm :)
Unfortunately having different request and response models is not supported currently in springfox. The current thought is that we might support this feature using #JsonView in the future.

Proper disposal of repository object inside controller

I am having a hard time figuring this out. I have implemented Repository and Unit of Work patterns as a data access abstraction for my database. I am using Dependency Injection to inject them into the controller. The problem is when the controller is disposed, it disposes the repository, but then when I refresh the page, DbContext object inside repository is null (it shouldn't be, I think). The implementation of classes is shown below.
This is the database Repository class:
public class ConferenceCrawlyDbRepository : IConferenceCrawlyDbRepository
{
private ConferenceCrawlyDbContext _context = null;
private static ConferenceCrawlyDbRepository _instance = null;
public IRepository<AcademicDegree> AcademicDegrees { get; private set; }
public IRepository<Conference> Conferences { get; private set; }
public IRepository<ConferenceComment> ConferenceComments { get; private set; }
public IRepository<ConferenceRating> ConferenceRatings { get; private set; }
public IRepository<ConnectionConferenceRecommendation> ConnectionConferenceRecommendation { get; private set; }
public IRepository<Country> Countries { get; private set; }
public IRepository<ImportantDate> ImportantDates { get; private set; }
public IRepository<Topic> Topics { get; private set; }
public IRepository<UserProfile> UserProfiles { get; private set; }
public IRepository<UserProfileSettings> UserProfileSettings { get; private set; }
public IRepository<UsersConnection> UserConnections { get; private set; }
public IRepository<Venue> Venues { get; private set; }
private ConferenceCrawlyDbRepository(ConferenceCrawlyDbContext context)
{
_context = context;
AcademicDegrees = new Repository<AcademicDegree>(context);
Conferences = new Repository<Conference>(context);
ConferenceComments = new Repository<ConferenceComment>(context);
ConferenceRatings = new Repository<ConferenceRating>(context);
ConnectionConferenceRecommendation = new Repository<ConnectionConferenceRecommendation>(context);
Countries = new Repository<Country>(context);
ImportantDates = new Repository<ImportantDate>(context);
Topics = new Repository<Topic>(context);
UserProfiles = new Repository<UserProfile>(context);
UserProfileSettings = new Repository<UserProfileSettings>(context);
UserConnections = new Repository<UsersConnection>(context);
Venues = new Repository<Venue>(context);
}
public static ConferenceCrawlyDbRepository Instance
{
get
{
if (_instance == null)
_instance = new ConferenceCrawlyDbRepository(new ConferenceCrawlyDbContext());
return _instance;
}
}
public bool CommitChanges()
{
try
{
return _context.SaveChanges() > 0;
}
catch
{
// TODO: Add logging
return false;
}
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
And this is the generic repository class:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private ConferenceCrawlyDbContext _context = null;
private DbSet<TEntity> _dbSet = null;
public Repository(ConferenceCrawlyDbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public DbSet<TEntity> DbSet
{
get
{
return _dbSet;
}
}
public bool Add(TEntity entity)
{
try
{
DbSet.Add(entity);
return true;
}
catch (Exception ex)
{
// TODO: Add logging
return false;
}
}
public bool Update(TEntity entity)
{
try
{
var entry = _context.Entry<TEntity>(entity);
DbSet.Attach(entity);
entry.State = EntityState.Modified;
return true;
}
catch(Exception ex)
{
// TODO: Add logging
return false;
}
}
public bool Remove(TEntity entity)
{
try
{
DbSet.Remove(entity);
return true;
}
catch (Exception ex)
{
// TODO: Add logging
return false;
}
}
public IQueryable<TEntity> GetAll()
{
return DbSet;
}
public IQueryable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return DbSet.Where(predicate);
}
public TEntity FindById(params object[] keys)
{
return DbSet.Find(keys);
}
public bool Contains(Expression<Func<TEntity, bool>> predicate)
{
return _dbSet.Any(predicate);
}
public bool CommitChanges()
{
try
{
return _context.SaveChanges() > 0;
}
catch
{
// TODO: Add logging
return false;
}
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
}
Here is my custom controller factory for dependency injection:
public class CustomControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType != null)
{
if (controllerType.GetConstructor(new Type[] { typeof(IConferenceCrawlyDbRepository) }) != null)
return Activator.CreateInstance(controllerType, new object[] { ConferenceCrawlyDbRepository.Instance }) as Controller;
else if (controllerType.GetConstructor(new Type[] { typeof(IConferenceCrawlyDbRepository), typeof(IMailService) }) != null)
return Activator.CreateInstance(controllerType, new object[] { ConferenceCrawlyDbRepository.Instance,
#if DEBUG
MockMailService.Instance
#else
MailService.Instance
#endif
}) as Controller;
}
return base.GetControllerInstance(requestContext, controllerType);
}
And finally, controller with its action:
public class HomeController : Controller
{
private IConferenceCrawlyDbRepository _dbRepository;
private IMailService _mailService;
public HomeController(IConferenceCrawlyDbRepository dbRepository, IMailService mailService)
{
_dbRepository = dbRepository;
_mailService = mailService;
}
//
// GET: /
public ActionResult Index()
{
var countries = _dbRepository.Countries.GetAll().ToList();
return View(countries);
}
//
// GET: /Home/About
public ActionResult About()
{
return View();
}
//
// GET: /Home/Contact
public ActionResult Contact()
{
return View(new Contact());
}
//
// POST: /Home/Contact
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(Contact contact)
{
if (ModelState.IsValid)
{
if (await _mailService.SendMail(contact.Email, contact.Title,
String.Format("{1}{0}{2}", Environment.NewLine, contact.Message, String.IsNullOrEmpty(contact.Name) ? "Anonimous" : contact.Name)))
{
ViewBag.SuccessMessage = "Comment has been successfully sent.";
return View(new Contact());
}
else
ViewBag.ErrorMessage = "Couldn't send your email. Please try again later";
}
return View(contact);
}
protected override void Dispose(bool disposing)
{
if (_dbRepository != null)
_dbRepository.Dispose();
base.Dispose(disposing);
}
}
The Exception is thrown inside index action when I call the repository, but only after the first time accessing this controller and it says that DbContext object inside repository. I am obviously doing something wrong, but I can't figure it out.
I figure it out after long staring and debugging of code. It's so simple, because I'm disposing context inside ConferenceCrawlyDbRepository I should also set _instance object which is using it to null, and then it will be recreated along with DbContext object. I fell so stupid right now...

Grails: Integrating the Underlying Java(Spring+Hibernate) web app : sub-object not showing it s fields in form

The problem is since my POJO/Domain classes are in java (obvious actually but just to make it clear) the sub-object that i use does'nt show up properly in the form when I click on available controllers: Eg: Patient has address -->> address is a sub-object in patient:
The address field shows a blank dropdown. How do i resolve this?
I am using def scaffold= in the controller.
package pojo;
public class Address {
private int id;
private String street;
private String city;
private String state;
private String country;
private Integer clinicid;
private Integer patientid;
public Address(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getClinicid() {
return clinicid;
}
public void setClinicid(Integer clinicid) {
this.clinicid = clinicid;
}
public Integer getPatientid() {
return patientid;
}
public void setPatientid(Integer patientid) {
this.patientid = patientid;
}
}
package pojo;
public class Clinic {
private int id ;
private String clinicname ;
private Address address;
public int contactNumber;
public Clinic() {
address=new Address();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getClinicname() {
return clinicname;
}
public void setClinicname(String clinicname) {
this.clinicname = clinicname;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
address.setClinicid(this.id);
this.address = address;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
} }
package pojo;
import java.util.*;
public class Doctor {
private int id ;
private Date dateOfBirth ;
private String username;
private String password ;
//private String name ;
private int contactNumber ;
private String specialization ;
public Clinic clinic;
public Doctor(){
clinic=new Clinic();
}
public Clinic getClinic() {
return clinic;
}
public void setClinic(Clinic clinic) {
this.clinic = clinic;
}
/*public Doctor() {
}*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String specialization) {
this.specialization = specialization;
}
}
package pojo;
import java.util.*;
public class Patient {
private int id;
private Date dateOfBirth;
private Date registrationDate;
private String name ;
public int contactNumber;
public enum sexenum {MALE, FEMALE}
public sexenum sex;
private Address address;
private Clinic clinic;
private Doctor doctor;
public Patient(){
clinic=new Clinic();
doctor=new Doctor();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public sexenum getSex() {
return sex;
}
public void setSex(sexenum sex) {
this.sex = sex;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
address.setPatientid(this.id);
this.address = address;
}
public Clinic getClinic() {
return clinic;
}
public void setClinic(Clinic clinic) {
this.clinic = clinic;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
}
patient [ one to one with ] address;.
clinic [ one to one with ] address;.
doctorid [ foreign key many to one]where ever referenced.
clinic id [foreign key many to one ] where ever referenced.
As far as I know, Grails only supports GORM-mappings (http://grails.org/doc/latest/guide/single.html#ormdsl) and hibernate mappings (http://grails.org/doc/latest/guide/single.html#hibernate)
I don't think the mappings you provide are valid for scaffolding.

Resources