/*
(non-Javadoc)
@see net.roboconf.target.api.TargetHandler
#createMachine(net.roboconf.target.api.TargetHandlerParameters)
433455
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

		this.logger.fine( "Creating a new agent in memory." );
		Map<String,String> targetProperties = preventNull( parameters.getTargetProperties());

		// Need to wait?
		try {
			String delayAsString = targetProperties.get( DELAY );
			long delay = delayAsString != null ? Long.parseLong( delayAsString ) : this.defaultDelay.get();
			if( delay > 0 )
				Thread.sleep( delay );

		} catch( Exception e ) {
			this.logger.warning( "An error occurred while applying the delay property. " + e.getMessage());
			Utils.logException( this.logger, e );
		}

		String machineId = parameters.getScopedInstancePath() + " @ " + parameters.getApplicationName();
		Factory factory = findIPojoFactory( parameters );
		createIPojo(
				targetProperties,
				parameters.getMessagingProperties(),
				machineId,
				parameters.getScopedInstancePath(),
				parameters.getApplicationName(),
				parameters.getDomain(),
				factory );

		return machineId;
	}
1230940
@Override
  public MtasTokenizer create(AttributeFactory factory) {
    MtasTokenizer tokenizer = null;
    try {
      tokenizer = create(factory, null);
    } catch (IOException e) {
      log.error(e);
    }
    return tokenizer;
  }
1249395
@Override public DeepLearningModel createImpl() {
    DeepLearningModel.DeepLearningParameters parms = parameters.createImpl();
    return new DeepLearningModel(Key.make() /*dest*/, parms, new DeepLearningModel.DeepLearningModelOutput(null), null, null, 0);
  }
1132431
public final ControlRequest createNewControlRequest() throws MessageCreateFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewControlRequest");
    ControlRequest msg = null;
    try {
      msg = new ControlRequestImpl(MfpConstants.CONSTRUCTOR_NO_OP);
    }
    catch (MessageDecodeFailedException e) {
      /* No need to FFDC this as JsMsgObject will already have done so */
      // No FFDC code needed
      throw new MessageCreateFailedException(e);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createNewControlRequest");
    return msg;
  }
335809
public static ModelControllerClient createAndAdd(final ManagementChannelHandler handler) {
        final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);
        handler.addHandlerFactory(client);
        return client;
    }
844690
public void createControlAdapter()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(this, tc, "createControlAdapter");

    if(type == Type.SOURCE)
      controlAdapter = new SourceStreamSetControl(remoteMEUuid, this);  
    else if (type == Type.LINK_SOURCE)
        controlAdapter = new LinkTransmitterControl(remoteMEUuid, this, true);
    else if (type == Type.LINK_REMOTE_SOURCE)
      controlAdapter = new LinkTransmitterControl(remoteMEUuid, this, false);
    else if(type == Type.TARGET)
      controlAdapter = new TargetStreamSetControl(this);
    else if (type == Type.LINK_TARGET)
      controlAdapter = new LinkReceiverControl(this, linkTarget);
    else if(type == Type.INTERNAL_OUTPUT)
      controlAdapter = new InternalOutputStreamSetControl(this);
    else if(type == Type.LINK_INTERNAL_OUTPUT)
      controlAdapter = new LinkPublicationPointControl(this);
    else if(type == Type.INTERNAL_INPUT)
    {
      // Nothing to do for an InternalInputStream set, we don't display those
    }
      
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "createControlAdapter");
  }
