/*
(non-Javadoc)
@see net.roboconf.target.api.TargetHandler
#isMachineRunning(net.roboconf.target.api.TargetHandlerParameters, java.lang.String)
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;
	}
447278
@Override
  public boolean onGenericMotionEvent(MotionEvent event) {
    if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
      switch (event.getAction()) {
        case MotionEvent.ACTION_SCROLL: {
          if (!mIsBeingDragged) {
            final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
            final float hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
            if (vscroll != 0) {
              final int verticalScrollRange = getVerticalScrollRange();
              final int horizontalScrollRange = getHorizontalScrollRange();
              int oldScrollY = getScrollY();
              int oldScrollX = getScrollX();
              int newScrollY = (int) (oldScrollY - vscroll);
              int newScrollX = (int) (oldScrollX - hscroll);
              if (newScrollY < 0) {
                newScrollY = 0;
              } else if (newScrollY > verticalScrollRange) {
                newScrollY = verticalScrollRange;
              }
              if (newScrollX < 0) {
                newScrollX = 0;
              } else if (newScrollX > horizontalScrollRange) {
                newScrollX = horizontalScrollRange;
              }
              if (newScrollY != oldScrollY || newScrollX != oldScrollX) {
                super.scrollTo(newScrollX, newScrollY);
                return true;
              }
            }
          }
        }
      }
    }
    return super.onGenericMotionEvent(event);
  }
101278
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

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

		// 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." );

		// Validate all the properties here
		String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());
		Map<String,String> targetProperties = parameters.getTargetProperties();
		validateAll( targetProperties, parameters.getApplicationName(), rootInstanceName );

		// Prepare the work
		NovaApi novaApi = OpenstackIaasHandler.novaApi( targetProperties );
		String zoneName = findZoneName( novaApi, targetProperties );
		String vmName = parameters.getApplicationName() + "." + rootInstanceName;

		// Find flavor and image IDs
		String flavorId = null;
		String flavorName = targetProperties.get( OpenstackIaasHandler.FLAVOR_NAME );
		for( Resource res : novaApi.getFlavorApiForZone( zoneName ).list().concat()) {
			if( res.getName().equalsIgnoreCase( flavorName )) {
				flavorId = res.getId();
				break;
			}
		}

		if( flavorId == null )
			throw new TargetException( "No flavor named '" + flavorName + "' was found." );

		String imageId = null;
		String imageName = targetProperties.get( OpenstackIaasHandler.IMAGE_NAME );
		for( Resource res : novaApi.getImageApiForZone( zoneName ).list().concat()) {
			if( res.getName().equalsIgnoreCase( imageName )) {
				imageId = res.getId();
				break;
			}
		}

		if( imageId == null )
			throw new TargetException( "No image named '" + imageName + "' was found." );

		// Prepare the server creation
		Map<String,String> metadata = new HashMap<>(3);
		metadata.put( "Application Name", parameters.getApplicationName());
		metadata.put( "Root Instance Name", rootInstanceName );
		metadata.put( "Created by", "Roboconf" );

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

			CreateServerOptions options = CreateServerOptions.Builder
					.keyPairName( targetProperties.get( OpenstackIaasHandler.KEY_PAIR ))
					.securityGroupNames( targetProperties.get( OpenstackIaasHandler.SECURITY_GROUP ))
					.userData( userData.getBytes( StandardCharsets.UTF_8 ))
					.metadata( metadata );

			String networkId = targetProperties.get( OpenstackIaasHandler.NETWORK_ID );
			if( ! Utils.isEmptyOrWhitespaces( networkId ))
				options = options.networks( networkId );

			ServerCreated server = novaApi.getServerApiForZone( zoneName ).create( vmName, imageId, flavorId, options);
			String machineId = server.getId();
			novaApi.close();

			return machineId;

		} catch( Exception e ) {
			throw new TargetException( e );
		}
	}
1255582
private boolean processRobot(String useragent, UserAgentInfo retObj) {
        try {
            lock.lock();

            if (robotsMap.containsKey(useragent)) {
                retObj.setTyp("Robot");
                RobotEntry robotEntry = robotsMap.get(useragent);
                robotEntry.copyTo(retObj);
                if (robotEntry.getOsId() != null) {
                    OsEntry os = osMap.get(robotEntry.getOsId());
                    if (os != null) {
                        os.copyTo(retObj);
                    }
                }
                return true;
            }
        } finally {
            lock.unlock();
        }
        return false;
	}
108921
public boolean isRunning()
  {
    if (tc.isEntryEnabled())
    {
      SibTr.entry(tc, "isRunning");
      SibTr.exit(tc, "isRunning", new Boolean(_isRunning));
    }
    
    return _isRunning;
  }
1294002
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

		this.logger.fine( "Creating a new VM @ VMware." );

		// 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
		try {
			System.setProperty("org.xml.sax.driver","org.apache.xerces.parsers.SAXParser");
			Map<String,String> targetProperties = parameters.getTargetProperties();
			final String machineImageId = targetProperties.get( TEMPLATE );
			final ServiceInstance vmwareServiceInstance = getServiceInstance( targetProperties );

			final ComputeResource vmwareComputeResource = (ComputeResource)(
					new InventoryNavigator( vmwareServiceInstance.getRootFolder())
					.searchManagedEntity("ComputeResource", targetProperties.get( CLUSTER )));

			// Generate the user data first, so that nothing has been done on the IaaS if it fails
			String userData = UserDataHelpers.writeUserDataAsString(
					parameters.getMessagingProperties(),
					parameters.getDomain(),
					parameters.getApplicationName(),
					rootInstanceName );

			VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineImageId );
			String vmwareDataCenter = targetProperties.get( DATA_CENTER );
			Folder vmFolder =
					((Datacenter)(new InventoryNavigator( vmwareServiceInstance.getRootFolder())
					.searchManagedEntity("Datacenter", vmwareDataCenter)))
					.getVmFolder();

			this.logger.fine("machineImageId=" + machineImageId);
			if (vm == null || vmFolder == null)
				throw new TargetException("VirtualMachine (= " + vm + " ) or Datacenter path (= " + vmFolder + " ) is NOT correct. Please, double check.");

			VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
			cloneSpec.setLocation(new VirtualMachineRelocateSpec());
			cloneSpec.setPowerOn(false);
			cloneSpec.setTemplate(true);

			VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec();
			vmSpec.setAnnotation( userData );
			cloneSpec.setConfig(vmSpec);

			Task task = vm.cloneVM_Task( vmFolder, rootInstanceName, cloneSpec );
			this.logger.fine("Cloning the template: "+ machineImageId +" ...");
			String status = task.waitForTask();
			if (!status.equals(Task.SUCCESS))
				throw new TargetException("Failure: Virtual Machine cannot be cloned." );

			VirtualMachine vm2 = getVirtualMachine( vmwareServiceInstance, rootInstanceName );
			this.logger.fine("Transforming the clone template to Virtual machine ...");
			vm2.markAsVirtualMachine( vmwareComputeResource.getResourcePool(), null);

			DynamicProperty dprop = new DynamicProperty();
			dprop.setName("guestinfo.userdata");
			dprop.setVal(userData);
			vm2.getGuest().setDynamicProperty(new DynamicProperty[]{dprop});

			task = vm2.powerOnVM_Task(null);
			this.logger.fine("Starting the virtual machine: "+ rootInstanceName +" ...");
			status = task.waitForTask();
			if( ! status.equals( Task.SUCCESS ))
				throw new TargetException("Failure: Virtual Machine cannot be started." );

			return vm2.getName();

		} catch( Exception e ) {
			throw new TargetException( e );
		}
	}
453063
private boolean canRun(String flowName, String flowGroup, boolean allowConcurrentExecution) {
    if (allowConcurrentExecution) {
      return true;
    } else {
      return !flowStatusGenerator.isFlowRunning(flowName, flowGroup);
    }
  }
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;
	}
1327122
@Override
	public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {

		try {
			cancelMachineConfigurator( machineId );

			final ServiceInstance vmwareServiceInstance = getServiceInstance( parameters.getTargetProperties());
			VirtualMachine vm = getVirtualMachine( vmwareServiceInstance, machineId );
			if (vm == null)
				throw new TargetException( "Error vm: " + machineId + " was not found");

			Task task = vm.powerOffVM_Task();
			try {
				if(!(task.waitForTask()).equals(Task.SUCCESS))
					throw new TargetException( "Error while trying to stop vm: " + machineId);

			} catch (InterruptedException ignore) { /*ignore*/ }

			task = vm.destroy_Task();
			try {
				if(!(task.waitForTask()).equals(Task.SUCCESS))
					throw new TargetException( "Error while trying to remove vm: " + machineId);

			} catch (InterruptedException ignore) { /*ignore*/ }

		} catch( Exception e ) {
			throw new TargetException(e);
		}
	}
