Friday, November 18, 2016

REST webservice - Apache CXF converts String to JSON incorrectly

I have created a simple REST webservice and it returns a String value from Response. But browser givesan error and nothing shows from tomcat side.


Error shown in font end: This is basically generic error

=======================

This page contains the following errors:

error on line 1 at column 1: Document is empty

Below is a rendering of the page up to the first error.

=============================


below is the coding for my webservice

------------------------------------------------------------------------------

@Path("/")
@WebService(name = "mailService", targetNamespace = "http://localhost/cxf-rest/example")
public interface MailService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/testMail")
public Response sendTestMail(@QueryParam("env") String env);

}

--------------------------------------------------------------------

----------------------------------------------------------------------------------------

public class MailServiceImpl implements MailService {


@Override
public Response sendTestMail(String env) {
// TODO Auto-generated method stub
return Response.ok("good").build();
}
}


----------------------------------------------------------------------------------------

below is the definitions for 'beans.xml"

------------------------------------------------------------------------------------------

<jaxrs:server id="mailService" address="/mailservices">
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
<jaxrs:serviceBeans>
<ref bean="mailServiceImpl" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</jaxrs:extensionMappings>
</jaxrs:server>
<bean id="mailServiceImpl" class="com.rest.cxfrestservice.service.MailServiceImpl" />

-----------------------------------------------------------------------------------------------

Reason
Jaxb does not know how to convert String to Json.

you have few solutions

Solution 1:
change response type to "text/plain"


----------------------------------------------------------------------------------------

@Path("/")
@WebService(name = "mailService", targetNamespace = "http://localhost/cxf-rest/example")
public interface MailService {


@GET
@Produces("text/plain")
@Path("/testMail")
public Response sendTestMail(@QueryParam("env") String env);

}
----------------------------------------------------------------------------------------


this will solve the error. But output will be a plain text.

Solution 2 : 
Use wrapper

----------------------------------------------------------------------------------------

@XmlRootElement(name = "statusMessage")
public class StatusMessage {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

}

----------------------------------------------------------------------------------------

new Service Impl class

---------------------------------------------------------------------------------------

@Path("/")
@WebService(name = "mailService", targetNamespace = "http://localhost/cxf-rest/example")
public interface MailService {

@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/sendMail")
public Response sendRefreshMail(@QueryParam("env") String env);

}

------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------
public class MailServiceImpl implements MailService {

public Response sendRefreshMail(String env) {
if (env == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
StatusMessage statusMessage = new StatusMessage();
statusMessage.setMessage(mailSao.sendEmail(env));

return Response.ok(statusMessage).build();
}


}


----------------------------------------------------------------------------------------


This will return response as needed. below is xml output

<statusMessage>
<message>SUCCESS</message>
</statusMessage>

below link is a good one

Thursday, November 17, 2016

Loading properties from default property file location in maven project

Sometimes loading the property from file becomes a headache to java developers and it starts giving some awful errors. Specially finding the correct path for the property file.
As per maven property files will be placed inside "resources" folder and these files are copied into 'classes' folder inside "WEB-INF" (WEB-INF\classes)

below is a java code block works fines taking the given property file from default location. (default =WEB-INF\classes)

Here property file is loaded using class loader and you need Java 7 to use this logic.
With this you can easily get rid of pain came from  Java 1.5

======================================================

String resourceName = "config.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try (InputStream resourceStream = loader
.getResourceAsStream(resourceName)) {
props.load(resourceStream);
System.out.println(props);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


=============================================================

Thursday, November 3, 2016

Steps of building the Rest webservice

I have made a blog on creating a rest application. Just thought giving some steps to follow and check the application building process.

this is based on the link
http://cgenit.blogspot.com/2015/06/creating-webservice.html

1.       Create application “Rest” using maven plugin in eclipse.
2.       Deployed to tomcat and http://localhost:8080/Rest/ loading the home page
4.       Apache CXF , spring , Jaxon, JAXB
5.       Added all the maven dependencies
6.       Build the project  mvn clean package , and redeploy in tomcat server and check home page http://localhost:8080/Rest/  loading fine
7.       Change the web.xml , Initially no entries except for
8.       You cannot just add changes to web.xml and test. It won’t work as web.xml refers beans and etc.
9.       Change web.xml
a.       Added classed
b.      Build and deploy   - not working
c.       My added “java” folder was not inside “Rest\src\main”
d.      I copied ”java” folder
e.      It was not working, cause I have named bean.xml where it should have been beans.xml – which is referred by the web.xml
f.        Make sure names are spelled correctly. Working fine


Adding or showing javascript , HTML code block inside blogger post

I have being trying several times to add html codes, java scripts inside a blogger post.
However using BLOCKQUOTE tag it was resolved.

Sometimes this might also give some headache, but for the time it gives me some hope to just to go on with my blogging.

so before the coding you are entering just add <blockquote>

Simple Angular Application to Call A Rest Webservice

Here I make an simple angular application to call a rest web service call

1. create sample rest web service. get an employee with id

http://cgenit.blogspot.com/2015/06/creating-webservice.html

2. let's create a simple web application calling this rest service

we call this rest service with

http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1

3. We use the same "index.jsp" for this application
4. we create "hello.js" to put the angular based scripts
5. These script is called inside the "index.jsp"


the two files should be inside "webapp" folder . For this application path would be "Rest\src\main\webapp"

 6. build the project with maven and deploy the Rest.war file inside the tomcat and access the application using the url http://localhost:8080/Rest/

you will simply get an output as below.



Rest Application code structure


Below are the code snipets


hello.js
===========================================================


angular.module('demo', []).controller(
'Hello',
function($scope, $http) {
$http.get('http://localhost:8080/Rest/rest/employeeservices/getemployeedetail?employeeId=1').then(
function(response) {
$scope.employee = response.data;
});
});



=========================================================


index.jsp

============================================================


<!doctype html>
<html ng-app="demo">
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
    <script src="hello.js"></script>
</head>

<body>
<div ng-controller="Hello">
<p>The ID is  = {{employee.employeeId}}</p>
<p>First name = {{employee.firstName}}</p>
<p>Last name  = {{employee.lastName}}</p>
<p>Date of join = {{employee.dateOfJoining}}</p>
<p>Department = {{employee.department}}</p>
<p>Email{{employee.email}}</p>
</div>
</body>
</html
============================================================

SQL Server :Link Server Test connection fail

Issue:
I have created a link server in MS SQL server.
Connect to database with "windows  Auhtentication"  - Connection successful
Conneect to database server with " SQL server Auhtentication -  Test connection fail

most proabably you will get an error like below


Cannot create an instance of OLE DB provider "OraOLEDB.Oracle" for linked server "YourLinkServerName". (Microsoft SQL Server, Error: 7302)

Solution
Enable "Allow inprocess" to "OraOLEDB.Oracle"

How to do this
---------

Server Objects --> Linked Servers -->Providers --> OraOLEDB.Oracle


tick Enable "Allow inprocess"

make sure you have link server using this provider