927264
@Override
    public void createControlAdapter()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "createControlAdapter");

        DestinationHandler dh = null;
        try
        {
            ItemStream is = getItemStream();
            if (is instanceof PubSubMessageItemStream)
            {
                dh = ((PubSubMessageItemStream) is).getDestinationHandler();
                controlAdapter = new QueuedMessage(this, dh, is);
            }
            else if (is instanceof MQLinkMessageItemStream)
            {
                dh = ((MQLinkMessageItemStream) is).getDestinationHandler();
                controlAdapter = new MQLinkQueuedMessage(this, dh, is);
            }
            else if (is instanceof PtoPMessageItemStream)
            {
                dh = ((PtoPMessageItemStream) is).getDestinationHandler();
                controlAdapter = new QueuedMessage(this, dh, is);
            }
            else
            {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    SibTr.debug(this, tc, "Unknown item stream type " + is);
            }
        } catch (Exception e)
        {
            FFDCFilter.processException(
                                        e,
                                        "com.ibm.ws.sib.processor.impl.store.items.MessageItem.createControlAdapter",
                                        "1:2585:1.244.1.40",
                                        this);

            SibTr.exception(tc, e);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "createControlAdapter");
    }
281347
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

		this.logger.fine( "Creating a new machine on AWS." );

		// For IaaS, we only expect root instance names to be passed
		if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 )
			throw new TargetException( "Only root instances can be passed in arguments." );

		String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());

		// Deal with the creation
		String instanceId;
		try {
			AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
			String userData = UserDataHelpers.writeUserDataAsString(
					parameters.getMessagingProperties(),
					parameters.getDomain(),
					parameters.getApplicationName(),
					rootInstanceName );

			RunInstancesRequest runInstancesRequest = prepareEC2RequestNode( parameters.getTargetProperties(), userData );
			RunInstancesResult runInstanceResult = ec2.runInstances( runInstancesRequest );
			instanceId = runInstanceResult.getReservation().getInstances().get( 0 ).getInstanceId();

		} catch( Exception e ) {
			this.logger.severe( "An error occurred while creating a new machine on EC2. " + e.getMessage());
			throw new TargetException( e );
		}

		return instanceId;
	}
785550
@Override
    public void createRobot(String name, InstructionSet pSet, int banksCount, boolean pMobile) {
	int turnsForBanks = Timing.getInstance().CREATION_BASE + Timing.getInstance().CREATION_PER_BANK * banksCount;
	if (pMobile) {
	    turnsForBanks = (int) (turnsForBanks * Timing.getInstance().MOBILITY_PENALTY + Timing.getInstance().MOBILITY_CONSTANT);
	}
	int turnsForSet = 0;
	if (pSet == InstructionSet.ADVANCED) {
	    turnsForSet = Timing.getInstance().ADVANCED_SET_PENALTY;
	}
	if (pSet == InstructionSet.SUPER) {
	    turnsForSet += Timing.getInstance().SUPER_SET_PENALTY;
	}

	int totalWait = Math.min(turnsForBanks + turnsForSet, GameSettings.getInstance().MAX_CREATE_WAIT);
	log.trace("[createRobot] Waiting {} cycles to create Robot {}", totalWait, name);
	turnsControl.waitTurns(totalWait, "Create Robot");

	robot.createRobot(name, pSet, banksCount, pMobile);
    }
1374101
@Override
	public MachineConfigurator machineConfigurator( TargetHandlerParameters parameters, String machineId ) {

		String userData = "";
		try {
			userData = UserDataHelpers.writeUserDataAsString(
					parameters.getMessagingProperties(),
					parameters.getDomain(),
					parameters.getApplicationName(),
					parameters.getScopedInstancePath());

		} catch( IOException e ) {
			this.logger.severe( "User data could not be generated." );
			Utils.logException( this.logger, e );
		}

		String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());
		return new VmWareMachineConfigurator(
				parameters.getTargetProperties(),
				userData,
				rootInstanceName,
				parameters.getScopedInstance());
	}
47847
@Override
	public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {

		this.logger.fine( "Terminating machine " + machineId );
		ComputeService computeService = jcloudContext( parameters.getTargetProperties());
		computeService.destroyNode( machineId );
		computeService.getContext().close();
	}
