Consume Rest-Webservice in java 1.6 version - rest

Need to consume post method in Rest webservice using java 1.6 version,I have used Jersey jar to connect web services but getting connect rest error when iam running it in JAVA 1.6 Version , But its working fine using java 1.7 and 1.8.
Can some one help me to achive this using JAVA 1.6 version because i need to deploy in server which runs on java 1.6.
Iam Connecting to URL :https:// (secured url)
Code Below:
import java.util.ArrayList;
import javax.ws.rs.client.Client;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.sun.jersey.api.client.WebResource;
import com.thortech.util.logging.Logger;
public class MFARestClientService {
public static void main(String[] args) {
MFARestClientService mfa1=new MFARestClientService();
ArrayList userList = new ArrayList();
userList.add("test1");
userList.add("Test2");
mfa1.postMFAUser(userList);
}
Logger logger = Logger.getLogger("RestClientService");
//Method To post data to AsureCloud
public void postUser(ArrayList<String> userList)
{
JSONObject obj = new JSONObject();
String url = "https://***.azurew.net/********************************/*****";
this.logger.info("Reached RestClientService");
this.logger.info("Get UserDetails from OIM usr table and creating json value");
obj.put("group", "ABC-99");
obj.put("userid", userList);
String jsondata=obj.toJSONString();
System.out.println("JSONDATA :"+jsondata);
{
try {
this.logger.info(jsondata);
Client restClient = Client.create();
WebResource webResource = restClient.resource(url);
ClientResponse response = webResource.accept("application/json").post(ClientResponse.class,jsondata);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
this.logger.info("Output from Server .... \n");
this.logger.info(output);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Error:
Connection reset
But this code work fine in java 1.7 and 1.8
Need help to consume this using java 1.6 version
Thanks
Midhun M S

I see that your URL is using https protocol. If it works in java 1.7 and doesn't work in java 1.6 means most probably is a handshake issue between the client and server. java 1.6 only supports TLS 1.0 where as java 1.7 or 1.8 supports TLS 1.0, TLS 1.1, TLS 1.2. You might have to used third party API's such as Bouncy Castle to for TLS 1.2 support. I would strongly recommend you to upgrade to higher version of java. Good luck

Related

Calling External WCF Service (using generated client) from CRM sandboxed plugin OnPremise is failing

How to call HTTPS WCF web service in Plugin, plugin assembly is registered in sandbox mode. I am getting System.Security.SecurityException exception, Can somebody please provide the way to all https web service. My code is below :
BasicHttpBinding myBinding = new BasicHttpBinding();
myBinding.MaxReceivedMessageSize = Int32.MaxValue;
myBinding.Name = “basicHttpBinding”;
if (EndPoint.ToLower().Contains(“https://”))
{
//Throwing exception here – System.Security.SecurityException exception,
ServicePointManager.ServerCertificateValidationCallback += (sendr, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072 | (SecurityProtocolType)192;
myBinding.Security.Mode = BasicHttpSecurityMode.Transport;
}
else
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
myBinding.Security.Mode = BasicHttpSecurityMode.None;
}
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress endPointAddress = new EndpointAddress(EndPoint);
WebIALClient myClient = new WebIALClient(myBinding, endPointAddress)
Since you are in on-premise version, you can register the plugin assembly in non-sandbox mode. ie Isolation mode = none to overcome such errors.
In case you wanted to use sandbox mode, try using WebClient class for invoking WCF service call. Read more
using (WebClient client = new WebClient())
{
byte[] responseBytes = client.DownloadData(webAddress);
string response = Encoding.UTF8.GetString(responseBytes);
tracingService.Trace(response);
// For demonstration purposes, throw an exception so that the response
// is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
}
Can you try and also include: using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("api/ConvertUpload/{env}/{id}")]
public string Get(string env, string id)
{
return "hi";
}
You may have to use WebClient as #Arun has mentioned.

Swagger grails Integration

I am new to swagger and I want to integrate swagger to Restful API project using grails framework. Please help if anybody have any idea what i am doing wrong?
my grails specification as below:
| Grails Version: 3.0.7
| Groovy Version: 2.4.4
| JVM Version: 1.8.0_71
Did some settings for swagger as below:
in build.gradle:
dependencies {
...
compile "io.swagger:swagger-core:1.5.3"
compile "io.swagger:swagger-jaxrs:1.5.3"
...
}
in resources.groovy
import io.swagger.jaxrs.config.BeanConfig
beans = {
swaggerConfig(BeanConfig) {
def serverUrl = "http://localhost:8080/"
def hostName = "localhost:8080"
resourcePackage = "grails.rest.example"
host = hostName
basePath = "/api"
version = 'v0' // Default "1".
title = 'Core Registration API, Version V0'
description = 'API for Accessing secured resources'
contact = 'testtest#mailinator.com'
license = ''
licenseUrl = ''
}
corsFilter(CorsFilter)
}
Added a Controller ApiDocController.groovy:
package grails.rest.example.apidoc
import grails.web.mapping.LinkGenerator
class ApiDocController {
LinkGenerator grailsLinkGenerator
def apiDocService
def index = {
String basePath = grailsLinkGenerator.serverBaseURL
render(view: 'index', model: [apiDocsPath: "${basePath}/api/swagger-json"])
//render(view: 'index', model: [apiDocsPath: "localhost:8080/api/swagger-json"])
//render(view: 'index', model: [apiDocsPath: "localhost:8080/dist/index.html"])
}
def swaggerJson = {
render apiDocService.generateJSON()
}
}
Added a URLMapping for controller:
"/api/info"(controller: 'ApiDoc')
"/"(controller: 'Index')
"500"(controller: 'InternalServerError')
"404"(controller: 'NotFound')
Added a service ApiDocService.groovy:
//package com.care.apidoc
package grails.rest.example.apidoc
import io.swagger.jaxrs.config.BeanConfig
import grails.transaction.Transactional
import io.swagger.util.Json
#Transactional
class ApiDocService {
def swaggerConfig
/*
* generates SWAGGer JSON
*/
def generateJSON() {
String[] schemes = ["http"] as String[]
swaggerConfig.setSchemes(schemes)
swaggerConfig.setScan(true)
def swagger = swaggerConfig.getSwagger()
Json.mapper().writeValueAsString(swagger);
}
}
added Swagger-ui in src/main/webapp/dist folder
with a working customised API URL "http://localhost:8080/api/orders" in index.html
added CorsFilter setting in src/main/groovy/CorsFilter.groovy
import org.springframework.web.filter.OncePerRequestFilter
import javax.annotation.Priority
import javax.servlet.FilterChain
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
#Priority(Integer.MIN_VALUE)
public class CorsFilter extends OncePerRequestFilter {
public CorsFilter() { }
#Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws ServletException, IOException {
String origin = req.getHeader("Origin");
boolean options = "OPTIONS".equals(req.getMethod());
resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
resp.addHeader("Access-Control-Max-Age", "3600");
resp.addHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
resp.addHeader("Access-Control-Allow-Credentials", "true");
if (!options) chain.doFilter(req, resp);
}
}
On starting the server.
API for orders is working correctly, however, when I try to load the API in Swagger UI index file. it shows.
No operations defined in spec!
as attached in a pics.
Have you looked at springfox?
Here is a sample Grails Application hosted in Heroku that demonstrates the capabilities of springfox integrating with it to produce the service description in the Open API specification 2.0 (fka swagger). The source code for the demo is available here.
You can see this demo running live here demonstrating the Open API specification generated by the grails application and rendered using swagger-ui.
The library that makes this possible is springfox-grails-integration library. It is about to be released and probably needs a little bit of work to make it a grails plugin. There is some preliminary documentation of how to configure this the library repository.
NOTE: This only works with grails 3.x
Also it was a notable library showcased in the SHOW US YOUR GRAILS contest. Feedback to improve this library is much appreciated.

GWT-APACHE CXF header

I have a CXF JAX-RS service and a GWT MVP4G presenter.
I call the service with the RequestBuilder and set Content-Type header to application/json.
But in the server side REST method do not call .
REST code is :
class PlayerService{
#POST
#Path("addplayer")
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
String createOrSaveNewPLayerInfo(PlayerType playerType);
}
GWT code:
RequestBuilder rq = new RequestBuilder(RequestBuilder.POST, url)
rq.setHeader("Content-Type", "application/json");
rq.sendRequest(s, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
LOGGER.info(">" + response.getStatusCode() + "<");
}
#Override
public void onError(Request request, Throwable exception) {
LOGGER.info(">>" + exception.getMessage() + "<<");
}
});
I assume, that your GWT application is running on the Jetty server and your service on a Tomcat server. In this case you have two different ports: 8080 & 8888. Calling the service on 8080 will be blocked by the Same Origin Policy.
To solve this, you can switch off the policy (look for CORS). Bad idea.
Instead run your GWT application inside a Tomcat. In this case you will not have any problems with the SOP.
To set up a external server with GWT take a look here.

Authorisation issue while accessing a page from repository in CQ5.

I'm trying to hit a page which contains a xml structure. for that i'm using this code
#Reference
private SlingRepository repository;
adminSession = repository.loginAdministrative( repository.getDefaultWorkspace());
String pageUrl = "http://localhost:4504"+page+".abc.htm";
conn = (HttpURLConnection)new URL(pageUrl).openConnection();
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you'rusing Firefox 3.6.3
urlResponse = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader( new InputStreamReader(urlResponse) );
While accesing the page i'm getting this issue
org.apache.sling.auth.core.impl.SlingAuthenticator getAnonymousResolver: `Anonymous access not allowed by configuration - requesting credentials`
I'm logged in as an admin and whenever i'm directly hitting this urlfrom browser it is working properly bt while accessing it thriugh my code i'm getting this error.
any suggestion ?
If you are trying to call an url on an author instance, the following method I use in one of my projects might help (using apache commons HttpClient):
private InputStream getContent(final String url)
HttpClient httpClient = new HttpClient();
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getState().setCredentials(new AuthScope(null, -1, null),
new UsernamePasswordCredentials("admin", "admin"));
try {
GetMethod get = new GetMethod(url);
httpClient.executeMethod(get);
if (get.getStatusCode() == HttpStatus.SC_OK) {
return get.getResponseBodyAsStream();
} else {
LOGGER.error("HTTP Error: ", get.getStatusCode());
}
} catch (HttpException e) {
LOGGER.error("HttpException: ", e);
} catch (IOException e) {
LOGGER.error("IOException: ", e);
}
}
Though at it is using admin:admin it only works on a local dev instance, if you are on a productive environment, I wouldn't put the admin password in plaintext, even though it is onyl code...
You are mixing up sling credentials & http credentials. While you are logged in at the sling-repository the http session is not aware of any authentication informations!

Jersey Grizzly REST service not visible outside localhost

I'm trying to write a REST service in java using Jersey and Glassfish Grizzly. I have a very simple case working internally, but can't seem to call on the server from an external address. I've tried using a variety of different pairs of machines with externally visible IP's, and tried specifying the actual IP address in the server instead of localhost, but nothing works. I'm somewhat loosely following the official user guide here. My resource:
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/simpleREST")
public class SimpleRESTResource
{
#GET
#Produces("text/plain")
public String getMessage()
{
return "Message from server\n";
}
}
And the server:
import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main
{
public static final URI BASE_URI = UriBuilder.fromUri("http://localhost").port(9998).build();
public static void main(String[] args) throws IOException
{
System.out.println("Starting grizzly...");
ResourceConfig rc = new PackagesResourceConfig("resources");
HttpServer myServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
System.out.println(String.format("Jersey app started with WADL available at %s/application.wadl\n" +
"Try out %s/simpleREST\nHit enter to stop it...", BASE_URI, BASE_URI));
System.in.read();
myServer.stop();
}
}
On the same machine, I can successfully interact with the server using
curl -X GET localhost:9998/simpleREST
OR
curl -X GET [external numeric address]:9998/simpleREST
Many thanks in advance for any suggestions.
SOLUTION
I have fixed this problem by setting the server URI to http://0.0.0.0:9998 instead of localhost, 127.0.0.1, or the actual address.
To make a server IP adress visible outside of localhost, you must fist open the neccessary firewall ports(if you have one), or use "0.0.0.0" instead of "localhost" in order for the server to listen to all IP addresses and network adapters. Before testing it in your local network, try pinging your server device from your client device to check if there is an actual connection or if the devices are not connected at all.
With Jersey and Grizzly 2.30, it's simpler:
final ResourceConfig rc = new ResourceConfig().packages("com.rest");
HttpServer httpServer = Grizzly
HttpServerFactory.createHttpServer(URI.create("http://0.0.0.0:9998/api/"), rc);
or, you can try these codes below:
ResourceConfig rc = new PackagesResourceConfig("your-rest-packages");
HttpHandler handler = ContainerFactory.createContainer(HttpHandler.class, rc);
server = new HttpServer();
server.getServerConfiguration().addHttpHandler(handler);
//attach listeners
InetAddress localHost = InetAddress.getLocalHost();
String localHostAddr = localHost.getHostAddress();
NetworkListener localHostListener = new NetworkListener("localhost", localHostAddr, port);
server.addListener(localHostListener);
InetAddress loopback = InetAddress.getLoopbackAddress();
String loopbackAddr = loopback.getHostAddress();
NetworkListener loopbackListener = new NetworkListener("loopback", loopbackAddr, port);
now your server could both list to localhost and loopback