394001
public boolean hasRunOnMachine(String trackerHost, String trackerName) {
    return this.activeTasks.values().contains(trackerName) || 
      hasFailedOnMachine(trackerHost);
  }
18852
@Override
    public synchronized boolean isChainRunning(String chainName) {
        boolean rc = false;
        if (null != chainName) {
            Chain c = this.chainRunningMap.get(chainName);
            if (null != c) {
                rc = c.getState().equals(RuntimeState.STARTED) || c.getState().equals(RuntimeState.QUIESCED);
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "isChainRunning: " + chainName + " " + rc);
        }
        return rc;
    }
836571
public static boolean isStandaloneRunning(final ModelControllerClient client) {
        try {
            final ModelNode response = client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, "server-state"));
            if (Operations.isSuccessfulOutcome(response)) {
                final String state = Operations.readResult(response).asString();
                return !CONTROLLER_PROCESS_STATE_STARTING.equals(state)
                        && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state);
            }
        } catch (RuntimeException | IOException e) {
            LOGGER.trace("Interrupted determining if standalone is running", e);
        }
        return false;
    }
389459
@Override
	public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

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

		// We do not do anything else here.
		// We return a UUID.
		return "rbcf_" + UUID.randomUUID().toString();
	}
270607
public static boolean isCommandLine() {
        String output = AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return System.getProperty("wlp.process.type");
            }
        });
        boolean value = true;
        if (output != null && ("server".equals(output) || "client".equals(output))) {
            value = false;
        }
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("value: " + value);
        }
        return value;
    }
