/*******************************************************************************
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************************************************/

package io.cloudslang.worker.management;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.log4j.Logger;

import io.cloudslang.engine.node.entities.WorkerNode;
import io.cloudslang.engine.node.services.WorkerNodeService;

/**
 * @author stoneo
 * @author Avi Moradi
 * @since 15/07/2014
 */
public class WorkerRegistration {

	private static final Logger log = Logger.getLogger(WorkerRegistration.class);

	@Resource
	protected String workerUuid;
	@Resource
	protected WorkerNodeService workerNodeService;

	@PostConstruct
	public void registerWorkerPostConstruct() throws Exception {
		try {
			registerWorker();
		} catch(Exception ex) {
			log.error("Failed to register worker due to: " + ex.getMessage(), ex);
			throw ex;
		}
	}

	protected void registerWorker() throws Exception {
		try {
			WorkerNode workerNode = workerNodeService.readByUUID(workerUuid);
			if(workerNode != null) {
				log.info("Worker already registered: " + workerNode);
				return;
			}
		} catch(Exception ex) { /* Worker not found, register it */ }
		log.info("Registering worker " + workerUuid);
		String password = UUID.randomUUID().toString();
		createWorker(workerUuid, password, System.getProperty("user.dir"));
	}

	protected void createWorker(String uuid, String password, String installPath) throws UnknownHostException {
		log.info("Creating worker...");
		workerNodeService.create(uuid, password, InetAddress.getLocalHost().getCanonicalHostName(), installPath);
		workerNodeService.activate(uuid);
		log.info("Worker [" + uuid + "] registered and activated");
	}

}

@@ -678,16 +678,60 @@
 ource;%0A%0A
+import org.apache.commons.lang.StringUtils;%0A
 import o
@@ -2041,45 +2041,13 @@
 ord,
- InetAddress.getLocalHost().getCanoni
+getLo
 calH
@@ -2169,14 +2169,447 @@
 ated%22);%0A
-
 %09%7D%0A%0A
+    protected String getLocalHostName()%7B%0A        String hostName = StringUtils.EMPTY;%0A        try %7B%0A            hostName = InetAddress.getLocalHost().getCanonicalHostName();%0A        %7D catch (UnknownHostException e) %7B%0A            // on Mac OS X with Java 7 calling 'getLocalHost()' can throw UnknownHostException%0A            // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7180557%0A        %7D%0A        return hostName;%0A    %7D%0A%0A
 %7D%0A

fix hostName = InetAddress.getLocalHost().getCanonicalHostName() issue with OSX and Java7