您的位置:首页 > 其它

Expose ADF BC as RESTful Web Service

2015-07-22 14:43 381 查看


Expose ADF BC as RESTful Web Service

28
October 2014Oracle

Expose an ADF BC as SOAP Web Service is very simple. All you have to do is enable your Application Module to support Service Interface. But, how can I expose this same Application Module as RESTful Web Service?
In this post, you will learn how to expose ADF BC as RESTful Web Service using JDeveloper 12c (12.1.3). Download the sample application: ADFRESTApp.zip.
Create an ADF Fusion Web Application, and call it as ADFRESTApp.



Create the Business Components, using the Employees table.



This way, you have a simple ADF Application with two projects, Model and ViewController.

Now, we have to create a project to organize the RESTful codes.

Create a new ADF Model RESTful Web Service Project.



To use Application Module from Model project, you need to add the Model Project as a dependency project.

Double-click RESTWebService project and add the Model Project as a dependency project.



Create the Employee and Employees Entities.

In the Applications window, right-click RESTWebService Project and choose New > From Gallery.

In the New Gallery dialog, choose General > Java Class, and click OK.

In the Create Java Class dialog, change the Name to Employee and click OK.

Copy the following code inside Employee class:
@XmlRootElement
public class Employee {
  @XmlElement
  private Integer employeeId;
  @XmlElement
  private String firstName;
  @XmlElement
  private String lastName;
  @XmlElement
  private String email;
  @XmlElement
  private String phoneNumber;
  @XmlElement
  private Date hireDate;
  @XmlElement
  private String jobId;
  @XmlElement
  private BigDecimal salary;
  @XmlElement
  private BigDecimal commissionPct;
  @XmlElement
  private Integer managerId;
  @XmlElement
  private Integer departmentId;
    
  public Employee() {
    super();
  }
  public void setEmployeeId(Integer employeeId) {
    this.employeeId = employeeId;
  }
  public Integer getEmployeeId() {
    return employeeId;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setEmail(String email) {
    this.email = email;
  }
  public String getEmail() {
    return email;
  }
  public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
  }
  public String getPhoneNumber() {
    return phoneNumber;
  }
  public void setHireDate(Date hireDate) {
    this.hireDate = hireDate;
  }
  public Date getHireDate() {
    return hireDate;
  }
  public void setJobId(String jobId) {
    this.jobId = jobId;
  }
  public String getJobId() {
    return jobId;
  }
  public void setSalary(BigDecimal salary) {
    this.salary = salary;
  }
  public BigDecimal getSalary() {
    return salary;
  }
  public void setCommissionPct(BigDecimal commissionPct) {
    this.commissionPct = commissionPct;
  }
  public BigDecimal getCommissionPct() {
    return commissionPct;
  }
  public void setManagerId(Integer managerId) {
    this.managerId = managerId;
  }
  public Integer getManagerId() {
    return managerId;
  }
  public void setDepartmentId(Integer departmentId) {
    this.departmentId = departmentId;
  }
  public Integer getDepartmentId() {
    return departmentId;
  }
}

Repeat the step above and create the Employees class.

Copy the following code inside Employees class:
@XmlRootElement
public class Employees {
  @XmlElement(name = "employee")
  private List employees;

  public Employees() {
    super();
  }
  public void setEmployees(List employees) {
    this.employees = employees;
  }
  public List getEmployees() {
    return employees;
  }
  public void addEmployees(Employee employee) {
    if (employees == null) {
      employees = new ArrayList();
    }
    employees.add(employee);
  }
}

Create the Employees RESTful Service.

In the Applications window, right-click Rest Project and choose New > From Gallery.

In the New Gallery dialog, choose General > Java Class, and click OK.

In the Create Java Class dialog, change the Name to EmployeesResource and click OK.

Copy the following code inside EmployeesResource class:
public class EmployeesResource {
  private static final String amDef = "br.com.waslleysouza.model.AppModule";
  private static final String config = "AppModuleLocal";

  public EmployeesResource() {}

