I am trying to use Apache Wink to get Service Document from an IBM host but I always get error 403 Forbidden. Here is my code :
import org.apache.wink.client.Resource;
import org.apache.wink.client.RestClient;
public class CommunityEvents {
private String uri = "https://w3-connections.ibm.com/profiles/atom/search.do?name=Nam,+Vu+Hoai";
public CommunityEvents() {
RestClient restClient = new RestClient();
Resource resource = restClient.resource(uri);
System.out.println(resource.get().getMessage());
}
public static void main(String[] args) {
new CommunityEvents();
}
}
The link is working fine when I put it into browser address. I have tried with other https and they worked.
Can someone correct my code or tell me what I missed ? what I need to do to access the link above ?
Thank you so much !
is the URL trusted by your JVM? I imagine it's a CACERTS issue. You'll want to extract the certificate using your browser, and use the keytool to import it into your JVM CACERTS.
Also Wink supports JSON and other resource styles, make sure you have the right library for ATOM+XML which is the current resource URL you selected.
Related
I am trying to retrieve the details of a destination using the APIs provided by SAP Cloud SDK for JAVA. I have added the following annotations to our Spring Boot application:
#ComponentScan(basePackages = {"com.sap.cloud.sdk", "path to my package"}, excludeFilters = {#ComponentScan.Filter(type = CUSTOM, classes = TypeExcludeFilter.class)})
#ServletComponentScan({"com.sap.cloud.sdk", "path to my package"})
#SpringBootApplication()
public class ActionApplication {
public static void main(final String[] args) {
SpringApplication.run(ActionApplication.class, args);
}
}
The SpringBoot application internally uses a JAVA library developed by us. The code for fetching the destination details is present in this library:
public static Destination getDestination() {
Tenant consumerTenant = TenantAccessor.getCurrentTenant();
return TenantAccessor.executeWithTenant(consumerTenant,
() -> DestinationAccessor.getDestination(destinationName));
}
I am able to get the destination details EVERY TIME I run my application locally.
However, when I run my application on cloud, after a few successful attempts, I get the following error:
"com.sap.cloud.sdk.cloudplatform.thread.exception.ThreadContextExecutionException: com.sap.cloud.sdk.cloudplatform.connectivity.exception.DestinationAccessException: Failed to get destination with name 'name_of_the_destination'."
To resolve the issue, I have to re-deploy my Spring Boot application.
Is anything wrong with the implementation? What I understand from the logs is, the threadcontext is not set correctly.
DefaultHttpDestination should be used when building a destination instead of the MockUtil test class. The built destination should also be registered in a DefaultDestinationLoader, and this DefaultDestinationLoader should be prepended in the DestinationAccessor.
I want to use user secrets for KeyVault clientid etc. I call my configs from program.cs when I setup KeyVault. When I add the values in appsettings.json all works fine, but if I remove it and manage user secrets it's always say null when my program.cs is running.
And I have the correct values in the created secret.json and the attribute with a guid to it is also in my project file
I have also tried to add a key and value to the secret.json and tried to get it from a controller and it's also null.
So it seems like WebHost.CreateDefaultBuilder in my program.se does not load my secret.json file.
And if I add AssUserSecrets to my WebHost.CreateDefaultBuilder(args) in progam.cs there is no difference same problem.
I'm using WebHost.CreateDefaultBuilder so it shall be used by default in asp .net core 2.2
dontnet user-secret list
Will also shows the values for me from my secret.json file so the value is there, the user-secret has been initialized.
dontnet user-secret init
Also, say it's already setup.
But still just null when calling my secret.json attributes
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services => services.AddAutofac())
.ConfigureAppConfiguration((context, builder) =>
{
var config = builder.Build();
var vault = config["KeyVault:Vault"];
builder.AddAzureKeyVault($"https://{config["KeyVault:Vault"]}.vault.azure.net/", config["KeyVault:ClientId"], config["KeyVault:ClientSecret"]);
});
I test in my site and it works fine, here is the steps you could refer to.
1.Right click on the project and select Manage User Secrets. It will open the secrets.json file in Visual Studio where you can add your secrets and it will add the to the .csproj file.
2.Add what you may wish to add to your User Secrets. It includes two ways of writing a json object and a simple key/value pair.
3.Mapping User Secrets to a model.
public class KeyVault
{
public string Vault { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
4.Adding the Configuration.
Install package Microsoft.VisualStudio.Web.CodeGeneration.Design and Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.UserSecrets
5.Bind the values. This is done in the Startup.cs file.
6.Using your mapped secrets
public class HomeController : Controller
{
private readonly KeyVault _keyvault;
// I’ve injected twilioAccountDetails into the constructor
public HomeController(IOptions<KeyVault> keyvault)
{
// We want to know if twilioAccountDetails is null so we throw an exception if it is
_keyvault = keyvault.Value ?? throw new ArgumentException(nameof(keyvault));
}
........
}
7.Call it in Program.cs.
For more details about how to use User Secrets in a .NET Core Web App, you could refer to this article.
It seems to be related to: Microsoft.Extensions.Configuration.AzureKeyVault
because as soon I add that nuget it stops working.
UPDATE: More info. it seems like the latest Microsoft.Extensions.Configuration.AzureKeyVault downgrade some of the configuration libs for me. And then it stops working.
I was having this same issue when using Host.CreateDefaultBuilder() and discovered that it was because my host environment was not Development.
To resolve this I added the following section to my launchSettings.json:
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
See related documentation:
The following defaults are applied to the returned HostBuilder:
load app IConfiguration from User Secrets when EnvironmentName is 'Development' using the entry assembly
In my case, I was missing the following NuGet package:
Microsoft.Extensions.Configuration.UserSecrets
Once I installed this, it worked perfectly.
I'm running a Nancy application in a Virtual Directory on my development machine and I've got static content working but if the module redirects the browser then the URL being sent back is incorrect.
If the result is:
return new RedirectResponse("/");
Then the browser redirects to http://localhost/ rather than the root of the virtual directory.
If I try
return new RedirectResponse("~/");
I get taken to http://localhost/MyVirtualDirectory/action/~/ which at least includes the virtual directory, but the rest is screwed up.
I should point out that the module is created like this...
public abstract class ActionRootModule : NancyModule
{
protected ActionRootModule() : base("/action/") { }
}
public class SendEmailModule : ActionRootModule
{
public SendEmailModule()
{
// Parts missing for brevity....
Post["/send-email/"] = o => PostSendEmail(o);
}
private dynamic PostSendEmail(dynamic o)
{
// Do stuff...
return new RedirectResponse("~/");
}
}
What is the correct way of telling Nancy to redirect to a specific URL inside a virtual directory?
I'm running Visual Studio on Windows 7 and IIS 7.5 (not IIS Express - as I have incoming traffic from third parties making callbacks)
This won't be a issue on production as the production deployment won't be in a virtual directory.
There are two ways to solve this.
1) Use return Response.AsRedirect("~/");
2) Use return new RedirectResponse(Context.ToFullPath("~/"));
The first option is just a convenient wrapper around the second so either way yields the same result (https://github.com/NancyFx/Nancy/blob/85dfe8567d794ff3e766521a9fa0891832d4fc8a/src/Nancy/FormatterExtensions.cs#L51). The call to ToFullpath() is what corrects the /~/ you saw in your redirected URL.
Hello ServiceStack aficionados!
I would like to host static XML files through the ServiceStack service; however, I can't seem to get the configuration right and only receive 404 errors. Feels like I tried all sorts of path/url combinations.
Can the WebHostPhysicalPath be defined as a relative path? Is there another setting that must be enabled? I was concerned that maybe the XML extension is conflicting with the format conversion stuff.
Also, can I host Razor cshtml files this way too?
Any comments on this approach?
thanks!
You can return a static file from a service like so:
[Route("/myFile/")]
public class GetMyFile
{
}
public class HelloService : Service
{
public HttpResult Any(GetMyFile request)
{
return new HttpResult(new FileInfo("~/myfile.xml"), asAttachment:true) { ContentType = "text/xml" };
}
}
As for razor: http://razor.servicestack.net/
My public web app has a special servlet to generate a digest of published documents and saves them to a configured file path on server. This servlet must only be available by ip's specified by administrator of the app.
My hope is/was that this kind of stuff could be configured via tomcats security manager (a special servlet/ url should only be "listen" to a specific ip-(range)). Is this possible?
Or in general: i don't want to implement "security" in my code (the servlet it self could filter the ip). it should be a matter of container configuration or system configuration.
so how to achieve that
Tomcat already comes with Remote Address Filter valve that filters all requests to match a pattern. If you only need to provide filtering for a single URI, it is probably best to extend RequestFilterValve class and embed the logic in the extension. Something like this should work (haven't tested locally but you should be able to get the idea):
public class YourValve extends org.apache.catalina.valves.RequestFilterValve {
public void invoke(Request request, Response response) throws IOException, ServletException {
if (request.getRequestURI().startsWith("/path/to/your/secure/servlet") {
process(request.getRequest().getRemoteAddr(), request, response);
} else {
// no need to filter anything
}
}
}
You would have to configure this valve to provide allow regex, as explained in Remote Address Filter documentation. It could be something like
<Valve className="YourValve" allow="127\.\d+\.\d+\.\d+"/>
(above only allows localhost)
This article, chapter 4.1 explains how to install valves.