Error in establishing connection with HTTPS url - ssl

I have tried to establish https connection. I have loaded trustStore and password through following code:
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
String path = "/path to trust store";
String password = "password of trust store";
KeyStore keyStore = KeyStore.getInstance("p12");
InputStream inputStream = new FileInputStream(path);
keyStore.load(inputStream,password.toCharArray());
httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial((TrustStrategy) keyStore).build()));
CloseableHttpClient httpClient = httpClientBuilder.build();
HttpGet request = new HttpGet(this.backendUrl + url);
request.addHeader("Accept", "application/json");
String responseString = null;
try {
HttpResponse response = httpClient.execute(request);
if (logger.isDebugEnabled()) {
logger.debug("Request successful for " + url);
}
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (IllegalStateException e) {
logger.error("The response is empty ");
} catch (NullPointerException e) {
logger.error("Bad request to the URL");
} catch (IOException e) {
logger.error("mke");
}
I got an error in browser as:
The character encoding of the plain text document was not declared.
The document will render with garbled text in some browser configurations
if the document contains characters from outside the US-ASCII range.
The character encoding of the file needs to be declared in the
transfer protocol or file needs to use a byte order
mark as an encoding signature.

Related

rest-assured with pfx file always returns 401

From this source: RESTAssured - use .pfx certificate for https call
I created below.
#Test
void testPfxKey() {
// Source: https://stackoverflow.com/questions/42235588/restassured-use-pfx-certificate-for-https-call
FileInputStream instream1=null;
KeyStore keyStore=null;
org.apache.http.conn.ssl.SSLSocketFactory lSchemeSocketFactory=null;
try {
instream1 = new FileInputStream(new File("C:/Path/To/pfxfile.pfx"));
keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(instream1, "pfxfilepwd".toCharArray());
X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
lSchemeSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, "pfxfilepwd");
lSchemeSocketFactory.setHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
RestAssured.config = RestAssured.config().sslConfig(new SSLConfig().with().sslSocketFactory(lSchemeSocketFactory).and().allowAllHostnames().relaxedHTTPSValidation());
RestAssured.given().
contentType("application/json").
headers(
"Subscription-Key", "key-value",
"Accept-Encoding", "gzip,deflate"
);
Response response = RestAssured.get("https://endpoint.net/resource/path");
System.out.println(response.getStatusCode());
}
response.getStatusCode() always returns 401. I am expecting a 200. I have checked keyfile path, password and also the enpoint. All seem to be OK. When I run use ReadyAPI then I get a response. Please advice how to resolve this issue. Thanks you all!
I found this issue! I need to send headers with each request. Also .relaxedHTTPSValidation() should NOT be used in this case. We are in fact providing certificates that should be authenticated! Below code works:
#Test
void testPfxKey() {
FileInputStream instream1 = null;
KeyStore keyStore = null;
org.apache.http.conn.ssl.SSLSocketFactory lSchemeSocketFactory = null;
try {
instream1 = new FileInputStream(new File("C:/Path/To/pfxfile.pfx"));
keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(instream1, "pfxfilepwd".toCharArray());
X509HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
lSchemeSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, "pfxfilepwd");
lSchemeSocketFactory.setHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
RestAssured.config = RestAssured.config().sslConfig(new SSLConfig().with().sslSocketFactory(lSchemeSocketFactory).and().allowAllHostnames());
System.out.println(
RestAssured.given().
contentType("application/json").
headers(
"Subscription-Key", "key-value",
"Accept-Encoding", "gzip,deflate"
)
.get("https://endpoint.net/resource/path")
.getStatusCode()
);
}

How to get InputStream from MultipartFormDataInput?

I'm trying to save pdf in wildfly, I'm using RestEasy MultipartFormDataInput provided with wildfly 20.0.1,
but it doesn't work.
This is what I have:
public static Response uploadPdfFile(MultipartFormDataInput multipartFormDataInput) {
// local variables
MultivaluedMap<String, String> multivaluedMap = null;
String fileName = null;
InputStream inputStream = null;
String uploadFilePath = null;
try {
Map<String, List<InputPart>> map = multipartFormDataInput.getFormDataMap();
List<InputPart> lstInputPart = map.get("poc");
for(InputPart inputPart : lstInputPart){
// get filename to be uploaded
multivaluedMap = inputPart.getHeaders();
fileName = getFileName(multivaluedMap);
if(null != fileName && !"".equalsIgnoreCase(fileName)){
try {
// write & upload file to UPLOAD_FILE_SERVER
//here I have the error: Unable to find a MessageBodyReader for media type:
//application/pdf
inputStream = inputPart.getBody(InputStream.class,InputStream.class);
uploadFilePath = writeToFileServer(inputStream, fileName);
}catch (Exception e) {
e.printStackTrace();
}
// close the stream
inputStream.close();
}
}
}
catch(IOException ioe){
ioe.printStackTrace();
}
finally{
// release resources, if any
}
return Response.ok("File uploaded successfully at " + uploadFilePath).build();
}
I'm using postman for test, http POST method, in the body I send: form-data - file and selected the file.pdf.
When I sent the request, I have the next RunTimeException when I try:
inputStream = inputPart.getBody(InputStream.class,null);
I get:
java.lang.RuntimeException: RESTEASY007545: Unable to find a MessageBodyReader for media type: application/pdf and class type org.jboss.resteasy.util.Base64$InputStream
At the moment I am saving the file receiving it in Base64, but I think that with MultipartFormDataInput it is the correct way.
This is what I have when debug:
Thanks for your support.
I solved this changing the InputStream from "org.jboss.resteasy.util.Base64.InputStream"
to "java.io.InputStream"

Twitter streaming API - Error 401 Unauthorized

Running a java main program to call twitter streaming api. I have generated a bearer token and passing to the api. But getting the error response Error 401 Unauthorized
Is passing the bearer token right way to authenticate? If not what is the right way to do this?
SSLConnectionSocketFactory sslsf = getSSLConnectionFactory();
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpHost target = new HttpHost("stream.twitter.com", 443, "https");
new BasicHttpContext();
HttpPost httpPost = new HttpPost("/1.1/statuses/filter.json");
StringEntity postEntity = new StringEntity("track=birthday","UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
//httpPost.setHeader("Authorization", "Bearer " + Base64.encodeBase64(bearerToken.getBytes()));
httpPost.setHeader("Authorization", "Bearer " + bearerToken);
httpPost.setHeader("User-Agent", "Your Program Name");
httpPost.setHeader("Host", "stream.twitter.com");
HttpResponse response = httpClient.execute(target, httpPost,new BasicHttpContext());
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
if(buffer.length()>30000) break;
}
System.out.println(buffer);
//return new EventImpl(buffer.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}

download a certificate from a ldap server in java

Can someone explain to me whether following code is correct to download a certificate ties to a specific person in java? I am getting an exception as "unknown protocol: ldaps".
public void downloadCert() {
String urlStr="ldaps://aServerSomeWhere:636/cn=doe%20john,ou=personnel,o=comany123,c=us?caCertificate;binary";
URL url = null;
try {
url = new URL(urlStr);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(is);
System.out.println("getVersion: " + cert.getVersion());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
No it isn't correct. There is no handler for the LDAPS: protocol in the URL/URLConnection system.
You can use JNDI to get the caCertificate attribute of that user, via DirContext.getAttributes().

GWT: Sending PDF document from server to client

I have an RPC service and one of the method is generating a report using Pentaho Reporting Engine. Report is an PDF file. What I'd like to do, is when user request a report, the report is sent back to him and save dialog or sth pops up. I tried this inside my service method:
Resource res = manager.createDirectly(new URL(reportUrl), MasterReport.class);
MasterReport report = (MasterReport) res.getResource();
report.getParameterValues().put("journalName", "FooBar");
this.getThreadLocalResponse().setContentType("application/pdf");
PdfReportUtil.createPDF(report, this.getThreadLocalResponse().getOutputStream());
But it doesn't work. How it can be done?
I do it a little bit differently. I've got a separate servlet that I use to generate the PDF. On the client, do something like:
Cookies.setCookie(set what ever stuff PDF needs...);
Window.open(GWT.getModuleBaseURL() + "DownloadPDF", "", "");
The servlet, DownloadPDF looks something like this:
public class DownloadPDF extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
Cookie[] cookies = request.getCookies();
try {
// get cookies, generate PDF.
// If PDF is generated to to temp file, read it
byte[] bytes = getFile(name);
sendPDF(response, bytes, name);
} catch (Exception ex) {
// do something here
}
}
byte[] getFile(String filename) {
byte[] bytes = null;
try {
java.io.File file = new java.io.File(filename);
FileInputStream fis = new FileInputStream(file);
bytes = new byte[(int) file.length()];
fis.read(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
void sendPDF(HttpServletResponse response, byte[] bytes, String name) throws IOException {
ServletOutputStream stream = null;
stream = response.getOutputStream();
response.setContentType("application/pdf");
response.addHeader("Content-Type", "application/pdf");
response.addHeader("Content-Disposition", "inline; filename=" + name);
response.setContentLength((int) bytes.length);
stream.write(bytes);
stream.close();
}
}