  public void update(Employee employee) {
    ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
    ViewObject vo = am.findViewObject("EmployeesView1");

    Key key = new Key(new Object[] { employee.getEmployeeId() });
    Row[] rowsFound = vo.findByKey(key, 1);
    if (rowsFound != null && rowsFound.length > 0) {
      Row row = rowsFound[0];
      if (employee.getEmail() != null && !employee.getEmail().isEmpty()) {
        row.setAttribute("Email", employee.getEmail());
      }
      if (employee.getHireDate() != null) {
        row.setAttribute("HireDate", employee.getHireDate());
      }
      if (employee.getJobId() != null && !employee.getJobId().isEmpty()) {
        row.setAttribute("JobId", employee.getJobId());
      }
      if (employee.getLastName() != null && !employee.getLastName().isEmpty()) {
        row.setAttribute("LastName", employee.getLastName());
      }
    }
    am.getTransaction().commit();
    Configuration.releaseRootApplicationModule(am, true);
  }

  public Employee getById(Integer id) {
    ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
    ViewObject vo = am.findViewObject("EmployeesView1");
    Employee employee = null;

    Key key = new Key(new Object[] { id });
    Row[] rowsFound = vo.findByKey(key, 1);
    if (rowsFound != null && rowsFound.length > 0) {
      Row row = rowsFound[0];
      employee = new Employee();
      employee.setEmployeeId((Integer) row.getAttribute("EmployeeId"));
      employee.setEmail((String) row.getAttribute("Email"));
      employee.setHireDate((Timestamp) row.getAttribute("HireDate"));
      employee.setJobId((String) row.getAttribute("JobId"));
      employee.setLastName((String) row.getAttribute("LastName"));
    }
    Configuration.releaseRootApplicationModule(am, true);
    return employee;
  }

  public void deleteById(Integer id) {
    ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
    ViewObject vo = am.findViewObject("EmployeesView1");

    Key key = new Key(new Object[] { id });
    Row[] rowsFound = vo.findByKey(key, 1);
    if (rowsFound != null && rowsFound.length > 0) {
      Row row = rowsFound[0];
      row.remove();
    }
    am.getTransaction().commit();
    Configuration.releaseRootApplicationModule(am, true);
  }

  public void add(Employee employee) {
    ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
    ViewObject vo = am.findViewObject("EmployeesView1");

    Row row = vo.createRow();
    vo.insertRow(row);
    row.setAttribute("EmployeeId", employee.getEmployeeId());
    row.setAttribute("LastName", employee.getLastName());
    row.setAttribute("Email", employee.getEmail());
    row.setAttribute("HireDate", new Timestamp(employee.getHireDate().getTime()));
    row.setAttribute("JobId", employee.getJobId());
    am.getTransaction().commit();
    Configuration.releaseRootApplicationModule(am, true);
  }

  public Employees findAll() {
    ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
    ViewObject vo = am.findViewObject("EmployeesView1");
    vo.executeQuery();
    Employees employees = new Employees();

    while (vo.hasNext()) {
      Row row = vo.next();
      Employee employee = new Employee();
      employee.setEmployeeId((Integer) row.getAttribute("EmployeeId"));
      employee.setEmail((String) row.getAttribute("Email"));
      employee.setHireDate((Timestamp) row.getAttribute("HireDate"));
      employee.setJobId((String) row.getAttribute("JobId"));
      employee.setLastName((String) row.getAttribute("LastName"));
      employees.addEmployees(employee);
    }
    Configuration.releaseRootApplicationModule(am, true);
    return employees;
  }
}

In the Applications window, right-click EmployeesResource class and choose Create RESTful Service.

Choose JAX-RS 2.0 Style and click Next.

Configure the RESTful Service and click Finish.



In the Return Type Warning dialog, click OK.



Done!

To test the RESTful Service, right-click EmployeesResource class and choose Test Web Service.

You may test each service operation using HTTP Analyzer.

Select the findAll operation and click Send Request button.



