I have this code to get the external ip of instances in GCP project
private static void printInstances(Compute compute, String projectId) throws IOException {
final Compute.Instances.List instances = compute.instances().list(projectId, zoneName);
final InstanceList list = instances.execute();
if ( list.getItems() == null ) {
System.out.println("No instances found. Sign in to the Google APIs Console and create an instance at: code.google.com/apis/console");
} else {
for ( final Instance instance : list.getItems() ) {
//System.out.println(instance.toPrettyString());
System.out.println("------------- " + instance.getName() + " (" + instance.getId() + ")");
final List<NetworkInterface> networkInterfaces = instance.getNetworkInterfaces();
for ( final NetworkInterface networkInterface : networkInterfaces ) {
String extIP = null;
final List<AccessConfig> accessConfigs = networkInterface.getAccessConfigs();
for ( final AccessConfig accessConfig : accessConfigs ) { // More than one?
extIP = accessConfig.getNatIP();
}
System.out.println(" Private=[" + networkInterface.getNetworkIP() + "] Public=[" + extIP + "]");
}
}
}
}
I want to get the same (meaning accessConfig.getNatIP) form instance of GCP ManagedInstance.
Like this:
Compute.InstanceGroupManagers.ListManagedInstances listInstances =
compute.instanceGroupManagers().listManagedInstances(projectId, zoneName, groupName);
List<ManagedInstance> list = listInstances.execute().getManagedInstances();
But I have found no way to get this.
Compute.InstanceGroupManagers.ListManagedInstances contains the URLs of the instances. Then use instances.get API to get the external IP in the instance.
Related
I am trying to restrict the results of my BabelNet query to a specific (Babel)domain. To do that, I'm trying to find out a way to compare the synsets' domains with the domain I need (Geographical). However, I'm having trouble getting the right output, since although the 2 strings match, it still gives me the wrong output. I'm surely doing something wrong here, but I'm out of ideas.
After many trials, the following code was the one that gave me the nearest result to the desired output:
public class GeoRestrict {
public static void main(String[] args) throws IOException {
String file = "/path/to/file/testdata.txt";
BabelNet bn = BabelNet.getInstance();
BufferedReader br = new BufferedReader(new FileReader(file));
String word = null;
while ((word = br.readLine()) != null) {
BabelNetQuery query = new BabelNetQuery.Builder(word)
.build();
List<BabelSynset> wordSynset = bn.getSynsets(query);
for (BabelSynset synset : wordSynset) {
BabelSynsetID id = synset.getID();
System.out.println("\n" + "Synset ID for " + word.toUpperCase() + " is: " + id);
HashMap<Domain, Double> domains = synset.getDomains();
Set<Domain> keys = domains.keySet();
String keyString = domains.keySet().toString();
List<String> categories = synset.getDomains().keySet().stream()
.map(domain -> ((BabelDomain) domain).getDomainString())
.collect(Collectors.toList());
for (String category : categories) {
if(keyString.equals(category)) {
System.out.println("The word " + word + " has the domain " + category);
} else {
System.out.println("Nada! " + category);
}
}
}
}
br.close();
}
}
The output looks like this:
Synset ID for TURIN is: bn:00077665n
Nada! Geography and places
Any ideas on how to solve this issue?
I found my own error. For the sake of completeness I'm posting it.
The BabelDomain needs to be declared and specified (before the while-loop), like this:
BabelDomain domain = BabelDomain.GEOGRAPHY_AND_PLACES;
The following java code lists all the bare metal servers in softlayer for a specific SL account and filters for servers which are powered on (e.g. powerState='on'.
public void listServers(Account.Service service, ApiClient client) throws Exception {
service.withMask().hardware().fullyQualifiedDomainName().primaryIpAddress();
service.withMask().hardware().hardwareStatus();
service.withMask().hardware().id();
Account account = service.getObject();
//
// list of softlayer servers for the client account
//
for (Hardware hardware : account.getHardware()) {
String hostname = hardware.getFullyQualifiedDomainName();
String hardwareStatus = (hardware.getHardwareStatus() == null) ? null : hardware.getHardwareStatus().getStatus();
Long serverId = hardware.getId();
String powerState = null;
if (serverId != null) {
Hardware.Service hardwareService = Hardware.service(client, serverId);
hardwareService.setMask("mask[serverPowerState");
try {
powerState = hardwareService.getServerPowerState();
} catch (Exception ex) {
System.out.println("Error, cannot get powerState, hostname=" + hostname + ", msg=" + ex.getMessage());
}
}
System.out.println("Hostname=" + hostname + ", hwStatus=" + hardwareStatus + ", powerState=" + powerState);
}
}
Code seems to work, but for at least one of the servers, it fails on the call to hardwareService.getServerPowerState()
"Unable to establish IPMI v2 / RMCP+ session".
Any ideas why this is failing ?
I want to discover all the destinations from solace (queues and topics)
I tried using MBeanServerConnection and query after names (but I didn't find a proper way to use this) or JNDI lookups Destination dest = (Destination) context.lookup(Dest_name), but I don't have the names of the queues/topics.
I am using solace - jms library.
I am searching for smth like this: (but for solace, not activeMq)
get all Queue from activeMQ
You will need to make use of SEMP over the management interface for this.
Sample commands:
curl -d '<rpc><show><queue><name>*</name></queue></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
curl -d '<rpc><show><topic-endpoint><name>*</name></topic-endpoint></show></rpc>' -u semp_username:semp_password http://your_management_ip:your_management_port/SEMP
Note that I'm using curl for simplicity, but any application can perform HTTP POSTs to execute these commands.
If you are using Java, you can refer to the SempHttpSetRequest sample found within the Solace API samples.
Documentation on SEMP can be found here.
However, the larger question here is why do you need to discover all destinations?
One of the features of the message broker is to decouple the publishers and consumers.
If you need to know if your persistent message is being published to a topic with no consumers, you can make use of the reject-msg-to-sender-on-no-subscription-match setting in the publishing application's client-profile.
This means that the publisher will obtain a negative acknowledgement in the event that it tries to publish a message on a topic that has no matching subscribers.
You can refer to "Handling Guaranteed Messages with No Matches" at https://docs.solace.com/Configuring-and-Managing/Configuring-Client-Profiles.htm for further details.
Here is some source code that might help. With the appliance configured correctly, SEMP is also available over JMS on topic "#SEMP/(router)/SHOW".
/**
* Return the SolTopicInfo for this topic (or all topics if 'topic' is null).
*
* #param session
* #param endpointName
* #return
*/
public static SolTopicInfo[] getTopicInfo(JCSMPSession session, String endpointName, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolTopicInfo> tiMap = new HashMap<String, SolTopicInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_TE_TOPICS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><topic-endpoint><name>"
+ endpointName
+ "</name><vpn-name>"+ vpn + "</vpn-name></topic-endpoint></show></rpc>";
RpcReply teTopics = sendRequest(session, SEMP_SHOW_TE_TOPICS);
for (TopicEndpoint2 te : teTopics.getRpc().getShow().getTopicEndpoint().getTopicEndpoints()
.getTopicEndpointArray()) {
SolTopicInfo ti = new SolTopicInfo();
ti.setBindCount(te.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
ti.setEndpoint(te.getName());
ti.setMessageVPN(te.getInfo().getMessageVpn());
ti.setTopic(te.getInfo().getDestination());
ti.setDurable(te.getInfo().getDurable());
ti.setInSelPres(te.getInfo().getIngressSelectorPresent());
ti.setHwmMB(formatter.format(te.getInfo().getHighWaterMarkInMb()));
ti.setSpoolUsageMB(formatter.format(te.getInfo().getCurrentSpoolUsageInMb()));
ti.setMessagesSpooled(te.getInfo().getNumMessagesSpooled().longValue());
String status = te.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getIngressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + te.getInfo().getType().substring(0, 1).toUpperCase();
ti.setStatus(status);
tiMap.put(ti.getEndpoint(), ti);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return tiMap.values().toArray(new SolTopicInfo[0]);
}
/**
* Return the SolQueueInfo for this queue (or all queues if 'queue' is null).
*
* #param session
* #param queue
* #param vpn (if null, use the session's vpn name)
* #param sempVersion, if null use 'soltr/7_1_1'
* #return
*/
public static SolQueueInfo[] getQueueInfo(JCSMPSession session, String queue, String vpn,
String sempVersion) {
XMLMessageConsumer cons = null;
XMLMessageProducer prod = null;
Map<String, SolQueueInfo> qiMap = new HashMap<String, SolQueueInfo>();
try {
// Create a producer and a consumer, and connect to appliance.
prod = session.getMessageProducer(new PubCallback());
cons = session.getMessageConsumer(new SubCallback());
cons.start();
if (vpn == null) vpn = (String) session.getProperty(JCSMPProperties.VPN_NAME);
if (sempVersion == null) sempVersion = getSempVersion(session);
// Extract the router name.
final String SEMP_SHOW_QUEUE_SUBS = "<rpc semp-version=\""
+ sempVersion
+ "\"><show><queue><name>"
+ queue
+ "</name><vpn-name>"+ vpn + "</vpn-name><subscriptions/><count/><num-elements>200</num-elements></queue></show></rpc>";
RpcReply queueSubs = sendRequest(session, SEMP_SHOW_QUEUE_SUBS);
for (QueueType qt : queueSubs.getRpc().getShow().getQueue().getQueues().getQueueArray()) {
SolQueueInfo qi = new SolQueueInfo();
qi.setBindCount(qt.getInfo().getBindCount());
//qi.setDescription(qt.getInfo().getNetworkTopic());
qi.setName(qt.getName());
qi.setMessageVPN(qt.getInfo().getMessageVpn());
qi.setDurable(qt.getInfo().getDurable());
qi.setEgSelPres(qt.getInfo().getEgressSelectorPresent());
qi.setHwmMB(formatter.format(qt.getInfo().getHighWaterMarkInMb()));
qi.setMessagesSpooled(qt.getInfo().getNumMessagesSpooled().longValue());
qi.setSpoolUsageMB(formatter.format(qt.getInfo().getCurrentSpoolUsageInMb()));
String status = qt.getInfo().getIngressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressConfigStatus().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getAccessType().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getEgressSelectorPresent().substring(0, 1).toUpperCase();
status += " " + qt.getInfo().getType().substring(0, 1).toUpperCase();
status += qt.getInfo().getDurable() ? " D" : " N";
qi.setStatus(status);
for (Subscription sub : qt.getSubscriptions().getSubscriptionArray()) {
qi.addSubscription(sub.getTopic());
}
qiMap.put(qi.getName(), qi);
}
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
if (cons != null)
cons.close();
if (prod != null)
prod.close();
}
return qiMap.values().toArray(new SolQueueInfo[0]);
}
private static String getSempVersion(JCSMPSession session)
{
String retval = "soltr/7_1_1";
try {
String peerVersion = (String)session.getCapability(CapabilityType.PEER_SOFTWARE_VERSION);
if (peerVersion != null)
{
retval = "soltr/";
String[] version = peerVersion.split("\\.");
retval += version[0];
retval += "_" + version[1];
if (!version[2].equals("0")) retval += "_" + version[2];
}
} catch (Throwable e) {
System.err.println(e);
}
return retval;
}
private static RpcReply sendRequest(JCSMPSession session,
final String requestStr) {
try {
// Set up the requestor and request message.
String routerName = (String) session
.getCapability(CapabilityType.PEER_ROUTER_NAME);
final String SEMP_TOPIC_STRING = String.format("#SEMP/%s/SHOW",
routerName);
final Topic SEMP_TOPIC = JCSMPFactory.onlyInstance().createTopic(
SEMP_TOPIC_STRING);
Requestor requestor = session.createRequestor();
BytesXMLMessage requestMsg = JCSMPFactory.onlyInstance().createMessage(
BytesXMLMessage.class);
requestMsg.writeAttachment(requestStr.getBytes());
BytesXMLMessage replyMsg = requestor
.request(requestMsg, 5000, SEMP_TOPIC);
String replyStr = new String();
if (replyMsg.getAttachmentContentLength() > 0) {
byte[] bytes = new byte[replyMsg.getAttachmentContentLength()];
replyMsg.readAttachmentBytes(bytes);
replyStr = new String(bytes, "US-ASCII");
}
RpcReplyDocument doc = RpcReplyDocument.Factory.parse(replyStr);
RpcReply reply = doc.getRpcReply();
if (reply.isSetPermissionError()) {
throw new RuntimeException(
"Permission Error: Make sure SEMP over message bus SHOW commands are enabled for this VPN");
}
if( reply.isSetParseError() ) {
throw new RuntimeException( "SEMP Parse Error: " + reply.getParseError() );
}
if( reply.isSetLimitError() ) {
throw new RuntimeException( "SEMP Limit Error: " + reply.getLimitError() );
}
if( reply.isSetExecuteResult() && reply.getExecuteResult().isSetReason() ) { // axelp: encountered this error on invalid 'queue' name
throw new RuntimeException( "SEMP Execution Error: " + reply.getExecuteResult().getReason() );
}
return reply;
} catch (JCSMPException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (XmlException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
You can get message VPN specific queues and topics using following SEMPv2 command.
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/queues?select="queueName"
curl -s -X GET -u semp_user:semp_pass management_host:management_port/SEMP/v2/monitor/msgVpns/{vpn-name}/topicEndpoints?select="topicEndpointName"
I have a list of properties like this,
server1.serverName =""
server1.serverType ="'
server1.hostName =""
server1.userName =""
server1.password =""
in a property file and I have 'n' no of sets,like
server2, server3,...servern in a property file. And also I have a class which contain all off these elements with getter and setter method,
public class ServerDetails implements Serializable {
private String serverName;
private String serverType;
private String hostName;
private String userName;
private String password;
...
}
Now, I need to read the above property file and create an arraylist like ,
ArrayList<ServerDetails> serverDetailsList = new ArrayList<ServerDetails>();
where each element of the arrayList should have an object of the class ServerDetails. I need to know how to read the property file and get the server details so that I can create an object and add it to the list.
It seems kind of easy but i lost my way. Kindly help.
Thank you !!
Regards,
Bala
You could load the properties file into a Properties object, then loop through the properties like so:
int i = 1;
while( properties.get( "server" + i + ".serverName" ) != null ) {
ServerDetails details = new ...
details.setServerName( properties.get( [as above] ) );
...
list.add( details );
++i;
}
Open the file using Java IO
Parse the file line by line. Try storing the 'Key' 'value' pairs in a hashMap, you can then iterate over that adding/updating serverDetails that are stored in your arrayList.
Quick example:
private static final String KEY ="server";
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("props.properties"));
int i = 1;
while (properties.containsKey(KEY + i + ".serverName")) {
String serverName = properties.getProperty(KEY + i + ".serverName");
String serverType = properties.getProperty(KEY + i + ".serverType");
String hostName = properties.getProperty(KEY + i + ".hostName");
String userName = properties.getProperty(KEY + i + ".userName");
String password = properties.getProperty(KEY + i + ".password");
System.out.println(serverName);
System.out.println(serverType);
System.out.println(hostName);
System.out.println(userName);
System.out.println(password);
i++;
}
}
props.properties:
server1.serverName =1
server1.serverType =2
server1.hostName =3
server1.userName =4
server1.password =5
server2.serverName =6
server2.serverType =7
server2.hostName =8
server2.userName =9
server2.password =10
Properties properties = new Properties();
properties.load(new FileInputStream("application.properties"));
int i = 1;
String serverNameKey = "server" + i + ".serverName";
while (properties.containsKey(serverNameKey)) {
String serverName = (String) properties.get(serverNameKey);
//Read other properties
// Create new ServerDetails
// Add to list
i++;
}
Our developers use Java on Linux for various things (like checking membership of groups etc). It works - no problem with that!
The problem is that they have hardcoded the servernames of our Domain Controllers (LDAP-servers) in their code. So now when we need to replace them with newer DCs, they need to change the code.
Active Directory by nature is redundant. The domain name (example: domain.local) is a round-robin of all the DC:s available for our AD.
Is there any way for the developer to NOT specify Domain Controller server names but simply the Active Directory domain name and then their Linux server will find the DC:s available and use whichever one is up and running?
Examples/links appreciated. Thanks!
Obviously, the server name should at least be configurable, not hard coded into the application.
However, you should be able to find the server by looking up a special DNS record, namely a SRV record for _ldap._tcp.DOMAINNAME. The linux servers have to be configured to use the same DNS server as your AD updates.
To determine whether this is feasible, run the command host -t srv _ldap._tcp.DOMAINNAME on your linux server
See also Querying the DNS service records to find the hostname and TCP/IP provides some info on how to look up SRV records in java, and https://community.oracle.com/blogs/kohsuke/2008/06/12/more-active-directory-integration-java
We use the follow code that work on a large amount of systems:
/**
* Detect the default LDAP server
* #return server:port or null
*/
String getDefaultLdapHost() {
try {
Hashtable<String, String> env = new Hashtable();
env.put( "java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory" );
DirContext dns = new InitialDirContext( env );
InetAddress address = InetAddress.getLocalHost();
String domain = address.getCanonicalHostName();
if( domain.equals( address.getHostAddress() ) ) {
//domain is a ip address
domain = getDnsPtr( dns );
}
int idx = domain.indexOf( '.' );
if( idx < 0 ) {
//computer is not in a domain? We will look in the DNS self.
domain = getDnsPtr( dns );
idx = domain.indexOf( '.' );
if( idx < 0 ) {
//computer is not in a domain
return null;
}
}
domain = domain.substring( idx + 1 );
Attributes attrs = dns.getAttributes( "_ldap._tcp." + domain, new String[] { "SRV" } );
Attribute attr = attrs.getAll().nextElement();
String srv = attr.get().toString();
String[] parts = srv.split( " " );
return parts[3] + ":" + parts[2];
} catch( Exception ex ) {
ex.printStackTrace();
return null;
}
}
/**
* Look for a reverse PTR record on any available ip address
* #param dns DNS context
* #return the PTR value
* #throws Exception if the PTR entry was not found
*/
private String getDnsPtr( DirContext dns ) throws Exception {
Exception exception = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()) {
NetworkInterface nif = interfaces.nextElement();
if( nif.isLoopback() ) {
continue;
}
Enumeration<InetAddress> adresses = nif.getInetAddresses();
while(adresses.hasMoreElements()) {
InetAddress address = adresses.nextElement();
if( address.isLoopbackAddress() || address instanceof Inet6Address) {
continue;
}
String domain = address.getCanonicalHostName();
if( !domain.equals( address.getHostAddress() ) && (domain.indexOf( '.' ) > 0) ) {
return domain;
}
String ip = address.getHostAddress();
String[] digits = ip.split( "\\." );
StringBuilder builder = new StringBuilder();
builder.append( digits[3] ).append( '.' );
builder.append( digits[2] ).append( '.' );
builder.append( digits[1] ).append( '.' );
builder.append( digits[0] ).append( ".in-addr.arpa." );
try {
Attributes attrs = dns.getAttributes( builder.toString(), new String[] { "PTR" } );
return attrs.get( "PTR" ).get().toString();
} catch( Exception ex ) {
exception = ex;
}
}
}
if( exception != null ) {
throw exception;
}
throw new IllegalStateException("No network");
}