Howto use custom JMXAuthenticator - jmx

I have to authenticate JMX clients against entries in a database. Therefore I have written a custom JMXAuthenticator implementation.
When starting up my application I can access the MBeans using JConsole via the 'Local Process'. But when I try to access it as a remote process using the url 'service:jmx:rmi:///jndi/rmi://localhost:10999/jmxrmi' JConsole shows a message complaining that 'The connection to service:jmx:rmi:///jndi/rmi://localhost:10999/jmxrmi did not succeed.'
Below is the server side code to start up the MBeanServer and the JMXConnectorServer. Has anybody an idea what I am doing wrong?
Thanks in advance,
Thomas
final MBeanServer mbs = MBeanServerFactory.createMBeanServer("MyDomain");
final HashMap<String, Object> environment = new HashMap<String, Object>();
final JMXAuthenticator authenticator = new JMXAuthenticatorImpl();
environment.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
final JMXServiceURL serviceURL = new JMXServiceURL("rmi", "localhost", 10999);
final JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serviceURL, environment, mbs);
connectorServer.start();

It seems the problem was that I have not created the RMI Registry before creating the new JMXConnectorServer.
Inserting
LocateRegistry.createRegistry(port);
before creating the JMXConnectorServer solved the problem.

Related

Orleans direct client in ASP.NET Core project

I am currently looking into Orleans as a backend for Asp.net core web api project, and was wondering if anyone has any experience with its new feature - "direct client". The orleans docs say "it allows co-hosting a client and silo in a way that let the client communicate more efficiently with not just the silo it's attached to, but the entire cluster", and I am aware that you can code something like this (and it works just fine in a console app):
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
I am struggling trying to figure out where to put this type of code in an asp.net project that has its own webhost builder in "Main" (should it go to Startup class in "ConfigureServices"?). In the end, we are aiming for a separate client/server setup, but for faster development it would be useful to play with a simple setup, which direct client appears to allow for. Any pointers to resources and/or sample solutions containing direct client with asp.net core would be appreciated. Thanks.
EDIT: Here's the code that kinda works for me now, but I am not happy with he way the DI is set up
public static async Task Main(string[] args)
{
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.ConfigureServices(services =>
{
services.AddDbContext<UserDbSet>(o => o.UseSqlite("Data Source=UserTest.db"));
services.AddMediatR(typeof(Startup).Assembly);
})
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
await WebHost.CreateDefaultBuilder(args)
.UseConfiguration(new ConfigurationBuilder()
.AddCommandLine(args)
.Build())
.ConfigureServices(services =>
services
.AddSingleton<IGrainFactory>(client)
.AddSingleton<IClusterClient>(client))
.UseStartup<Startup>()
.Build()
.RunAsync();
}
If I put registration of the DbContext and Mediatr in the StartUp class, grain code fails with an exception indicating failure to instantiate the required dependencies. Maybe I am doing something wrong when setting up the Webhost?
For ASP.NET 2.x & Orleans below 2.3, I recommend creating & starting the silo before the Web host. When configuring the Web host, inject the IGrainFactory & IClusterClient instances from the silo (obtained via silo.Services):
var silo = new SiloHostBuilder()
.UseLocalhostClustering()
.EnableDirectClient()
.Build();
await silo.StartAsync();
var client = silo.Services.GetRequiredService<IClusterClient>();
var webHost = new WebHostBuilder()
.ConfigureServices(services =>
services
.AddSingleton<IGrainFactory>(client)
.AddSingleton<IClusterClient>(client))
.UseStartup<Startup>()
// Other ASP.NET configuration...
.Build();
For ASP.NET 3.0 & Orleans 2.3 or greater, the integration code becomes simpler due to the addition of Microsoft.Extensions.Hosting support in both frameworks:
var host = new HostBuilder()
.ConfigureWebHost(builder =>
{
// Adding IGrainFactory, etc, is not necessary, since Orleans
// and ASP.NET share the same dependency injection container.
builder.UseStartup<Startup>();
})
.UseOrleans(builder =>
{
// EnableDirectClient is no longer needed as it is enabled by default
builder.UseLocalhostClustering();
})
.Build();
await host.StartAsync();

How to integrate waffle NegotiateSecurityFilter spring-security with sparkjava embedded jetty?