1031890
@Process(actionType = CreateHandler.class)
    public void createHandler(final CreateHandler action, final Dispatcher.Channel channel) {
        operationDelegate.onCreateResource(action.getAddressTemplate(), action.getInstanceName(), action.getNewModel(),
            new CrudOperationDelegate.Callback() {
                @Override
                public void onFailure(AddressTemplate template, String name, Throwable t) {
                    channel.nack(t);
                }

                @Override
                public void onSuccess(AddressTemplate addressTemplate, String name) {
                    lastModifiedInstance = action.getInstanceName();
                    // we must strip the pre-handler-chain suffix to reload a single configuration. 
                    readConfig(action.getAddressTemplate().subTemplate(0, 3), channel);
                }
            });
    }
436102
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		boolean result;
		try {
			final ServiceInstance vmwareServiceInstance = getServiceInstance( parameters.getTargetProperties());
			VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineId );
			result = vm != null;

		} catch( Exception e ) {
			throw new TargetException( e );
		}

		return result;
	}
1069722
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		boolean result = false;
		try {
			DockerClient dockerClient = DockerUtils.createDockerClient( parameters.getTargetProperties());
			ContainerState state = DockerUtils.getContainerState( machineId, dockerClient );
			result = state != null && extractBoolean( state.getRunning());

		} catch( Exception e ) {
			// nothing, we consider it is not running
			Utils.logException( this.logger, e );
		}

		return result;
	}
828985
@Override
	public final Object invoke(final String actionName, final Object[] params,
			final String[] signature) throws MBeanException,
			ReflectionException {
		// Get the JmxCommand
		JmxCommand curCmd = null;
		for (JmxCommand cmd : this.cmds) {
			if (cmd.getType().equals(actionName)) {
				curCmd = cmd;
				break;
			}
		}

		final boolean isSync = actionName.startsWith("sync");
		try {
			// initialize arguments for lunching (using Quartz)
			final Map<String, Object> jobDataMap = buildJobDataMap(curCmd, params);

			final Launch<?> launch = Launcher.getLauncher()
					.newLaunch((Class<?>) remoteProgram.getAdapterClass()).addParameters(jobDataMap);
			if (isSync) {
				// Launch and wait until terminated
				launch.synchLaunch();
				return LaunchingMessageKind.ILAUNCH0003.getFormatedMessage(
						remoteProgram.getAdapterClass().getCanonicalName(), launch.getLaunchId(),
						launch.getLaunchResult().getStatusCode(),
						launch.getLaunchResult().getReturnCode());
			} else {
				// Launch and continue
				launch.aSynchLaunch();
				return LaunchingMessageKind.ILAUNCH0002.getFormatedMessage(
						remoteProgram.getAdapterClass().getCanonicalName(), launch.getLaunchId());
			}
		} catch (LaunchException e) {
			LaunchingMessageKind.ELAUNCH0003.format(actionName, e);
		}
		
		return null;
	}
260172
@Override
	public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {
		try {
			// TODO remove next line when APIs get compatible...
			String postfix = (parameters.getTargetProperties().get(CloudautomationMixins.PROVIDER_ENDPOINT) != null ? "" : "/compute");
			OcciVMUtils.deleteVM( parameters.getTargetProperties().get(SERVER_IP_PORT) + postfix, machineId);
		} catch(TargetException ignore) {
			//ignore
		}
	}
1312093
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		boolean result = false;
		try {
			AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
			DescribeInstancesRequest dis = new DescribeInstancesRequest();
			dis.setInstanceIds(Collections.singletonList(machineId));

			DescribeInstancesResult disresult = ec2.describeInstances( dis );
			result = ! disresult.getReservations().isEmpty();

		} catch( AmazonServiceException e ) {
			// nothing, the instance does not exist

		} catch( AmazonClientException e ) {
			this.logger.severe( "An error occurred while checking whether a machine is running on Amazon EC2. " + e.getMessage());
			throw new TargetException( e );
		}

		return result;
	}