Update ReplicaSet using Java Kubernetes Client - java

I am writing a client that manages Kubernetes objects. Is it possible to update ReplicaSets using a Java client?

Yes, you can update ReplicaSet using Java Kubernetes Client. Depending on which Kubernetes client you use here are the code snippets.
Kubernetes Java Client
AppsV1Api api = new AppsV1Api();
api.patchNamespacedReplicaSet(...);
Fabric8 Kubernetes & OpenShift Java Client
KubernetesClient client = new DefaultKubernetesClient();
client.apps().replicaSets().createOrReplace(...);

I was just doing this this morning!
Yes you can do that. Checkout Fabric8 Kubernetes client for Java (https://github.com/fabric8io/kubernetes-client/blob/master/kubernetes-tests/src/test/java/io/fabric8/kubernetes/client/mock/ReplicaSetTest.java)
An example of the change would be:
try (KubernetesClient k8sClient = new DefaultKubernetesClient()) {
ReplicaSetList list = k8sClient.apps().replicaSets().inNamespace("default").list();
for (ReplicaSet next : list.getItems()) {
next.getSpec().setReplicas(10);
k8sClient.apps().replicaSets().create(next);
}
} catch (Exception e) {
//TODO: logging
}
Just be sure to use the correct one. In this example I am changing all of them in the default namespace.

Related

Android MQTT - Paho Doesn't support wss://

I'm using the Paho Android Client.
https://eclipse.org/paho/clients/java/
This is probably THE go to library for MQTT on Android, yet it doesn't support secure MQTT websockets (wss://), giving me IllegalArgument exceptions for the server uri.
I have been looking for a solution to connect to my MQTT websocket which has a wss:// path scheme, and so far there's only one library:
https://github.com/inventit/mqtt-websocket-java
Which also doesn't work! I'm getting Jetty SSL exceptions.
If you have an implementation you've used before, please share them with me, this has taken a lot of my time, and I'm still clueless, thanks!
For both libraries, I've tried using the sample code they offer in their documentations.
I think Paho Android Client doesn't support websocket ssl but you can use MqttAsyncClient instead MqttAndroidClient like this :
The libraries are the same :
dependencies {
...
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.0'
...
}
Use MqttAsyncClient instead MqttAndroidClient like this :
private MqttAsyncClient mMqttAndroidClient;
try {
mMqttAndroidClient = new MqttAsyncClient("wss://...", MqttClient.generateClientId(), new MemoryPersistence());
} catch (MqttException e) {
e.printStackTrace();
}
I used "WSS://" without any problem. Make a MqttAndroidClient object with "WSS" schema and port 443.
mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setKeepAliveInterval(MqttConfig.KEEPALIVE);
mqttConnectOptions.setUserName("username");
mqttConnectOptions.setPassword("pass");
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setMaxInflight(1024);
..
uri="wss://broker.hivemq.com:443"
MqttAndroidClient client = new MqttAndroidClient(context, uri, clientId,persistence);
..
getClient().connect(mqttConnectOptions,applicationContext,mqttActionListener;

How to bind variables into websocket route paths using Spark Web Framework?

I'm, trying to implement a websocket server using Spark (a java web framework). I'm using the version 2.3 that has added support for it.
There's some way to bind variables into route paths just like http routes?
e.g. /chat/:city
I want to create conversation channels among users. If it's possible, how can I make it work and how can I retrieve the variable?
Simply add ?userId=somekey to the end of path on your client side. Example would be to initialize your websocket path to Spark.websocket("/chat") (server-side obvi.) . Then have your client hit the URL with /chat?userId=blah. From the server side you'll receive a connection for the socket. From there simply grab the incoming URI from the socket connection and use the String userKey = session.getRemote().getQuery() method to pull of the field. May have to do a user.split("=")[1] to get the value
(stackoverflow's answer didn't worked for me, but pointed me in the right direction):
I managed to get the parameters this way:
#OnWebSocketConnect
void onConnect(Session sockSession) throws Exception {
Map<String, List<String>> params = sockSession.upgradeRequest.parameterMap;
if(params != null && params.containsKey("city")) {
// As the parameter's value is a List, we use 'get(0)'
String city = params.get("city").get(0);
...
}
...
}

What is execProt("P") in Apache Commons net?

I have setup an FTPS server on my aws ec2 instance. I am using Apache Commons net to connect programmatically to my server.
try
{
ftps.enterLocalPassiveMode();
ftps.setBufferSize(1000);
ftps.execPROT("P");
if (!ftps.login(username, password))
{
ftps.logout();
error = true;
break __main;
}
}
I cannot retrieve files if I don't set execProt("P"). From their documentation, I see that "P" stands for Private Data Channel Protection Level. What does this mean? Why am I using P instead of "S" or "E"?
The PROT command in ftps can have the values P and C. P stands for private and means that the data connection is encrypted with TLS. C stands for clear and means that the data connection is not encrypted. The values of E (confidential) and S (safe) are defined too but in practice not implemented in FTP servers. For more details see the specification, i.e. RFC 4217.

Restlet framework: how to bind to localhost only?

I need to build a (standalone Java) restlet-based service that only listens on localhost, i.e. no requests from network are allowed.
I was trying to do the obvious:
Server srv = new Server(Protocol.HTTPS, "localhost", httpsPort);
component.getServers().add(srv);
But the service still listens on 0.0.0.0. :-(
I went into the code and found that HttpsServerHelper ignores the hostname when creating the service:
this.server = HttpsServer.create(new InetSocketAddress(getHelped().getPort()), 0);
Similar code exists in plain HTTP's HttpServerHelper, where it is even more clear.
My question then is this:
How can I configure Restlet component/service to only listen on localhost?
I don't know which server you use under the hood within your standalone Restlet application. You should use a server connector other than the default one and I recommend you to use the Jetty one.
To do that, simply put the jar of the extension org.restlet.ext.jetty in your classpath.
In this case, using the following code should correspond to your needs:
component.getServers().add(Protocol.HTTP, "localhost", 8182);
Here is the corresponding trace at application startup:
2015-09-03 09:47:22.180:INFO::jetty-7.1.6.v20100715
2015-09-03 09:47:22.211:INFO::Started SelectChannelConnector#localhost:8182
In addition, here is the link in the Restlet documentation regarding Restlet connectors: http://restlet.com/technical-resources/restlet-framework/guide/2.3/core/base/connectors.
Hope it helps you,
Thierry
The easier way to achieve that is to use virtual hosts.
Virtual hosts are the first routing barrier when handling a request, especially it helps routing on a domain.
Here is a sample code that illustrates this:
Component c = new Component();
c.getServers().add(Protocol.HTTP, 8182);
VirtualHost host = new VirtualHost();
host.setHostDomain("localhost");
c.getHosts().add(host);
host.attach(new Restlet() {
#Override
public void handle(Request request, Response response) {
response.setEntity("hello, world", MediaType.TEXT_PLAIN);
}
});
c.start();
Usually, applications are attached on the default host of a component. This default host does nothing, except routing requests based on the context path of the attached application:
c.getDefaultHost().attach("/contextPath1", new Test1Application());
c.getDefaultHost().attach("/contextPath2", new Test2Application());
When you would like to filter calls based on other data than the request's path, virtual host may be the solution.
Here is a diagram that may help you:
http://restlet.com/technical-resources/restlet-framework/tutorials/2.3#part05

How to manage Tomcat via Java

i'm looking for a way to manage tomcat (on localhost) programmatically via java.
I want to start/stop tomcat and deploy WARs.
Any help is appreciated.
You can run Tomcat embedded in your app.
The way to start/stop tomcat through java is to call execute on the bootstrap.jar (Use the class Runtime) with the sample parameters: -Dcatalina.home=c:/tomcat/
Sample code to see how ant executes tomcat start stop:
http://ptrthomas.wordpress.com/2006/03/25/how-to-start-and-stop-tomcat-from-ant
Sample code to see how external programs are executed from java:
http://www.linglom.com/2007/06/06/how-to-run-command-line-or-execute-external-application-from-java/
You can use java Runtime class to call a bat file. make sure User running java process has rights to start and stop tomcat.
try{
Runtime.getRuntime().exec("c:/program files/tomcat/bin/startup.bat");
} catch(IOException e) {System.out.println("exception");}
To manage tomcat programmatically, you may want to take a look at JMX and the bulit-in MBeans' capabilities of Tomcat.
In essence, you can write your own java based JMX client to talk to the MBeans via RMI or you can take advantage of the JMX Http Proxy in the Manager App and use plain old http requests to script and manage the tomcat instance.
For a good reference of JMX and Tomcat 6:
http://www.datadisk.co.uk/html_docs/java_app/tomcat6/tomcat6_jmx.htm
A good reference of Manager App and JMX Http Proxy:
http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#JMX_Set_command
You should be able to deploy and undeploy WARs fairly easily.
I don't think there is an existing MBean that allow you to shutdown tomcat, but it's fairly easy to implement one yourself and call System.exit();
You can use tomcat manager, or see its sources to learn how manager process the deploy operations.
You can restart individual Tomcat connector i.e. port restart like 8843 where your application is running. One scenario when this is required is when you are getting signed certificate through API or you are modifying your truststore.
Here is the complete code/method that I am using to restart tomcat connectors after I add/delete certificates.
public void refreshTrustStore() throws Exception
{
try
{
//following line need to be replaced based on where you get your port. It may be passed in as argument
String httpsPort = configurationManager.getHttpsPort();
String objectString = "*:type=Connector,port=" + httpsPort + ",*";
final ObjectName objectNameQuery = new ObjectName(objectString);
for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null))
{
if (server.queryNames(objectNameQuery, null).size() > 0)
{
MBeanServer mbeanServer = server;
ObjectName objectName = (ObjectName) server.queryNames(objectNameQuery, null).toArray()[0];
mbeanServer.invoke(objectName, "stop", null, null);
// Polling sleep to reduce delay to safe minimum.
// Use currentTimeMillis() over nanoTime() to avoid issues
// with migrating threads across sleep() calls.
long start = System.currentTimeMillis();
// Maximum of 6 seconds, 3x time required on an idle system.
long max_duration = 6000L;
long duration = 0L;
do
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
duration = (System.currentTimeMillis() - start);
} while (duration < max_duration &&
server.queryNames(objectNameQuery, null).size() > 0);
// Use below to get more accurate metrics.
String message = "TrustStoreManager TrustStore Stop: took " + duration + "milliseconds";
logger.information(message);
mbeanServer.invoke(objectName, "start", null, null);
break;
}
}
}
catch (Exception exception)
{
//Log and throw exception
throw exception
}
}

Categories