Our application is using sparkjava http://sparkjava.com/ as the REST framework. The jetty server is embedded in the application (sparkjava default). We are also using spring for dependency injection.
For providing AD authentication, we need to integrate the waffle's NegotiateSecurityFilter.
As per waffle documentation and several online resources including stackoverflow, a DelegatingFilterProxy is required with the name springSecurityFilterChain.
But since we are not using spring MVC, I have to add it as follows:
ServletContextHandler sparkContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
sparkContext.addFilter(new FilterHolder( new DelegatingFilterProxy( "springSecurityFilterChain" ) ),"/*", EnumSet.allOf( DispatcherType.class ));
And since a ContextLoaderListener does not already exist, need to add in the following manner:
sparkContext.addEventListener( new ContextLoaderListener() );
But it gives the error "Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader" at time of server startup.
Please let me know a solution in this scenario if you have successfully integrated spring-security DelegatingFilterProxy with embedded jetty and sparkjava (without using spring MVC).
This is how I achieved it finally:
In the main method where I have access to the sparkContext:
ServletContextHandler sparkContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
sparkContext.setContextPath("/");
sparkContext.addServlet(DefaultServlet.class, "/*");
addSPNEGOFilter(sparkContext);
And the implementing methods are as:
private void addSPNEGOFilter(ServletContextHandler sparkContext) {
final ServletHandler handler = new ServletHandler();
final FilterHolder fh = handler.addFilterWithMapping(NegotiateSecurityFilter.class, <SPNEGO_FILTER_PATH>,
EnumSet.allOf(DispatcherType.class));
setNegotiateFilterParams(fh);
sparkContext.addFilter(fh, <SPNEGO_FILTER_PATH>, EnumSet.allOf(DispatcherType.class));
}
Add the following properties to the holder:
private static void setNegotiateFilterParams(final FilterHolder fh) {
fh.setInitParameter("principalFormat", "fqn");
fh.setInitParameter("roleFormat", "both");
fh.setInitParameter("allowGuestLogin", "false");
fh.setInitParameter("impersonate", "false");
fh.setInitParameter("securityFilterProviders",
"waffle.servlet.spi.NegotiateSecurityFilterProvider");
fh.setInitParameter("waffle.servlet.spi.NegotiateSecurityFilterProvider/protocols", "Negotiate");
}

Why following HA Neo4j graph database creation takes long time?

I am creating neo4j graph database enterprise edition by the following method. It doesn't return any exception etc. and shows that program is running(forever).
HashMap<String, String> settings = new HashMap<String, String>();
settings.put("org.neo4j.server.database.mode", "HA");
settings.put("ha.server_id", "1");
settings.put("ha.initial_hosts",
"neo4j-01.local:5001,neo4j-02.local:5001,neo4j-03.local:5001");
GraphDatabaseService db = new HighlyAvailableGraphDatabaseFactory()
.newHighlyAvailableDatabaseBuilder("db.local")
.setConfig(settings).newGraphDatabase();
What would be the reason here?
P.S I got the configurations from official web-site of Neo4j.
It waits for the other instances to join the cluster. Be sure to run the same code with appropriate ha.server_id on the other hosts mentioned in ha.initial_hosts.

How to make HttpClient relay traffic show up in Fidder or Charles?

