Restful webservices(Apache wink+Guice+openjpa) - guice-3

I would like to use the following technologies to develop restful webservice.
Apache wink+Guice3+openjpa. I dont know how to use guice with wink and openjpa. could you please explain.

I can't help you with OpenJPA, but I just now figured out how to use Guice with Wink. First of all, you do not need to use Guice's guice-servlet JAR as you would with a plain webapp. Just set up your webapp to use Wink as you normally would, then follow these steps.
Replace the wink-server JAR with the wink-guice-server JAR (available from the same source).
Change the servlet-class in your web.xml file from
org.apache.wink.server.internal.servlet.RestServlet
to
org.apache.wink.guice.server.internal.servlet.GuiceRestServlet
Also in web.xml, add this snippet to Wink's <servlet-class> element:
<init-param>
<param-name>deploymentConfiguration</param-name>
<param-value>com.yourco.yourproj.DeploymentConfiguration</param-value>
</init-param>
Finally, create a new Wink DeploymentConfiguration class, which I call here com.yourco.yourproj.DeploymentConfiguration.
package com.yourco.yourproj;
import com.google.inject.Module;
import org.apache.wink.guice.server.internal.GuiceDeploymentConfiguration;
import org.apache.wink.guice.server.internal.lifecycle.WinkGuiceModule;
public class DeploymentConfiguration extends GuiceDeploymentConfiguration {
#Override
public Module[] createModules() {
return new Module[] { new WinkGuiceModule(), new YourModule() };
}
}
YourModule is just a normal Guice module.

Related

Error resolving template with Spring Boot using Thymeleaf packaged in a .jar

I have a Spring Boot application using Thymeleaf as template resolver, which works fine when debugging from NetBeans, but gives me this error running its .jar:
Error resolving template "/theme/property", template might not exist or might not be accessible by any of the configured Template Resolvers
The app is set to auto-configurer with the annotation #SpringBootApplication, at an extension of SpringBootServletInitializer. I haven't set any contextPath into the properties file. I'm using Thymeleaf 2.1.6 and Spring 4 version. The jar is generated with Maven.
Doing some research I've come out that in some controllers I was passing a double slash, which I've solved but most pages still not working.
This controller works:
#GetMapping("/{idweb}")
String frontEndHome(#PathVariable("idweb")Integer idweb, Model model){
...
return "theme/home";
With the return statement set as return "/theme/home"; doesn't work. I guess, because the template resolver is recieving a double slash (//).
This other controller raises the error:
#GetMapping("/{idweb}/property")
String frontEndProperty(#PathVariable("idweb") Integer idweb, #RequestParam(value = "idproperty", required = false) Integer idproperty, Model model) throws Exception {
...
return "theme/property";
The index controller works fine as well:
#GetMapping("/")
public String index(Model model){
...
return "index";
}
That's my application starter class:
#SpringBootApplication
public class RentalWebsApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RentalWebsApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(RentalWebsApplication.class, args);
}
}
For Thymeleaf I haven't set any configuration, although I've tested the app setting this into the application.properties file, with the same result:
spring.thymeleaf.prefix=classpath:/templates/
All html files are set into:
src/main/resources/templates
The html files from the examples are in:
src/main/resources/templates/index.html
src/main/resources/templates/theme/home.html
src/main/resources/templates/theme/property.html
There are some other questions dealing with the same issue, but none has a solution that works for me. Any help, would be much appreciated.
Update
Deploying the jar into Pivotal Web Services, the whole website works fine, but not deploying it with Boxfuse, Heroku or running the jar locally. Therefore, I guess the origin of the problem is some wrong configuration, that Pivotal system detects and corrects.*
*
PWS isn't correcting a configuration problem. It unpacks your jar file before running the application which stops the double slash from causing a problem. – Andy Wilkinson
At the end the solution was related to the double slashes, that the classpath:/templates/ gets if we set a return statement with a slash at the beginning like:
return "/theme/property"
Instead of:
return "theme/property"
In my case, the problem was not at the controller, but in the html with the Thymeleaf references of fragments, like in this example:
<footer th:replace="/index::footer"></footer>
Instead of:
<footer th:replace="index::footer"></footer>
What I don't understand is why the IDE's (NetBeans and STS), where not raising the error.
use
return new ModelAndView("member2",map);
instead of
return new ModelAndView("/member2",map);
Remove spring.thymeleaf.prefix=classpath:/templates/ from your application.properties.

