FileNotFoundException: cert\jssecacerts and sessionId = 0 - spring

I am trying to connect to our server via websocket. I was able to get the session when I run in IDE. However, the session id is 0.
Also, when I compile and run this using java -jar, I got the following error. When running in IDE, I don't get this error as I set the working directory to src/main/resources where the cert folder is located:
java.io.FileNotFoundException: cert\jssecacerts (The system cannot find the path specified)
...
at org.apache.tomcat.websocket.WsWebSocketContainer.createSSLEnginer(WsWebSocketContainer.java:893)
Please advise.
WebSocketClient client = new StandardWebSocketClient();
WebSocketHandler handler = new TextWebSocketHandler();
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("Authorization", "Bearer " + getSignedToken());
URI uri = new URI("wss://<some server>");
((StandardWebSocketClient) client).getUserProperties().put(Constants.SSL_TRUSTSTORE_PROPERTY, "cert/jssecacerts");
((StandardWebSocketClient) client).getUserProperties().put(Constants.SSL_TRUSTSTORE_PWD_PROPERTY, Constants.SSL_TRUSTSTORE_PWD_DEFAULT);
WebSocketSession session = client.doHandshake(handler, headers, uri).get();

Regarding filenotfound, I figured it out.
Resource resource = new ClassPathResource("cert/jssecacerts");
...
((StandardWebSocketClient) client).getUserProperties().put(Constants.SSL_TRUSTSTORE_PROPERTY, resource.getFile().getAbsolutePath());

Related

Using URI with HTTPS

I wrote a program on UWP that stores text in a .txt file which is then voiced to the client. This worked really well when using an HTTP URI but now that site uses HTTPS the program crashes with the error:
System.Net.Http.HttpRequestException: 'Response status code does not indicate success: 401 ().'
The line that it crashes on is:
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If I change the link to HTTP the program works fine again. Does anyone know how I can fix this please? Or is it just not possible?
var uriBing = new Uri(#"https://mydomain/net/hal2001/Actions/HALSpeak/speak.txt");
//set storageFolder as the location of the local app storage folder.
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
//Create a local file to be used to write the URL file to.
StorageFile sampleFile2 = await storageFolder.CreateFileAsync("status2.txt", CreationCollisionOption.ReplaceExisting);
//Write to local file the value stored in the URL file so they match.
var cli = new HttpClient();
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
If Have tried the following but still not happy.
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("username", "pass");
HttpClient cli = new HttpClient(handler);
I checked the IIS server application > SSL Settings and SSL Settings is set to 'Require SSL' with client certificates set to Accept.

Spring Boot and ConfigServer

We have a SpringBoot application which is successfully comunicating with config server.
The question I have is... say we have a application properties file and a csv file in config server.
when application starts if we want to get the contents of csv file too whats the better approach.
We are able to get it by doing a direct http connection to configserver and retreive the csv file contents
String url = configServerURL+"/*/*/*/example.csv";
byte[] encoded = Base64.encode((uname + ":" + password).getBytes());
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Authorization", "Basic "+encoded);
int responseCode = con.getResponseCode();
wanted to check what options are there.

How do I replace an existing Community file on IBM SmartCloud

I am trying to replace an existing Community file using the following java
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("createVersion", "false");
fileEntry = fileService.updateCommunityFile(fis, fileUuid, fileName, communityLibraryId, paramsMap);
But it is returning a HTTP 411:Length required error.
I am using the latest build (1.1.5.20150520-1200.jar)
Does anyone have a suggestion as to what i am missing?
I tried recreating the issue but I am able to upload New version of Community file correctly with and without version, using the updateCommunityFile API. I do not get any Length related error. This is the snippet I am using :
java.io.File file = new java.io.File("C://TestUploadCommunity.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (Exception e) {
//TODO
}
fileEntry = fileService.updateCommunityFile(fis, fileEntry.getFileId(), fileEntry.getLabel(), communityLibraryId, params);
Can you share more details on your sample, what exactly is your fis?
I have tried this on 2 environments and I do not see any issue.
Also, from the entry you have pasted,
"Request to url apps.na.collabserv.com/files/basic/api/library... /document/... /entry?content-length=6600&createVersion=false returned an error response 411:Length Required HTTP/1.1 411"
It seems that somehow an incorrect content-length is passed for your request.
Can you share the sample that you are using?

(401) Unauthorized Error When Calling Web API from a Console Application

When I call my WEB API from my Console Application, I encounter:
The remote server returned an error: (401) Unauthorized.
This application runs in Interanet (Windows Authentication)
Uri uri = new Uri("http://myServer/api/main/foo");
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
using (Stream data = client.OpenRead(uri))
{
using (StreamReader sr = new StreamReader(data))
{
string result = sr.ReadToEnd();
Console.WriteLine(result);
}
}
Updated
If I replace
client.Credentials = CredentialCache.DefaultCredentials;
with this line
client.Credentials = new NetworkCredential( username, password);
it works fine but I need the current credential to be set automatically.
Any idea?
Thanks in advance ;)
You use the default windows credentials here
client.Credentials = CredentialCache.DefaultCredentials;
Specify the credential that you want to authenticate using the following code:
var credential = new NetworkCredential(, , );
serverReport.ReportServerCredentials.NetworkCredentials = credential;
following line is the cause of this behaviour :
client.Credentials = CredentialCache.DefaultCredentials;
Actually this line assigns the credentials of the logged in user or the user being impersonated ( which is only possible in web applications ) , so what I believe is that you have to provide credentials explicitly (http://msdn.microsoft.com/en-us/library/system.net.credentialcache(v=vs.110).aspx) , thanks.

WebClient NotFound error but working with HttpWebRequest/Response

In my WinPhone app I'm accessing a REST service.
At the beginnings I was using this code:
WebClient wc = new WebClient();
wc.Credentials = credentials;
wc.Headers["App-Key"] = appKey;
wc.DownloadStringCompleted +=
(o, args) => MessageBox.Show(args.Error == null ? "OK" : "Error");
wc.DownloadStringAsync(uri);
but it suddenly stopped working returning me a "The remote server returned an error: NotFound" error. After a google session and some clicks in the control panel, I didn't get it to work.
I decided to try this other way:
HttpWebRequest request = HttpWebRequest.CreateHttp(uri);
request.Credentials = credentials;
request.Headers["App-Key"] = appKey;
request.BeginGetResponse(asResult =>
{
var response = request.EndGetResponse(asResult) as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseString = reader.ReadToEnd();
Dispatcher.BeginInvoke(
() => MessageBox.Show(response.StatusCode.ToString()));
}, null);
and it works.
I also tried to run the first snipped pointing the URI to google's home page and it works (I had to remove the credentials, of course).
Can anyone explain what's going on?
UPDATE
I managed to get it working by replacing the
wc.Credentials = new NetworkCredentials(username, password);
with
wc.Headers["Authorization"] = "Basic someBase64encodedString";
but i still wonder what happened and which are the differences between the first and the second line.
PS: the test URI is: https://api.pingdom.com/api/2.0/checks but you will need an app-key from them.
When using the Credentials property, the HttpWebRequest implementation will wait the challenge response from server before to send the 'Authorization' header value.
But this can be an issue in some cases, so you have to force Basic authentication by providing directly the Authorization header.
Example when using a REST Client library like Spring.Rest :
RestTemplate template = new RestTemplate("http://example.com");
template.RequestInterceptors.Add(new BasicSigningRequestInterceptor("login", "password"));
string result = template.GetForObject<string>(uri);

Resources