Clear ehcache of remote server - java

How can we clear ehcache on a remote server?
My application is running in staging environment (host 111.22.3.44 and port 17000) and I want to write an utility method that can connect to a given host:port and clear the ehcache of my App. This utility should to work in Windows as well as Linux.
I use JConsole.exe utility to flush the cache of ehcache created in stage-server, but there is a situation where I need to do it programatically.

Hurrey...:) I got the solution for clearing ehcache on a remote environment. Here, I have written a Java utility method that will flush out ehcache of a given remote machine that is specified by host name and port.
public void flushEhcache() throws IOException, NamingException, MalformedObjectNameException, NullPointerException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
String host = "111.22.3.44";
String port = "16000";
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"
+ host + ":" + port + "/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
ObjectName beanName = new ObjectName("net.sf.ehcache:type=CacheManager,name=Your Application Name Here");
mbsc.invoke(beanName, "clearAll", new Object[0], new String[0]);
System.out.println("Flushed out ehcache succesfully");
}

Related

How to configure the netty-SocketIO server so that it is accessible from all remote java clients in jelastic

I am developing a Spring-Boot project which also includes a socketIO server based on netty-socket Io. And therefore two clients: a web client and an android client!
all of them work wonderfully locally! But when I deploy online server in Jelastic only the web client which accesses netty-SocketIO server, but android client fails to connect to netty-SocketIO server. someone could help me configure the netty-socketIO server to accept all requests from any address on port 8888
Server configuration
Configuration config = new Configuration();
//config.setHostname("sec.j.layershift.co.uk");
config.setHostname("0.0.0.0");
config.setPort(8888);
final SocketIOServer server = new SocketIOServer(config);
// Listen for client connections
server.addConnectListener(client -> {
System.out.println("************ Client: " + getIpByClient(client) + " Connected ************");
});
Web client configuration
#CrossOrigin("*")
#RestController
public class ClientLocation {
Socket socket =null;
EventBuilder eventBuilder =null;
Gson gs = new Gson();
//................................
socket = IO.socket("http://sec.j.layershift.co.uk:8888");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
ChatObject co = new ChatObject("ADMIN", "");
String infUser = gs.toJson(co);
System.out.println("\n"+infUser);
JSONObject jb = new JSONObject();
try {
// jb.put("userName", co.getUserName());
// jb.put("message", co.getMessage());
jb = new JSONObject(infUser);
socket.emit("username", jb);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Configuration of the java or android client
private void clientIO(){
try {
socket = IO.socket("http://aug-sec.j.layershift.co.uk:8888");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
Nb. the configuration of the java or android client is identical to that of the web because all use the Socket.IO v1.0.0. But only the web client works from the Jelastic host because it is in the same folder as the server and the java clients do not succeed, so everything works in localhost or in LAN
There are 2 possible solutions
You can use the public IP (the way suggested by #Ruslan)
Also, the Jelastic platform resolver supports the WebSocket proxying (if the "Upgrade: websocket" header is present). You can use the JELASTIC_EXPOSE variable to forward the requests from port 80 to 8888 (more info here https://docs.jelastic.com/container-ports/#ports-auto-redirect) inside your container and then just access the app by your environment domain and port 80

Akka HTTP server with SSL support in Java - How to create configuration?

I am trying to create an Akka HTTP server, which will support SSL.
I am aware of this question for scala Akka HTTP 2.0 to use SSL (HTTPS) and I am trying to work it into Java code but I am getting lost.
The DSL akka.http.javadsl.Http class is different for Java and requires akka.actor.ExtendedActorSystem, when I try to create an instance for it I am required to create an application configuration with the com.typesafe.config.Config class, which I can't figure out how to instantiate and what to put in it.
Is there any simpler way? Or any classes I can use to create all the required configurations?
This is a snippet of the code:
// boot up server using the route as defined below
final ActorSystem system = ActorSystem.create();
final ActorMaterializer materializer = ActorMaterializer.create(system);
// Run the server bound to the local machine IP
String hostAddress = InetAddress.getLocalHost().getHostAddress();
// No implementation here?????
Config applicationConfig = new Config() {
}
ExtendedActorSystem extendedActorSystem = new ActorSystemImpl("HttpProxy", applicationConfig, ClassLoader.getSystemClassLoader(), Option.empty());
// todo: missing handler, settings, httpsContext and log
Flow<HttpRequest, HttpResponse, ?> handler;
ServerSettings settings;
akka.japi.Option<HttpsContext> httpsContext;
LoggingAdapter log;
new Http(extendedActorSystem).bindAndHandle(handler, hostAddress, PORT, settings, httpsContext, log, materializer);
System.out.println("Starting server on " + hostAddress + ":" + PORT);
// The server would stop if carriage return is entered in the system cosole
System.out.println("Type RETURN to exit");
System.in.read();
system.shutdown();
It supposed to be something like this:
// boot up server using the route as defined below
// Run the server bound to the local machine IP
String hostAddress = InetAddress.getLocalHost().getHostAddress();
// No implementation here?????
Config applicationConfig = ConfigFactory.load();
ActorSystem system = ActorSystem.create("HttpProxy", applicationConfig);
final ActorMaterializer materializer = ActorMaterializer.create(system);
// todo: missing handler, settings, httpsContext and log
Flow<HttpRequest, HttpResponse, ?> handler;
ServerSettings settings;
akka.japi.Option<HttpsContext> httpsContext;
LoggingAdapter log;
Http.get(system).bindAndHandle(handler, hostAddress, 9000, settings, httpsContext, log, materializer);
System.out.println("Starting server on " + hostAddress + ":" + 9000);

How to get the name or ip of a proxy server in a managed network?

i need to be able to access certain urls programmatically . I am using URLConnection as follows
URL url = new URL(http,
myProxy.com, // I need to know this parameter
-1,
http://www.example.com/);
How do I get the name of the proxy server used in a managed network.
when i use a browser like chrome it connects me with the proxy server that makes requests to the internet . How do i get the name of the proxy server ?
You can try to use a java ProxySelector class to do it, her is short example of it'usage from java proxy configuration guide:
private Proxy findProxy(URI uri)
{
try
{
ProxySelector selector = ProxySelector.getDefault();
List<Proxy> proxyList = selector.select(uri);
if (proxyList.size() > 1)
return proxyList.get(0);
}
catch (IllegalArgumentException e)
{
}
return Proxy.NO_PROXY;
}
To get a host name and IP address, you can use an InetSocketAddress, which you can get from Proxy instance:
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if(addr != null) {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
But as I know, it's needed to set a system property to do it:
System.setProperty("java.net.useSystemProxies","true");
One more solution is to use a proxy-vole library to do it. Here is some usage examples.

Getting Connection reset Exception when storing/retrieving InitialLdapContext in session

i have a webpage page to manage active directory groups, and in the initialization of this page i connect to ldap with jndi and save the ldap context in http session.
here's how i connect to ldap:
public static LdapContext connectToLdap(String host,
String userDN, String userPassword,
boolean ssl) throws Exception {
System.out.println("connectToLdap");
String hostPrefix = "ldap";
String ldapPort = "389";
if (ssl) {
hostPrefix = "ldaps";
ldapPort = "636";
}
String providerUrl = hostPrefix + "://" + host + ":" + ldapPort;
//System.out.println("####### LDAP URL: " + providerUrl);
LdapContext ldapContext;
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, providerUrl);
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, userDN);
ldapEnv.put(Context.SECURITY_CREDENTIALS, userPassword);
ldapEnv.put("com.sun.jndi.ldap.read.timeout", 1000 * 10 + "");
if (ssl) {
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
}
ldapEnv.put(Context.REFERRAL, "ignore");
try {
ldapContext = new InitialLdapContext(ldapEnv, null);
System.out.println("success connection to ldap");
return ldapContext;
} catch (Exception e) {
System.out.println("failure connection to ldap");
e.printStackTrace();
return null;
}
}
i don't close the context because it will be reused during user session.
i put the ldapcontext in session so that i don't have to make frequent conenctions to ldap per user, only one connection per session per user.
ISSUE: i noticed that sometimes after 10-15 minutes the retrieval of active directory groups fails and i get exception:
javax.naming.CommunicationException: Connection reset [Root exception is java.net.SocketException: Connection reset]
any ideas why ? please advise why i am getting this issue and how to resolve it.
Don't place LdapContext in HTTP session it does not implement Serializable interface so there is no guarantee that it can be stored/restored to/from session.
Think about it, if session was to be stored in database or replicated to another server LdapContext would be converted to bytes, along with any socket descriptors it references, how would that work when you restore them from bytes?
Have it in a singleton if you need long term connections.
Other than that it is common for servers and networking equipment to close [what they think are] inactive network connections, so any long term connections need to be tested or keep-alive'd.
If it's still relevant I would suggest that you use the (GPLv2, LGPLv2.1 licensed) UnboundID LDAP SDK for Java (no affiliation), that handles connection pooling and connection testing a bit better than the shipped JNDI implementation.

Connection to Tomcat JMX server failing

Failing to connect to Tomcat JMX instance
Ok i am stuck now - Im trying to configure JMX with Tomcat as follows
$CATALINA_BASE/setenv.sh:
CATALINA_OPTS="-Dcom.sun.management.jmxremote.port=18070 -Dcom.sun.management.jmxremote.password.file=$CATALINA_BASE/conf/jmxremote.password -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.access.file=$CATALINA_BASE/conf/jmxremote.access"
export CATALINA_OPTS
$CATALINA_BASE/conf/jmxremote.password
monitorRole monitorpass
controlRole controlpass
$CATALINA_BASE/conf/jmxremote.access
monitorRole readonly
controlRole readwrite
The client tool i am using to access the Tomcat JMX server is running on the same machine as the Tomcat instance. when i start tomcat i can see that there is something listening at port 18070 but when i try to connect i get the following error
Exception in thread "main" java.lang.SecurityException: Authentication failed! Credentials required
at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticationFailure(JMXPluggableAuthenticator.java:193)
at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticate(JMXPluggableAuthenticator.java:145)
at sun.management.jmxremote.ConnectorBootstrap$AccessFileCheckerAuthenticator.authenticate(ConnectorBootstrap.java:185)
at javax.management.remote.rmi.RMIServerImpl.doNewClient(RMIServerImpl.java:213)
I connect using the following bit of code
try {
url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:18070/jmxrmi");
jmxc = JMXConnectorFactory.connect(url,null);
mbsc = jmxc.getMBeanServerConnection();
} catch (MalformedURLException e) {
throw new Exception(methodName + ":" + e);
} catch (IOException e) {
throw new Exception(methodName + ":" + "Failed to connect to the Tomcat Server " + e);
}
It works fine if i set com.sun.management.jmxremote.authenticate=true to false. Other than that it just fails. The client tool is running on the same machine as the tomcat instance so there should not be any issues with the firewall. Any clues
This
JMXServiceURL url = ...;
Map env = ...;
String[] creds = {"monitorRole", "mrpasswd"};
env.put(JMXConnector.CREDENTIALS, creds);
JMXConnector cc = JMXConnectorFactory.connect(url, env);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
from http://blogs.oracle.com/lmalventosa/entry/jmx_authentication_authorization
should help

Categories