How to define a custom port for the WebDAV server using sardine? - webdav

In Sardine how do I change the port number to something different from port 80 (for HTTP) and 443 (for HTTPS)?
The User guide states that I have to "override SardineImpl#createDefaultSchemeRegistry() or provide your own configured HTTP client instance by instantiating SardineImpl#SardineImpl(org.apache.http.impl.client.HttpClientBuilder)" but I can't find how to define the port.
When I instantiate SardineImpl using:
HttpClientBuilder builder = HttpClientBuilder.create();
SardineImpl sardine = new SardineImpl(builder, "user", "password");
byte[] data;
data = FileUtils.readFileToByteArray(new File("test.txt"));
sardine.put("http://webdav-server:8095/projects/", data);
I obtain:
org.apache.http.NoHttpResponseException: webdav-server:8095 failed to respond
The server is accessible via browser so the problem must be with the definition of the port and I could not find an example on how to do this.
Can someone help me on this? Thanks in advance.

This is what I figured out after racking my brain trying to find a solution. Hopefully it helps someone else:
HttpClientBuilder builder = new HttpClientBuilder(){
#Override
public CloseableHttpClient build() {
SchemePortResolver spr = new SchemePortResolver() {
#Override
public int resolve(HttpHost httpHost) throws UnsupportedSchemeException {
return 8443; // SSL port to use
}
};
CloseableHttpClient httpclient = HttpClients.custom()
.useSystemProperties()
.setSchemePortResolver(spr)
.build();
return httpclient;
}
};
Sardine sardine = new SardineImpl(builder, "user", "passwd");
List<DavResource> resources = null;
resources = sardine.list("https://ftp-site.com/path/");
resources.forEach(resource -> {
System.out.println(resource.getName());
}
Hope that helps somebody.

Related

FeignClient configuration in ASP.Net

I am trying to create microservices using Spring-boot Java and SteelToe ASP.NET
Step-1: I created a full service using Java (A service with UI and API. It is hosted on PCF). The API has ClassesControler defined inside.
Step-2: Create a microservice using ASP.NET, SteelToe. Register the service in Eureka and make it discoverable using Zuul.
Step-3: Use the Interface, Service approach to access the JAVA microservice(s)
namespace employee-client.Service
{
public interface IRelayService
{
Task<HttpResponseMessage> getClassesList(string relativeUrl = "/api/v1/classes");
}
}
Service with Implementation for Interface:
namespace employee-client.Service
{
public class RelayService : IRelayService
{
DiscoveryHttpClientHandler _handler;
string _accessToken;
private const string BASE_URL = "https://www.example.com";
public QortaService(IDiscoveryClient client, string accessToken)
{
_handler = new DiscoveryHttpClientHandler(client);
_accessToken = accessToken;
}
public async Task<HttpResponseMessage> getClassesList(string relativeUrl)
{
string classesUrl= BASE_URL + relativeUrl;
HttpClient client = GetClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri(classesUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
return await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
}
private HttpClient GetClient()
{
var client = new HttpClient(_handler, false);
return client;
}
}
}
I came up with this approach based on the example in SteelToe but I hate hardcoding the BASE_URL.
Question: I very much like the #FeignClient annotation approach used in Java. Any ideas about how I can access an existing microservice in a better way. If so, an example would be much appreciated
Edit:
I modified the question to make more clear.
The flow of traffic is from Java Service to .NET service. .NET service requests for a list of classes from the controller in JAVA service (ClassesController.java)
I'm unclear which direction traffic is flowing in your scenario, but I think you're saying the .NET application is trying to call the Java application. The code you're using is from before HttpClientFactory was introduced and is a bit clunkier than what's possible now in general. Steeltoe can be used with HttpClientFactory for a better overall experience.
Steeltoe has debug logging available to confirm the results of service lookup if you set logging:loglevel:Steeltoe.Common.Discovery = true in your application config.
You didn't mention specifically what isn't working, but I'm guessing you're getting a 404 since it looks like your code will create a request path looking like https://fortuneService/api/fortunes/random/api/v1/classes
If you're looking for something like Feign in .NET, you could try out DHaven.Faux
For others who are looking for the same:
namespace employee-client.Service
{
public class RelayService : IRelayService
{
private const string CLASSES_API_SERVICEID = "classes-api";
IDiscoveryClient _discoveryClient;
DiscoveryHttpClientHandler _handler;
string _accessToken;
public RelayService(IDiscoveryClient discoveryClient, string accessToken)
{
_discoveryClient = discoveryClient;
_handler = new DiscoveryHttpClientHandler(client);
_accessToken = accessToken;
}
public async Task<HttpResponseMessage> getClassesList()
{
var classesApiInstances = _discoveryClient.GetInstances(CLASSES_API_SERVICEID);
Uri classesApiUri = classesApiInstances[0].Uri;
string classesUrl= classesApiUri.AbsoluteUri + relativeUrl;
HttpClient httpClient = GetClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri(classesUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
return await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
}
private HttpClient GetClient()
{
var client = new HttpClient(_handler, false);
return client;
}
}
}

Setting up ssl for http: ^0.12.0 package

I wonder how can I setup ssl for http(http: ^0.12.0) package in Flutter,
without migrating to dart:io.
Currently I'm using:
http.Client httpClient = http.Client();
and I do not see any options there to setup ssl.
Do I have to use
final SecurityContext context = SecurityContext.defaultContext;
HttpClient client = HttpClient(context);
from dart:io?
You can create a HttpOverride to make the Client ignore bad certificates as mentioned on this GitHub issue ticket. This is only recommended to be used in development builds.
class DevHttpOverrides extends HttpOverrides {
#override
HttpClient createHttpClient(SecurityContext? context) {
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
}
}
Then initialize the HttpOverride to be used.
HttpOverrides.global = DevHttpOverrides();

Single Instance of HttpClient with UseDefaultCredentials

I have been trying to update my API call using the suggestion from here
to only have 1 instance of HttpClient. https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/#
This works fine and I have my do not use up all of the ports, however when I try to create a HttpClientHandler to pass along the default credentials my ports start being used up again. My API is setup to use Windows Auth for security reasons so I need to pass along the app pools credentials for a successful call.
Here are the 2 code blocks
public static class WebApiCallUtility
{
private static HttpClientHandler _handlerNoCred = new HttpClientHandler();
private static HttpClient _clientNoCred = new HttpClient(_handlerNoCred);
private static HttpClientHandler _handlerCred = new HttpClientHandler { UseDefaultCredentials = true };
private static HttpClient _clientCred = new HttpClient(_handlerCred);
//Working ports are not used up
public static HttpResponseMessage SendHttpGetRequestNoCred(string webApiUrl, string logSourceName, string subId)
{
_clientNoCred.DefaultRequestHeaders.Accept.Clear();
_clientNoCred.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = _clientNoCred.GetAsync(webApiUrl).Result;
return result;
}
//No working tons of ports open hanging out with TIME_WAIT status
public static HttpResponseMessage SendHttpGetRequestCred(string webApiUrl, string logSourceName, string subId)
{
_clientCred.DefaultRequestHeaders.Accept.Clear();
_clientCred.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result = _clientCred.GetAsync(webApiUrl).Result;
return result;
}
}
Any help would be appreciated.
Thanks
I was able to revolve this issue buy using a different handler type
private static WebRequestHandler _handlerCred = new WebRequestHandler
{
UseDefaultCredentials = true,
UnsafeAuthenticatedConnectionSharing = true
};
private static HttpClient _clientCred = new HttpClient(_handlerCred);
I found this answer here Static HttpClient still creating TIME_WAIT tcp ports

Is there any way i get the reference of ChannelPipeline created when i a client connect to server on serverside?

In case of synchronous TCP server when ever a client connects i get a reference of Client example :
int serverPortNum = 9000;
socket while(true) {
ServerSocket connectionSocket = new ServerSocket(serverPortNum);
Socket dataSocket = connectionSocket.accept( );
// pass this reference(dataSocket ) to other part of program to read or write depending on app logic
}
Now i want to use asynchronous TCP Server using Netty so is there any way i can get the reference of ChannelPipeline or ChannelHandler created when a new client is connected.
On Client Side I can do it easily : sample code :
NioClientSocketChannelFactory ncscf = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool());
ClientBootstrap clientBootstrap = new ClientBootstrap(ncscf);
final DummyHandler dummy = new DummyHandler();
clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
#Override
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(dummy);
}
});
InetAddress inetaddress = InetAddress.getByName(host);
ChannelFuturecf=clientBootstrap.connect(newInetSocketAddress(inetaddress,port));
So every time i create a new client i have new DummyHandler reference
On Server Side : sample Code :
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new DummyServerHandler());
}
});
bootstrap.bind(new InetSocketAddress(port));
So when client request connection new DummyServerHandler object is created but i cannot get reference of this.
I may missunderstood the question but wouldn't this work.
Channel.getpipeline()