88855
@Override
	public MachineConfigurator machineConfigurator( TargetHandlerParameters parameters, String machineId ) {

		// machineId does not match a real container ID.
		// It is the name of the container we will create.
		DockerMachineConfigurator configurator = new DockerMachineConfigurator(
				parameters,
				machineId,
				this.userDataVolume,
				this.containerIdToVolume );

		return configurator;
	}
1262823
@Override
    public void run() {
        try {
            int maxEvents = PropertyManager.getIntegerProperty(PropertyNames.UNSCHEDULED_EVENTS_BATCH_SIZE, 100);
            if (maxEvents == 0 && hasRun) // indicates only run at startup (old behavior)
                return;
            int minAge = PropertyManager.getIntegerProperty(PropertyNames.UNSCHEDULED_EVENTS_MIN_AGE, 3600);
            if (minAge < 300) {
                logger.severe(PropertyNames.UNSCHEDULED_EVENTS_MIN_AGE + " cannot be less than 300 (5 minutes)");
                minAge = 300;
            }

            long curTime = DatabaseAccess.getCurrentTime();
            Date olderThan = new Date(curTime - minAge*1000);
            Date now = new Date(curTime);
            logger.log(LogLevel.TRACE, "Processing unscheduled events older than " + olderThan + " at: " + now);
            int count = processUnscheduledEvents(olderThan, maxEvents);
            if (count > 0)
                logger.log(LogLevel.INFO, "Processing " + count + " unscheduled events at " + new Date(DatabaseAccess.getCurrentTime()));
        }
        catch (Throwable t) {
            logger.severeException(t.getMessage(), t);
        }
    }
855204
@Override
    public void run() {
	try {
	    try {
		turnsControl.waitTurns(1, "Robot starting"); // block at the beginning so that all
							     // robots start at the
		// same time
	    } catch (BankInterruptedException exc) {
		log.trace("[run] Interrupted before starting");
	    }

	    assert getData().isEnabled() : "Robot is disabled";

	    mainLoop();

	    log.debug("[run] Robot terminated gracefully");
	} catch (Exception | Error all) {
	    log.error("[run] Problem running robot " + this, all);
	    die("Execution Error -- " + all);
	}
    }