Swagger not giving UI for Spring MVC Project

I am new to the Swagger and trying to implement it in the Spring MVC. I'm using latest dependency swagger-springmvc from http://mvnrepository.com/artifact/com.mangofactory/swagger-springmvc. So based on link https://dzone.com/articles/documenting-your-spring-api. I added following configuration in mvc-config.xml.
<!-- Serve static content - required for Swagger -->
<mvc:default-servlet-handler/>
<!-- to enable the default documentation controller-->
<context:component-scan base-package="com.mangofactory.swagger.controllers"/>
<!-- to pick up the bundled spring configuration-->
<context:component-scan base-package="com.mangofactory.swagger.configuration"/>
<!-- Direct static mappings -->
<mvc:resources mapping="*.html" location="/, classpath:/swagger-ui"/>
Also I used following from link shown above.
<bean class="com.xxx.xx.xx.SwaggerConfig"/>
Then I added
git clone https://github.com/wordnik/swagger-ui
cp -r swagger-ui/dist ~/dev/x-auth-security/src/main/webapps/docs
When I launch the site: http://localhost:8080/dp-rest/api-docs I don't see UI format, it only gives JSON format.
{"apiVersion":"1.0","swaggerVersion":"1.2","apis":[{"path":"/default/student-service","description":"Manage Student Service","position":0},{"path":"/default/student-service","description":"Manage Student Service","position":0}],"authorizations":[],"info":{"title":"Student API's","description":"API for Student ","termsOfServiceUrl":"terms.html","contact":"test#yahoo.com","license":"Commercial Proprietary","licenseUrl":"http://www.adbc.com"}}
Ny
#Configuration
#EnableSwagger
public class SwaggerConfig {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
// Don't forget the #Bean annotation
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(
apiInfo()).includePatterns(".*");
}
private ApiInfo apiInfo() {
return new ApiInfo("Student API", "API for Student",
"term.html", "test#tahoo.com",
"Commercial Proprietary", "http://www.test.com");
}
}
Why UI format not coming when we launch the http://localhost:8080/sample-rest/api-docs site?
Then only I see raw JSON response not any ui, What is missing here? What I need to changed/add/modify my code?
According to the article you'll see a section that tells you where to find the documentation. I'm not sure if you're using spring-boot but...
After making these changes, I was able to open fire up the app with "mvn spring-boot:run" and view http://localhost:8080/docs/index.html in my browser.
In any case, swagger-springmvc is now called springfox and supports the latest swagger specification (2.0). There is also documentation available to help you get started. I would recommend using the latest version (2.3.1 as of this writing) of springfox instead.

Using EJBs from a different JAR