When you try to execute a PUT or POST operation, like the add operation, you receive the following error:
Root cause of ServletException.
A MultiException has 1 exceptions.  They are:
1. java.lang.RuntimeException: Security features for the SAX parser could not be enabled.
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2494)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:98)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:87)
at org.glassfish.jersey.internal.inject.ContextInjectionResolver$1.provide(ContextInjectionResolver.java:114)
at org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:138)
Truncated. see log file for complete stacktrace
Caused By: java.lang.RuntimeException: Security features for the SAX parser could not be enabled.
at org.glassfish.jersey.message.internal.SecureSaxParserFactory.(SecureSaxParserFactory.java:103)
at org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider.provide(SaxParserFactoryInjectionProvider.java:78)
at org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider.provide(SaxParserFactoryInjectionProvider.java:57)
at org.jvnet.hk2.internal.FactoryCreator.create(FactoryCreator.java:96)
at org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
Truncated. see log file for complete stacktrace
Caused By: javax.xml.parsers.ParserConfigurationException: SAX feature 'http://xml.org/sax/features/external-general-entities' not supported.
at oracle.xml.jaxp.JXSAXParserFactory.setFeature(JXSAXParserFactory.java:272)
at weblogic.xml.jaxp.RegistrySAXParserFactory.setFeature(RegistrySAXParserFactory.java:134)
at org.glassfish.jersey.message.internal.SecureSaxParserFactory.(SecureSaxParserFactory.java:100)
at org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider.provide(SaxParserFactoryInjectionProvider.java:78)
at org.glassfish.jersey.message.internal.SaxParserFactoryInjectionProvider.provide(SaxParserFactoryInjectionProvider.java:57)
Truncated. see log file for complete stacktrace




This is a known issue for JDeveloper
and ADF 11g Release 2, but I didn’t find anything about it in Release
Notes from JDeveloper and ADF 12c.

Probably this issue continues in JDeveloper and ADF 12c, so let’s use the workaround for 11g.
Create a Java Class that extends org.glassfish.jersey.server.ResourceConfig and set the MessageProperties.XML_SECURITY_DISABLE property to TRUE.
@ApplicationPath("/resources/")
public class MyResourceConfig extends ResourceConfig {

  public MyResourceConfig() {
    super();
    property(MessageProperties.XML_SECURITY_DISABLE, Boolean.TRUE);
  }
}

Done!

Test your RESTful Web Service again, and execute the PUT and POST operations successfully!





Related Posts

No related posts.


Post navigation

← RESTful Web Service in JDeveloper 12cEmpty
REST DC in MAF 2.0.1 (Workaround) →


10 thoughts on “Expose ADF BC as RESTful Web Service”


Csaba

16 January 2015 at 5:10 pm

I tried your example but the findAll returns actual Empoyee objects (like restwebservice.Employee@112460a)

I even annotated the findAll with

@Produces(value={“application/json”})
What might be wrong? How can I actually see the xml or json return value?

Reply


Csaba

16 January 2015 at 7:35 pm

I’m not sure if my previous reply made it through so I try again: I followed you example, recreated all the classes, etc but something is wrong because when I run the findAll request, the return for Employees are
all Employee instances?

I specified @Produces(value={“application/json”}) for findAll, but in vain.

Reply


Waslley
Souza

16 January 2015 at 8:02 pm

Csaba, try to annotate your EmployeesResource class with those annotations:
@Consumes(“application/xml”)

@Produces(“application/xml”)

Reply


Csaba

16 January 2015 at 8:33 pm

Hi Waslley,

hm…I have those:

@Path(“employees”)

@Consumes(“application/xml”)

@Produces(“application/xml”)

public class EmployeesResource {

private static final String amDef = “model.AppModule”;

private static final String config = “AppModuleLocal”;

public EmployeesResource() {

super();

}

Reply


Waslley
Souza

19 January 2015 at 4:10 pm

Ok. What is the response when you access the findAll through the HTTP Analyzer?

Reply


Csaba

20 January 2015 at 12:12 pm

Hi Waslley,
I got back a bunch of Employee object references, like:

“restwebservice.Employee@29accf0f”,”restwebservice.Employee@104df729″,…

Reply


Waslley
Souza

20 January 2015 at 12:24 pm

Are Employee and Employees classes annotated with the XML annotations?

Try to use

@Consumes(“application/json”)

@Produces(“application/json”)

Reply


Csaba

20 January 2015 at 7:07 pm

Everything works now as in your example. Thanks a lot!

Reply


sarah

11 February 2015 at 3:54 am

Hi, Waslley

Everything works great when testing on HTTP Analyzer. When I deployed the same ear to Weblogic Server 12c, I get error message “Method not allowed” when executing post/put method such as add/ update and delete. How can I work around this?
Thank you in advance.

Reply


Waslley
Souza

11 February 2015 at 11:38 am

Hi Sarah,

I created an ear file with 3 projects and everything works.

What steps you followed to generate the ear file?

Reply
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: