Resteasy client not working from office, but working from home - rest

I am using RestEasy client api, to make call to some internal api, but when I run the code from my home I am able to get the response without any timeout exception. But when I run from office getting timeout execution, am I missing any configurations?
I/O exception (java.net.ConnectException) caught when processing request: Operation timed out
Below the code am using:
ClientRequest request = new ClientRequest(
"https://example.com/v2");
request.queryParameter("name", "jhon");
request.accept("application/json");
ClientResponse<String> response = request.get(String.class);
if(response.getStatus() == 404){
System.out.println(response.getEntity());
System.out.println(response.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(response.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
JSONObject d = new JSONObject(output);
JSONObject sd = d.getJSONObject("Error");
System.out.println(sd.get("Detail"));
}

Related

Karate ApacheHttpClient Response is failing with error com.intuit.karate - Runtimejava.io.IOException: Attempted read from closed stream

Reference: java.io.IOException: Attempted read from closed stream
Reference: https://github.com/karatelabs/karate/blob/master/karate-core/src/main/java/com/intuit/karate/http/ApacheHttpClient.java
KarateCore - class file: ApacheHttpClient.java is unable to process the Response its failing at the code line
CloseableHttpClient client = clientBuilder.build();
CloseableHttpResponse httpResponse;
byte [] bytes;
try {
httpResponse = client.execute(requestBuilder.build());
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity == null || responseEntity.getContent() == null) {
bytes = Constants.ZERO_BYTES;
} else {
**InputStream is = responseEntity.getContent();**
bytes = FileUtils.toBytes(is);
}
request.setEndTimeMillis(System.currentTimeMillis());
} catch (Exception e) {
if (e instanceof ClientProtocolException && e.getCause() != null) { // better error message
throw new RuntimeException(e.getCause());
} else {
throw new RuntimeException(e);
}
}
The Code is failing at line InputStream is = responseEntity.getContent(); when trying to read from a closed stream. The exception message displayed
Error com.intuit.karate - Runtimejava.io.IOException: Attempted read from closed stream.
May be the InputStream need to updated.
I am able read the Http Response content using below code
BufferedReader br = new BufferedReader(
new InputStreamReader((httpResponse.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null){
output = br,readLine();
System.out.println(output);
}
Also the able to read the response using EntityUtils as a string content
String content = EntityUtils.toString(responseEntity);
System.out.println(content);
Not sure if i am missing something in the feature:scenario file response or the ApacheHttpClient.java file need to updated to read InputStream and then convert to bytes.
Feature: Hello
Scenario: Rest API Post
Given url 'some url path'
And header Content-Type = 'application/json'
And request { username: 'abc', password: 'pwd' }
When method POST
Then status 200
And print 'Response is:', response
The expected Response is a JSON format as:
{
"accessToken": "akjdoioikf",
"expires":"2020-01-29T01:09:48Z"
}
Any suggestions, appreciated!

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.

Error empty content gmail using javamail api send email smtp

I'm working project : jsf, richfaces. I has just updated javamail api newest version 1.5.5 at https://java.net/projects/javamail/pages/Home
When i test send email from gmail to my gmail,
Subject : Subject test.
Content : Content test. And config : smtp.gmail.com, 465, SSL.
It has just subject and no content in my inbox receive gmail :
And log :
And my code :
try {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Set the host smtp address
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.ssl.trust", "*");
props.put("mail.smtp.ssl.socketFactory", sf);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
.......
.......
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setText("UTF8");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(SMTP_AUTH_USER);
msg.setFrom(addressFrom);
System.out.println(addressFrom);
msg.setSubject(subject, "utf-8");
......
......
try {
String content = replaceCharacterInEmail(cus, null,null, message);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(content, "text/html; charset=utf-8");
// attach the file to the message
Multipart mp = new MimeMultipart();
int count = 0;
if(files != null){
while (count < files.size()) {
MimeBodyPart mbdp = new MimeBodyPart();
mbdp.attachFile(files.get(count));
mp.addBodyPart(mbdp);
count++;
}
}
// create the Multipart and add its parts to it
mp.addBodyPart(mbp1);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);
} catch (Exception e) {
invalidAddress += (", " + address.trim());
e.printStackTrace();
}finally{
if (!"".equals(emailFails)) {
emailFails = emailFails.substring(1);
}
}
But, when i test above code at another project test (java application) with above lib javamail. It's ok :
.
I don't think problem at version of lib javamail. I don't know different between 2 project, because part send email is similar. How can i fix that error ?
Please observe this email structure:
-- multipart/mixed
-- mutlipart/alternative
-- text/plain
-- text/html
-- application/octet-stream (or any other mimetypes)
I found problem is conflict library at lib of jboss server and lib of app.ear (deploy).

How to bypass SSL certificates issue in JBOSS REST ClientRequest

I'm new in Jboss, and using rest easy client for connection in my jboss code. Below is the code -
---
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
---
public String login() throws Exception {
---
String URL = "https://IP//service/perform.do?operationId=XXXXX";
ClientRequest restClient = new ClientRequest(URL);
restClient.accept(MediaType.APPLICATION_JSON);
restClient.body(MediaType.APPLICATION_JSON, hmap);
ClientResponse < String > resp = restClient.post(String.class);
if (resp.getStatus() != 201) {
throw new RuntimeException("Failed : HTTPS error code : " + resp.getStatus());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(resp.getEntity().getBytes())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
return output;
}
While connecting with SSL enabled server, getting certificate error "HTTP Status 500 - org.jboss.resteasy.spi.UnhandledException: javax.net.ssl.SSLException: hostname in certificate didn't match".
We can't change certificate at this moment, but is there any way to trust any certificate? I googled many posts, but nothing helped.
Anyone can tell me what is the solution of this issue.

How to access Spring REST API in JHipster with standalone

i need to call de jhipster rest service in a java sheduling standalone.
but i dont know how, I try with HttpClient libraries and use CredentialsProvider to set de username and password
I cant login use this
HttpGet httpget = new HttpGet("http://localhost:8080/#Login");
but when I try to get de rest jason api i get HTTP 401 Unauthorized
I see de Gatlin Test make in scala and its like there are simulating a web-browser.
So I am stacking here, and I will apreciate anybody that can give me some suggest in how to do these.
These is the code
HttpHost targetHost = new HttpHost("localhost", 8080, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(DEFAULT_USER,DEFAULT_PASS));
AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
String output;
In this call a have de estatus 401
response = client.execute(new HttpGet(URL_PROMOTORES), context);
statusCode = response.getStatusLine().getStatusCode();
System.out.println("Estatus Codee : " +statusCode);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
response.close();
client.close();
Thanks in advance.
I don't think you should use basicAuth because it is for HTTP basic authentication (RFC 2617) which is different from what JHipster uses in your case login/password form encoded and session.