I'm developing a JAX-WS WebService in JDeveloper 11.1.1.4 that should use EJBs from a JAR previously deployed to a WebLogic server. Both the WebService project and the EJB project are my own code, but I'd like to deploy them separately. For now I'm experimenting with the setup.
In the ExampleEJB project I have a bean ExampleBean that implements a remote interface Example.
#Remote
public interface Example {
public String doRemoteStuff();
}
#Stateless(name = "Example", mappedName = "ExampleApplication-ExampleEJB-Example")
public class ExampleBean implements Example {
public String doRemoteStuff() {
return "did remote stuff";
}
}
In that project, I have two deploy descriptors (ejb-jar.xml and weblogic-ejb-jar.xml):
ejb-jar.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0" xmlns="http://java.sun.com/xml/ns/javaee">
<enterprise-beans>
<session>
<ejb-name>Example</ejb-name>
</session>
</enterprise-beans>
</ejb-jar>
weblogic-ejb-jar.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<weblogic-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd"
xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar">
<weblogic-enterprise-bean>
<ejb-name>Example</ejb-name>
<stateless-session-descriptor/>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Additionaly, I've created an EJB JAR deployment profile named example-ejb.jar and managed to deploy it to the server.
In the ExampleWS project I have an ExampleWebService:
#WebService(serviceName = "ExampleWebService")
public class ExampleWebService {
#EJB
Example example;
public String doStuff() {
return example.doRemoteStuff();
}
}
I added the ExampleEJB project dependency to this project (so it would compile). The only XML I have in this project is the web.xml used to describe the servlet. Also, I have the WebServices WAR file created automatically by jDeveloper when creating a WebService. Lastly, I created an EAR deployment profile named example-ws that only includes the WebServices WAR file in it's application assembly.
What do I need to do for this to work? Also, what would the procedure be if the ExampleEJB project was referenced from another project (say, AdditionalExampleEJB) that has additional beans that use ExampleBean? How would I reference the ExampleBean from there?
Thank you VERY MUCH for any help you can give me!
EDIT:
I've managed to reference the EJB from the WebService!
In the ExampleEJB project I modified the weblogic-ejb-jar.xml and now it looks like this:
weblogic-ejb-jar.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<weblogic-ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-ejb-jar http://www.bea.com/ns/weblogic/weblogic-ejb-jar/1.0/weblogic-ejb-jar.xsd"
xmlns="http://www.bea.com/ns/weblogic/weblogic-ejb-jar">
<weblogic-enterprise-bean>
<ejb-name>Example</ejb-name>
<stateless-session-descriptor>
<pool>
<max-beans-in-free-pool>10</max-beans-in-free-pool>
<initial-beans-in-free-pool>3</initial-beans-in-free-pool>
</pool>
<business-interface-jndi-name-map>
<business-remote>hr.example.Example</business-remote>
<jndi-name>ejb/example-ejb/Example</jndi-name>
</business-interface-jndi-name-map>
</stateless-session-descriptor>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
In the ExampleWS project I added a deployment descriptor weblogic.xml that looks like this:
weblogic.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<weblogic-web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.bea.com/ns/weblogic/weblogic-web-app http://www.bea.com/ns/weblogic/weblogic-web-app/1.0/weblogic-web-app.xsd"
xmlns="http://www.bea.com/ns/weblogic/weblogic-web-app">
<ejb-reference-description>
<ejb-ref-name>ExampleReference</ejb-ref-name>
<jndi-name>ejb/example-ejb/Example</jndi-name>
</ejb-reference-description>
</weblogic-web-app>
Note that the ExampleReference value and ejb/example-ejb/Example value are something I decided to enter - I think they is more or less a developer's choice.
Also, I referenced the EJB in my WebService using the ExampleReference value, so my ExampleWebService looks like this:
ExampleWebService
#WebService(serviceName = "ExampleWebService")
public class ExampleWebService {
#EJB(
name="ExampleReference"
)
Example example;
public String doStuff() {
return example.doRemoteStuff();
}
}
Lastly, in the deployment profile of ExampleWS (the WebServices.war) I added the dependency contributor and checked the interface Example.class element (NOT the ExampleBean.java that has the implementation).
Now, how would this work if the Example bean was referenced from another EJB project (not a WebService)?
So, for all those that encounter the same problem, I have solved it. There is no way to look up a remote EJB in EJB 3.0 other than using InitialContext.lookup("jndi/name"). Also, narrowing the object seems to help in some ClassCastException situations, so I tend to do it as a precaution. This is how I look up my EJBs:
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
public Object lookup (String jndiName, Class type) throws NamingException {
return PortableRemoteObject.narrow(InitialContext.doLookup(jndiName), type);
}
If using EJB 3.1, there is a way using #EJB(lookup = "jndi/name"), but since I'm not using this version, I cannot guarantee that this works.

