cxf local transport JAX_WS - cxf

I Am using CXF framework to implement JAX_WS soap web service. I want to make use of local transport to call a webservice in another web service with out using actual endpoint. any examples?
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setServiceBean(new LocalTransportSample_Service().getLocalTransportSamplePort());
factory.setAddress("local://hello");
factory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
Server server = factory.create();
JaxWsProxyFactoryBean proxyFac = new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://hello");
proxyFac.getClientFactoryBean().setTransportId(LocalTransportFactory.TRANSPORT_ID);
LocalTransportSample exc = proxyFac.create(LocalTransportSample.class);
return exc.hello("I am from local transport");

JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setServiceBean(new LocalTransportSample_Service().getLocalTransportSamplePort());
factory.setAddress("local://hello");
factory.setTransportId(LocalTransportFactory.TRANSPORT_ID);
Server server = factory.create();
JaxWsProxyFactoryBean proxyFac = new JaxWsProxyFactoryBean();
proxyFac.setAddress("local://hello");
proxyFac.getClientFactoryBean().setTransportId(LocalTransportFactory.TRANSPORT_ID);
LocalTransportSample exc = proxyFac.create(LocalTransportSample.class);
return exc.hello("I am from local transport");

Related

s it possible to implement file upload function?

We are implementing file download function.
UI, service API server, and file server (external server) exist, and I cannot access the file server. (Code cannot be changed)
Currently, a file is downloaded by requesting UI -> FileServer.
I want to configure UI -> Service API -> File Server for multiple file downloads and exception handling.
As the service API operates in the middle, the final value of http that the client receives is different, but I don't know why.
Existing file servers returned an ArrayBuffer,
It was changed to a long string in String format while going through my service API server.
// my Server -> fileServer (GET Http Request)
// setting header...
// setting uri...
HttpEntity req = new HttpEntity<>(httpHeaders);
RestTemplate rt = new RestTemplate();
HttpEntity<byte[]> result = rt.exchange(
uri,
HttpMethod.GET,
req,
byte[].class
);
byte[] blob = result.getBody();
The reason why I received byte[] through result.getBody() is that I thought that the return value of the file server would be a file, and it would be a byte[] type in Java.
// react (client code)
// blobFromApi = The result my server responded
let blob = new Blob([blobFromApi], { type:'image/png' });
if (navigator.userAgent.match('CriOS')) {
let reader = new FileReader();
reader.onload = function (e) {
window.location.href = reader.result;
};
reader.readAsDataURL(blob);
} else {
FileSaver.saveAs(blob, file.file_name);
}
});
In conclusion, is it possible to implement a file download function in my current situation?

AddHttpClient in Blazor Server Side