I have a simple web api project based on this example:
http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/RelaySample/Program.cs
However, in the above sample the relay is working with a local server, in my project the relay is working with an external web server with a real address; companyX.com
I am using the relay service (or, web proxy service) through a browser, for example, in the browser request relayService.com/companyX. The relay service responds with data from the external companyX.com site.
The relay works great, however some headers are not correct and I need to see what the HttpClient is sending to the remote companyX.com server.
In fiddler or Charles, only the request/response from my browser to relayService.com is listed, the request/response from the HttpClient to relayService.com never shows up.
The relayService.com is running locally on my machine, in IIS7, I'm using the hosts file to direct traffic to relayService.com.
I have tried several variation of the following when creating the HttpClient:
var clientHandler = new HttpClientHandler
{
CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
UPDATE
If I change UseProxy = false The service continues to work, when Fiddler is open or closed.
With UseProxy = true then the service will fail, if fiddler is open, I get the following error:
Object reference not set to an instance of an object.
at System.DomainNameHelper.IdnEquivalent(String hostname) at System.Net.HttpWebRequest.GetSafeHostAndPort(Uri sourceUri, Boolean addDefaultPort, Boolean forcePunycode) at System.Net.HttpWebRequest.GenerateProxyRequestLine(Int32 headersSize) at System.Net.HttpWebRequest.SerializeHeaders() at System.Net.HttpWebRequest.EndSubmitRequest() at System.Net.Connection.CompleteConnection(Boolean async, HttpWebRequest request)
With UseProxy = true and fiddler is CLOSED, I get the following (obvious) error:
No connection could be made because the target machine actively refused it 127.0.0.1:8888
In the same solution I am using HttpWebRequest to download data from the web and that does show up in Fiddler, so it seems to be an issue with the HttpClient.GetAsync()
I have tried this on two machines with identical results.
I have been struggling with this all day, any help would be much appreciated.
Just to recap:
* relayService.com is running locally on my machine, in IIS7
hosts file has "127.0.0.1 relayService.com"
relayService.com is an MVC Web API site that uses HttpClient.GetAsync() to download content from the live web
Fiddler/Charles is running locally on same machine
browser traffic to the local relayService.com appears in Fiddler/Charles
HttpClient.GetAsync() to live web traffic does not appear in Fiddler/Charles
Fiddler/Charles are both up to date versions.
Thanks again
You don't need anything in your HOSTS file if you're using Fiddler; you can use Fiddler's Tools > HOSTS to redirect traffic anywhere you'd like.
When trying to capture traffic from a service account (e.g. the ASP.NET acccount) you typically want to configure that account to use the proxy; see http://fiddler2.com/blog/blog/2013/01/08/capturing-traffic-from-.net-services-with-fiddler for details on that. If you do that, you shouldn't need to configure the proxy object directly in code.
The exception you've shown suggests that here's a bug in the GenerateProxyRequestLine function. Is there any change if you update this: new WebProxy("http://localhost:8888"); to new WebProxy("127.0.0.1", 8888); ?
Generally speaking, .NET applications will bypass the proxy for URLs pointed at //localhost or //127.0.0.1, so when debugging with Fiddler it's common to use a service URL of //localhost.fiddler so that the traffic is always sent to the proxy.
I fixed the problem by making the HttpClient static.
This works fine (for the program functionality) but has the problem with fiddler described above, where trying to use the proxy throws an error:
private HttpClient _client()
{
var clientHandler = new HttpClientHandler
{
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = true,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
client.Timeout = TimeSpan.FromMinutes(20);
return client;
}
The client was created with:
using (HttpResponseMessage serviceResponse = await _client().GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
However, the below also works and all traffic shows up in Fiddler!
private static readonly HttpClientHandler _clientHandler = new HttpClientHandler()
{
//CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = false,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic,
};
//Create a shared instance of HttpClient and set the request timeout
private static readonly HttpClient _client = new HttpClient(_clientHandler)
{
Timeout = TimeSpan.FromMinutes(20)
};
The client was created with (only difference is removing the '()' after _client above):
using (HttpResponseMessage serviceResponse = await _client.GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
I have no clue why this works. Any insight would be appreciated.
Thanks,

How can i store database information in JSF2

In my managed bean i need to access a mySql database.
So far i used code like this:
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test";
String username = "user";
String password = "1234";
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
Now i have to do this in more than one bean, so if i need to change the database credentials, i have to fiddle around in like 10 files.
Is there
a way to store the databaseconnection
a way to define some variables for the whole web project
Thanks in advance
First of all you should understand basic architecture of a Java EE project. It is not a good idea connecting databases in managed beans. It is really bad practice. Please have look my previous answer to understand basic architecture.
Database connections is done in Integration Tier and these classes are called Data Access Objects (DAO).
Create a BaseDao class for static connection properties.
class BaseDao
{
private String url = "jdbc:mysql://localhost:3306/test";
private String username = "user";
private String password = "1234";
private Connection connection;
protected Connection getConnection()
{
connection = DriverManager.getConnection(url, username, password);
return connection;
}
}
and extend base class to its derived classes where database connection is needed and access connection by using BaseDao#getConnection().
Furthermore, it is better to keep database connections in a properties file and inject them into proper classes.
Related Tutorial
Read BalusC tutorial for better understanding DAO tutorial - the data layer
It is generally a good idea to store these kind of values in a .properties file. They can then be accessed via java.util.Properties (http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html)
Here is a good tutorial describing how access these files and their values, I suggest you start with this: http://www.mkyong.com/java/java-properties-file-examples/
(More information: http://en.wikipedia.org/wiki/.properties)
In my IDE, I usually create a new source package /src/main/config and put all my configuration-concerning .properties and .xml files in there. If you do it this way, you need to access it like this from within your jsf application:
String configFilePath = "configuration.properties";
props = new Properties();
InputStream propInStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFilePath);
props.load(propInStream);
Or you can simply do this:
How to get properties file from /WEB-INF folder in JSF?

Resources