Accessing services directory when setting up Zend AMF in Codeigniter

I followed the instructions in this tutorial to set up Zend AMF as a way of passing data from my flash app to my PHP app:
http://codeigniter.com/forums/viewthread/180414/
So I have the directory structure and everything as described there. This is my gateway controller:
class Gateway extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('zend');
//root_folder + application + controllers + amf + services
define('SERVICES_FOLDER', APPPATH.'controllers/amf/services/');
}
public function index()
{
$server = new Zend_Amf_Server();
$server->setProduction(false);
//$server->addFunction('testservice');
$server->addDirectory(SERVICES_FOLDER);
echo $server->handle();
}
}
And the APPPATH is /application/ so the path defined by SERVIES_FOLDER is "/application/controllers/amf/services" which is where my file 'testservice.php' sits.
When I try and connect to that service in flash:
var gateway:String = "http://mysite.com/amf/gateway";
con.connect(gateway);
con.call("Testservice.getMessage", new Responder(onResult, onFault));
It calls the onFault method and displays the error:
Plugin by name 'Testservice' was not found in the registry;
Which makes me think that the addDirectory() line in Gateway.php was the problem somehow. Interestingly, I also cannot access the testservice function through a URL, ie by going to mysite.com/amf/services/testservice.
Any thoughts on what might be going on here?
Figured it out, sort of.
Instead of using the addDirectory method which I was having no luck with, I used the setClass method and created another class within the gateway.php file that has the functions, and now I can connect to those functions from flash.
I had an issue with this when using parent::__construct() in my service controllers. Once I removed that, the problem went away.

In java web application, how to read log4j.xml from WEB-INB/conf location with spring 3.0 annotations

I wanted to put my log4j.xml file in WEB-INF/conf directory where I have many other configuration files. And I wanted the web application to read log4.xml from there.
I was trying to use spring3.0 and annotations. So not sure how to access the servlet context to get the WEB-INF location.
tried this
InputStream ist = Thread.currentThread().getContextClassLoader().getResourceAsStream("/conf/log4j-my.xml");
but it searches under to tomcat/bin/
Tried this but did't help much
DOMConfigurator.configure("WEB-INF/conf/log4j-my.xml");
Would appreciate any help/links/pointer.
Not sure what you really wanna do....
if your log4j.xml is in the classpath, when you start your app-server, it should be loaded automatically.
Check the console when you start your server and you should see your log4j info.
You can also put debug=true:
<log4j:configuration debug="true" xmlns:log4j="http://jakarta.apache.org/log4j/">
in your xml. you will be able to see a lot of info about your config.
Now if you want to access the appenders you configured in the log4j.xml, all you have to do is:
Logger mylogger = Logger.getLogger("MyAppenderName");
Ok, i think you wanna load a custom log4j config file! In a web app context, you will need 2 things:
create a contextListnerServlet;
modify your web.xml
ServletListner:
public class StartupListener implements ServletContextListener
{
#Override
public void contextDestroyed(ServletContextEvent arg0)
{
// Cleanup code goes here
}
#Override
public void contextInitialized(ServletContextEvent sce)
{
Logger logger = null;
String log4jFile = sce.getServletContext().getInitParameter("log4jFileName");
DOMConfigurator.configure(sce.getServletContext().getRealPath(log4jFile));
logger = LogManager.getLogger(StartupListener.class.getName());
logger.debug("Loaded: " + log4jFile);
}
web.xml:
<context-param>
<param-name>log4jFileName</param-name>
<param-value>
WEB-INF/config/log4j-my.xml
</param-value>
</context-param>
<listener>
<listener-class>
com.yourpackage.StartupListener
</listener-class>
</listener>
Hope it helps

Resources