I'm trying to create an httpclient in Blazor Server side which would create the least amount of configuration effort every time I call my webapi.
Essentially I would like achieve the following:
Named HTTPClient I can automatically call when I call a function in my webapi.
The webapi requires a bearer token, which I get by calling AcquireTokenSilent
Would be great if I don't have to specify the httpclient when I call the api
The webapi has been added as a service reference, so there is scaffold classes created under the namespace myapp.server.api
To start this off, I created the following in startup:
services.AddHttpClient<myapp.server.api.swaggerClient>(c =>
{
c.BaseAddress = new Uri("https://api.myapp.com/");
AzureADB2COptions opt = new AzureADB2COptions();
Configuration.Bind("AzureAdB2C", opt);
IConfidentialClientApplication cca =
ConfidentialClientApplicationBuilder.Create(opt.ClientId)
.WithRedirectUri(opt.RedirectUri)
.WithClientSecret(opt.ClientSecret)
.WithB2CAuthority(opt.Authority)
.WithClientName("myWebapp")
.WithClientVersion("0.0.0.1")
.Build();
IHttpContextAccessor pp;
string signedInUserID = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
new MSALStaticCache(signedInUserID, pp.HttpContext).EnablePersistence(cca.UserTokenCache);
var accounts = cca.GetAccountsAsync().Result;
AuthenticationResult result = null;
result = cca.AcquireTokenSilent(opt.ApiScopes.Split(' '), accounts.FirstOrDefault()).ExecuteAsync().Result;
c.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
My hope is to be able to call my api in my views in this way:
myapp.server.api.swaggerClient t = new myapp.server.api.swaggerClient();
currentCount = t.WeatherForecastAsync().Result.FirstOrDefault().Summary;
calling a new instance of swaggerclient requires me to specify an httpclient, so my hopes is to inject the httpclient I am configuring on a global level for that type can be injected automatically.
The pieces I need help with:
Given that I have specified my httpclient scoped to a specific type, would it call automatically if I call a function in my webapi? (Does not seem to fire when debugging)
To get the bearer token, I need to get the current userID, which is in the authstateprovider... seeing that this is in Startup, is getting it from DI even possible?
Any easy way to inject the httpclient on the constructor of my webapi classes? would I be able to get the httpclient in the constructor so that I essentially have a parameterless constructor not asking for httpclient?
Concerning your first question, inject the Web API HttpClient like this in your view:
#inject myapp.server.api.swaggerClient MyClient
and then in the code block:
currentCount = MyClient.WeatherForecastAsync().Result.FirstOrDefault().Summary;
You should be able to debug the code inside AddHttpClient.

Set SOAP addressing header in server side CXF service implemenion

I have web service implemented in Apache CXF. Is there way how can I set SOAP header to request (server side) using AddressingProperties?
This works for me:
List<Header> headers = new ArrayList<Header>();
Header messageIDHeader = new Header(new QName("http://www.w3.org/2005/08/addressing", "MessageID", "wsa"), some_messageID, new JAXBDataBinding(String.class));
headers.add(messageIDHeader);
Header relatesToHeader = new Header(new QName("http://www.w3.org/2005/08/addressing", "RelatesTo", "wsa"), some_relatesTo_ID, new JAXBDataBinding(String.class));
headers.add(relatesToHeader);
wsContext.getMessageContext().put(Header.HEADER_LIST, headers);
But I would like to use org.apache.cxf.ws.addressing.AddressingProperties - something like this:
RelatesToType soapRelatesTo = new RelatesToType();
soapRelatesTo.setValue(some_relatesTo_ID);
soapAddressingHeaders.setRelatesTo(soapRelatesTo);
AttributedURIType soapMsgId = new AttributedURIType();
soapMsgId.setValue(some_messageID);
soapAddressingHeaders.setMessageID(soapMsgId);
How can I pass that to request? I am not able to set it through MessageContext
Adding soapAddressingHeaders to MessageContext
messageContext.put("http://www.w3.org/2005/08/addressing", soapAddressingHeaders);
works correctly but I forgot to enable WS-A addressing for CXF:
<jaxws:features>
<wsa:addressing xmlns:wsa="http://cxf.apache.org/ws/addressing"/>
</jaxws:features>

YouTube API Resumable Uploader Session Token

I am working with the YouTube api trying to upload a video using the resumable uploader. I would really rather not have to directly ask the user for their credentials.
I am able to use AuthSub and get a session token. The problem is I cant seem to use this with the resumable uploader. Is this possible or is this totally separate? I see that GDataCredentials can take a client token. What is this? I i use the session token I get back Error = {"The remote server returned an error: (401) Unauthorized."}
Here is my code
Video newVideo;
var mResumableUploader = new ResumableUploader(10485760);
mResumableUploader.AsyncOperationCompleted += mResumableUploader_AsyncOperationCompleted;
mResumableUploader.AsyncOperationProgress += mResumableUploader_AsyncOperationProgress;
var youTubeAuthenticator = new ClientLoginAuthenticator(AppName, ServiceNames.YouTube, new GDataCredentials(YouTubeToken));
youTubeAuthenticator.DeveloperKey = DevKey;
newVideo = new Video();
newVideo.Title = "video";
newVideo.Tags.Add(new MediaCategory("Entertainment", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "video";
newVideo.Description = "video";
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FilePath, "video/mp4");
var link = new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads");
link.Rel = ResumableUploader.CreateMediaRelation;
newVideo.YouTubeEntry.Links.Add(link);
mResumableUploader.InsertAsync(youTubeAuthenticator, newVideo.YouTubeEntry, "inserter");
ClientLogin is problematic and will be deprecated soon. Please use OAuth2 and you won't have problems.

cxf: wsdl2java created a class that extends Service (javax.xml.ws.Service)

I am new to java WS and WSDL.
I used wsdl2java to create java classes for my web service client and there was a class created with <Service Name>Service extends javax.xml.ws.Service
Please let me know what is the use of the class
I think of this as a 'locator' or 'factory' which can be used for making client-side (proxy) instances of the service. For example (where 'Example' is the Service Name):
ExampleService locator = new ExampleService();
locator.addPort( ExampleService.Example, SOAPBinding.SOAP11HTTP_BINDING
, "http://myserver:8080/myapp/services/example" );
// now get the instance
Example example = locator.getExample();
Though with CXF you can use utilities such as the JaxWsProxyFactoryBean and ignore the <Service Name>Service class. Eg:
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(Example.class);
factory.setAddress("http://myserver:8080/myapp/services/example");
factory.setUsername("user");
factory.setPassword("password");
Example example = (Example) factory.create();

Resources