flex4 socket problem

I'm trying to communicate my flash application with my server. Either the problem is my code is working on Flash Professional, but I have prepared all my interface on Flash Builder which uses Flex 4 -SDK. My code does not work on Flex Project.
The problem is not security file. I can not solve the problem. What are the possible reasons?
Kind Regards.
If necessary my code is below [working on FlashPro but not on Flex ! ]
import flash.net.*;
import flash.events.Event;var host:String = new String("127.0.0.1");
var port:int = 8080;
var securityFile:String = "http://localhost:1755/.../..../s....xml";
var bagli:Boolean = false;
var socket:Socket = null;
var veri:String = new String("----");
btnGonder.addEventListener(MouseEvent.MOUSE_DOWN, tiklantiEvent);
function buildSocket():void
{
trace("beginning....");
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnect);
socket.addEventListener(Event.CLOSE, onClose);
socket.addEventListener(ErrorEvent.ERROR, onError);
socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
socket.addEventListener(ProgressEvent.SOCKET_DATA, onResponse);
Security.allowDomain(host);
Security.loadPolicyFile(securityFile);
try {
socket.connect(host, port);
bagli = true;
trace("--- connection...");
} catch (error:Error) {
trace("--- connection failed...");
socket.close();
}
}
function send(string:String):void {
socket.writeUTFBytes(string);
socket.flush();
}
function onConnect(event:Event):void {
trace("connect");
}
function onClose(event:Event):void {
trace("closed");
}
function onError(event:IOErrorEvent):void {
trace("connection erron");
}
function onIOError(event:IOErrorEvent):void {
trace("data error");
}
function onResponse(event:ProgressEvent):void {
var string:String = socket.readUTFBytes(socket.bytesAvailable);
trace(string);
}
function (sender:Event):void {
trace("clicked button....");
buildSocket();
trace("------------------");
}
You are trying to authorize a socket connection by using a content-type policy file. You should use socket policy file instead. Policy file syntax is the same as far as I remember, but the url should begin with xmlsocket:// instead of http://. This file should not be served through http.
Furthermore, the host's domain and the domain from the policy file address should be exactly the same. Given that your host is specified as 127.0.0.1, change the policy file url to
xmlsocket://127.0.0.1:1755
For more details see Adobe's guidelines for policy files.

Resources