Applies changes in the vertex assignment to the stored management graph.

@param jobID
the ID of the job whose management graph shall be updated
@param vertexAssignmentEvent
the event describing the changes in the vertex assignment
432135
private void updateManagementGraph(final JobID jobID, final VertexAssignmentEvent vertexAssignmentEvent) {

		synchronized (this.recentManagementGraphs) {

			final ManagementGraph managementGraph = this.recentManagementGraphs.get(jobID);
			if (managementGraph == null) {
				return;
			}
			final ManagementVertex vertex = managementGraph.getVertexByID(vertexAssignmentEvent.getVertexID());
			if (vertex == null) {
				return;
			}

			vertex.setInstanceName(vertexAssignmentEvent.getInstanceName());
			vertex.setInstanceType(vertexAssignmentEvent.getInstanceType());
		}
	}
986514
private void processAssignments() throws SQLException
   {
      List<Row> permanentAssignments = getRows("select * from permanent_schedul_allocation inner join perm_resource_skill on permanent_schedul_allocation.allocatiop_of = perm_resource_skill.perm_resource_skillid where permanent_schedul_allocation.projid=? order by permanent_schedul_allocation.permanent_schedul_allocationid", m_projectID);
      m_reader.processAssignments(permanentAssignments);
   }
264340
public void setJobFlowIds(java.util.Collection<String> jobFlowIds) {
        if (jobFlowIds == null) {
            this.jobFlowIds = null;
            return;
        }

        this.jobFlowIds = new com.amazonaws.internal.SdkInternalList<String>(jobFlowIds);
    }
926745
void addGroupMember(final ManagementVertex vertex) {

		while (this.groupMembers.size() <= vertex.getIndexInGroup()) {
			this.groupMembers.add(null);
		}

		this.groupMembers.set(vertex.getIndexInGroup(), vertex);

		this.getGraph().addVertex(vertex.getID(), vertex);
	}
417199
@Override
	public CompletableFuture<Acknowledge> requestSlot(
		final SlotID slotId,
		final JobID jobId,
		final AllocationID allocationId,
		final String targetAddress,
		final ResourceManagerId resourceManagerId,
		final Time timeout) {
		// TODO: Filter invalid requests from the resource manager by using the instance/registration Id

		log.info("Receive slot request {} for job {} from resource manager with leader id {}.",
			allocationId, jobId, resourceManagerId);

		try {
			if (!isConnectedToResourceManager(resourceManagerId)) {
				final String message = String.format("TaskManager is not connected to the resource manager %s.", resourceManagerId);
				log.debug(message);
				throw new TaskManagerException(message);
			}

			if (taskSlotTable.isSlotFree(slotId.getSlotNumber())) {
				if (taskSlotTable.allocateSlot(slotId.getSlotNumber(), jobId, allocationId, taskManagerConfiguration.getTimeout())) {
					log.info("Allocated slot for {}.", allocationId);
				} else {
					log.info("Could not allocate slot for {}.", allocationId);
					throw new SlotAllocationException("Could not allocate slot.");
				}
			} else if (!taskSlotTable.isAllocated(slotId.getSlotNumber(), jobId, allocationId)) {
				final String message = "The slot " + slotId + " has already been allocated for a different job.";

				log.info(message);

				final AllocationID allocationID = taskSlotTable.getCurrentAllocation(slotId.getSlotNumber());
				throw new SlotOccupiedException(message, allocationID, taskSlotTable.getOwningJob(allocationID));
			}

			if (jobManagerTable.contains(jobId)) {
				offerSlotsToJobManager(jobId);
			} else {
				try {
					jobLeaderService.addJob(jobId, targetAddress);
				} catch (Exception e) {
					// free the allocated slot
					try {
						taskSlotTable.freeSlot(allocationId);
					} catch (SlotNotFoundException slotNotFoundException) {
						// slot no longer existent, this should actually never happen, because we've
						// just allocated the slot. So let's fail hard in this case!
						onFatalError(slotNotFoundException);
					}

					// release local state under the allocation id.
					localStateStoresManager.releaseLocalStateForAllocationId(allocationId);

					// sanity check
					if (!taskSlotTable.isSlotFree(slotId.getSlotNumber())) {
						onFatalError(new Exception("Could not free slot " + slotId));
					}

					throw new SlotAllocationException("Could not add job to job leader service.", e);
				}
			}
		} catch (TaskManagerException taskManagerException) {
			return FutureUtils.completedExceptionally(taskManagerException);
		}

		return CompletableFuture.completedFuture(Acknowledge.get());
	}
207668
protected void processAssignment(Row row)
   {
      Resource resource = m_project.getResourceByUniqueID(row.getInteger("RES_UID"));
      Task task = m_project.getTaskByUniqueID(row.getInteger("TASK_UID"));

      if (task != null)
      {
         ResourceAssignment assignment = task.addResourceAssignment(resource);
         m_assignmentMap.put(row.getInteger("ASSN_UID"), assignment);

         assignment.setActualCost(row.getCurrency("ASSN_ACT_COST"));
         assignment.setActualFinish(row.getDate("ASSN_ACT_FINISH"));
         assignment.setActualOvertimeCost(row.getCurrency("ASSN_ACT_OVT_COST"));
         assignment.setActualOvertimeWork(row.getDuration("ASSN_ACT_OVT_WORK"));
         assignment.setActualStart(row.getDate("ASSN_ACT_START"));
         assignment.setActualWork(row.getDuration("ASSN_ACT_WORK"));
         assignment.setACWP(row.getCurrency("ASSN_ACWP"));
         assignment.setBaselineCost(row.getCurrency("ASSN_BASE_COST"));
         assignment.setBaselineFinish(row.getDate("ASSN_BASE_FINISH"));
         assignment.setBaselineStart(row.getDate("ASSN_BASE_START"));
         assignment.setBaselineWork(row.getDuration("ASSN_BASE_WORK"));
         assignment.setBCWP(row.getCurrency("ASSN_BCWP"));
         assignment.setBCWS(row.getCurrency("ASSN_BCWS"));
         assignment.setCost(row.getCurrency("ASSN_COST"));
         assignment.setCostRateTableIndex(row.getInt("ASSN_COST_RATE_TABLE"));
         //assignment.setCostVariance();
         //assignment.setCreateDate(row.getDate("ASSN_CREATION_DATE")); - not present in some MPD files?
         //assignment.setCV();
         assignment.setDelay(row.getDuration("ASSN_DELAY"));
         assignment.setFinish(row.getDate("ASSN_FINISH_DATE"));
         assignment.setFinishVariance(MPDUtility.getAdjustedDuration(m_project, row.getInt("ASSN_FINISH_VAR"), TimeUnit.DAYS));

         //assignment.setGUID();
         assignment.setLevelingDelay(MPDUtility.getAdjustedDuration(m_project, row.getInt("ASSN_LEVELING_DELAY"), MPDUtility.getDurationTimeUnits(row.getInt("ASSN_DELAY_FMT"))));
         assignment.setLinkedFields(row.getBoolean("ASSN_HAS_LINKED_FIELDS"));
         //assignment.setOvertimeCost();
         assignment.setOvertimeWork(row.getDuration("ASSN_OVT_WORK"));
         //assignment.setPercentageWorkComplete();
         assignment.setRemainingCost(row.getCurrency("ASSN_REM_COST"));
         assignment.setRemainingOvertimeCost(row.getCurrency("ASSN_REM_OVT_COST"));
         assignment.setRemainingOvertimeWork(row.getDuration("ASSN_REM_OVT_WORK"));
         assignment.setRegularWork(row.getDuration("ASSN_REG_WORK"));
         assignment.setRemainingWork(row.getDuration("ASSN_REM_WORK"));
         assignment.setResponsePending(row.getBoolean("ASSN_RESPONSE_PENDING"));
         assignment.setStart(row.getDate("ASSN_START_DATE"));
         assignment.setStartVariance(MPDUtility.getAdjustedDuration(m_project, row.getInt("ASSN_START_VAR"), TimeUnit.DAYS));

         //assignment.setSV();
         assignment.setTeamStatusPending(row.getBoolean("ASSN_TEAM_STATUS_PENDING"));
         assignment.setUniqueID(row.getInteger("ASSN_UID"));
         assignment.setUnits(Double.valueOf(row.getDouble("ASSN_UNITS").doubleValue() * 100.0d));
         assignment.setUpdateNeeded(row.getBoolean("ASSN_UPDATE_NEEDED"));
         //assignment.setVAC(v);
         assignment.setWork(row.getDuration("ASSN_WORK"));
         assignment.setWorkContour(WorkContour.getInstance(row.getInt("ASSN_WORK_CONTOUR")));
         //assignment.setWorkVariance();

         String notes = row.getString("ASSN_RTF_NOTES");
         if (notes != null)
         {
            if (m_preserveNoteFormatting == false)
            {
               notes = RtfHelper.strip(notes);
            }
            assignment.setNotes(notes);
         }

         m_eventManager.fireAssignmentReadEvent(assignment);
      }
   }
630997
public void fireAssignmentReadEvent(ResourceAssignment resourceAssignment)
   {
      if (m_projectListeners != null)
      {
         for (ProjectListener listener : m_projectListeners)
         {
            listener.assignmentRead(resourceAssignment);
         }
      }
   }
1010067
public void copy(VertexData data) {
        clear();
        indices.addAll(data.indices);
        final TIntObjectIterator<VertexAttribute> iterator = data.attributes.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            attributes.put(iterator.key(), iterator.value().clone());
        }
        nameToIndex.putAll(data.nameToIndex);
    }
411937
private void insertOrUpdateTasks(TaskStartEvent event) {
        Assignment old = event.getOldAssignment();
        Assignment current = event.getNewAssignment();

        Map<Integer, String> task2Component = event.getTask2Component();
        List<KVSerializable> taskTrackList = new ArrayList<>();

        // assign
        if (old == null) {
            Set<ResourceWorkerSlot> workers = current.getWorkers();
            logger.info("old workers are null, assigned workers:{}", Joiner.on(",").join(workers));
            for (ResourceWorkerSlot worker : workers) {
                Set<Integer> tasks = worker.getTasks();
                for (Integer task : tasks) {
                    TaskTrack track = new TaskTrack(
                            event.getClusterMetricsContext().getClusterName(), event.getTopologyId());
                    track.setStart(new Date(event.getTimestamp()));
                    track.setComponent(task2Component.get(task));
                    track.setHost(worker.getHostname());
                    track.setPort(worker.getPort());
                    track.setTaskId(task);

                    taskTrackList.add(track);
                }
            }
        } else { // rebalance, we only insert newly assigned tasks
            Set<ResourceWorkerSlot> oldWorkers = old.getWorkers();
            Joiner joiner = Joiner.on(",");
            logger.info("old workers:{}, new workers:{}", joiner.join(oldWorkers), joiner.join(current.getWorkers()));
            for (ResourceWorkerSlot worker : current.getWorkers()) {
                // a new worker, insert all tasks
                if (!oldWorkers.contains(worker)) {
                    for (Integer task : worker.getTasks()) {
                        TaskTrack track = new TaskTrack(
                                event.getClusterMetricsContext().getClusterName(),
                                event.getTopologyId());
                        track.setStart(new Date(event.getTimestamp()));
                        track.setComponent(task2Component.get(task));
                        track.setHost(worker.getHostname());
                        track.setPort(worker.getPort());
                        track.setTaskId(task);

                        taskTrackList.add(track);
                    }
                } else {
                    for (Integer task : worker.getTasks()) {
                        ResourceWorkerSlot oldWorker = old.getWorkerByTaskId(task);
                        if (oldWorker != null) {

                            // update end time of old task
                            TaskTrack oldTrack = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            oldTrack.setEnd(new Date(event.getTimestamp()));
                            oldTrack.setTaskId(task);
                            oldTrack.setHost(oldWorker.getHostname());
                            oldTrack.setPort(oldWorker.getPort());
                            taskTrackList.add(oldTrack);

                            // insert new task
                            TaskTrack track = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            track.setStart(new Date());
                            track.setComponent(task2Component.get(task));
                            track.setHost(worker.getHostname());
                            track.setPort(worker.getPort());
                            track.setTaskId(task);
                            taskTrackList.add(track);
                        }
                    }
                }
            }
        }
        if (taskTrackList.size() > 0) {
            batchAdd(taskTrackList, TABLE_TASK_TRACK);
        }
    }
1042253
@Override
	public void move(List<GeometryIndex> indices, List<List<Coordinate>> coordinates)
			throws GeometryOperationFailedException {
		if (indices == null || coordinates == null || indices.size() == 0 || coordinates.size() == 0) {
			throw new GeometryOperationFailedException("Illegal arguments passed; nothing to move.");
		}

		Geometry geometry = service.getGeometry();
		OperationSequence seq = null;
		if (isOperationSequenceActive()) {
			seq = current;
		} else {
			seq = new OperationSequence();
			redoQueue.clear();
		}
		for (int i = 0; i < indices.size(); i++) {
			if (indexService.getType(indices.get(i)) == GeometryIndexType.TYPE_VERTEX) {
				GeometryIndexOperation op = new MoveVertexOperation(indexService, coordinates.get(i).get(0));
				executeOperation(op, indices.get(i));
				seq.addOperation(op);
			} else {
				throw new GeometryOperationFailedException("Can only move vertices. Other types not suported.");
			}
		}
		if (!isOperationSequenceActive()) {
			undoQueue.add(seq);
		}
		eventBus.fireEvent(new GeometryEditMoveEvent(geometry, indices));
		if (!isOperationSequenceActive()) {
			eventBus.fireEvent(new GeometryEditShapeChangedEvent(service.getGeometry()));
		}
	}
942194
public synchronized void removeWorkManager(String id)
   {
      if (id == null || id.trim().equals(""))
         throw new IllegalArgumentException("The id of WorkManager is invalid: " + id);

      Integer i = refCountWorkmanagers.get(id);
      if (i != null)
      {
         int newValue = i.intValue() - 1;
         if (newValue == 0)
         {
            if (trace)
               log.tracef("Removed WorkManager: %s", id);

            WorkManager wm = activeWorkmanagers.get(id);
            if (wm instanceof DistributedWorkManager)
            {
               DistributedWorkManager dwm = (DistributedWorkManager)wm;
               if (dwm.getTransport() != null)
                  dwm.getTransport().unregister(new Address(wm.getId(), wm.getName(), dwm.getTransport().getId()));
            }

            activeWorkmanagers.remove(id);
            refCountWorkmanagers.remove(id);
         }
         else
         {
            if (trace)
               log.tracef("DerefCount WorkManager: %s", id);

            refCountWorkmanagers.put(id, Integer.valueOf(newValue));
         }
      }
   }
332279
@Override
	public CompletableFuture<RegistrationResponse> registerJobManager(
			final JobMasterId jobMasterId,
			final ResourceID jobManagerResourceId,
			final String jobManagerAddress,
			final JobID jobId,
			final Time timeout) {

		checkNotNull(jobMasterId);
		checkNotNull(jobManagerResourceId);
		checkNotNull(jobManagerAddress);
		checkNotNull(jobId);

		if (!jobLeaderIdService.containsJob(jobId)) {
			try {
				jobLeaderIdService.addJob(jobId);
			} catch (Exception e) {
				ResourceManagerException exception = new ResourceManagerException("Could not add the job " +
					jobId + " to the job id leader service.", e);

					onFatalError(exception);

				log.error("Could not add job {} to job leader id service.", jobId, e);
				return FutureUtils.completedExceptionally(exception);
			}
		}

		log.info("Registering job manager {}@{} for job {}.", jobMasterId, jobManagerAddress, jobId);

		CompletableFuture<JobMasterId> jobMasterIdFuture;

		try {
			jobMasterIdFuture = jobLeaderIdService.getLeaderId(jobId);
		} catch (Exception e) {
			// we cannot check the job leader id so let's fail
			// TODO: Maybe it's also ok to skip this check in case that we cannot check the leader id
			ResourceManagerException exception = new ResourceManagerException("Cannot obtain the " +
				"job leader id future to verify the correct job leader.", e);

				onFatalError(exception);

			log.debug("Could not obtain the job leader id future to verify the correct job leader.");
			return FutureUtils.completedExceptionally(exception);
		}

		CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getRpcService().connect(jobManagerAddress, jobMasterId, JobMasterGateway.class);

		CompletableFuture<RegistrationResponse> registrationResponseFuture = jobMasterGatewayFuture.thenCombineAsync(
			jobMasterIdFuture,
			(JobMasterGateway jobMasterGateway, JobMasterId leadingJobMasterId) -> {
				if (Objects.equals(leadingJobMasterId, jobMasterId)) {
					return registerJobMasterInternal(
						jobMasterGateway,
						jobId,
						jobManagerAddress,
						jobManagerResourceId);
				} else {
					final String declineMessage = String.format(
						"The leading JobMaster id %s did not match the received JobMaster id %s. " +
						"This indicates that a JobMaster leader change has happened.",
						leadingJobMasterId,
						jobMasterId);
					log.debug(declineMessage);
					return new RegistrationResponse.Decline(declineMessage);
				}
			},
			getMainThreadExecutor());

		// handle exceptions which might have occurred in one of the futures inputs of combine
		return registrationResponseFuture.handleAsync(
			(RegistrationResponse registrationResponse, Throwable throwable) -> {
				if (throwable != null) {
					if (log.isDebugEnabled()) {
						log.debug("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress, throwable);
					} else {
						log.info("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress);
					}

					return new RegistrationResponse.Decline(throwable.getMessage());
				} else {
					return registrationResponse;
				}
			},
			getRpcService().getExecutor());
	}
1100738
public static void addProperty(AtlasVertex vertex, String propertyName, Object value) {
        String actualPropertyName = GraphHelper.encodePropertyKey(propertyName);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding property {} = \"{}\" to vertex {}", actualPropertyName, value, string(vertex));
        }

        vertex.addProperty(actualPropertyName, value);
    }
799779
protected synchronized void handleJobStatusChange(final String jobId, final Status status) {
    final BlockingStatus block = this.map.get(jobId);
    if (block != null) {
      block.changeStatus(status);
    }
  }
226735
private void writeResourceAssignmentWorkgroupFields(ResourceAssignmentWorkgroupFields record) throws IOException
   {
      m_buffer.setLength(0);

      m_buffer.append(MPXConstants.RESOURCE_ASSIGNMENT_WORKGROUP_FIELDS_RECORD_NUMBER);
      m_buffer.append(m_delimiter);
      m_buffer.append(format(record.getMessageUniqueID()));
      m_buffer.append(m_delimiter);
      m_buffer.append(record.getConfirmed() ? "1" : "0");
      m_buffer.append(m_delimiter);
      m_buffer.append(record.getResponsePending() ? "1" : "0");
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatDateTimeNull(record.getUpdateStart())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(formatDateTimeNull(record.getUpdateFinish())));
      m_buffer.append(m_delimiter);
      m_buffer.append(format(record.getScheduleID()));

      stripTrailingDelimiters(m_buffer);
      m_buffer.append(MPXConstants.EOL);

      m_writer.write(m_buffer.toString());
   }
1361161
protected function init(JobInterface $job, JobGraph $graph, Io\IoDescriptor $io = null)
    {
        $contexts = [];
        $inputs = $this->buildInputs($io);

        foreach ($inputs as $input) {
            $contexts[] = $this->ctxFactory->create($job, $input, $graph->current());
        }

        $msgs = $this->msgFactory->createInitMsgs($contexts);
        foreach ($msgs as $msg) {
            $this->push($msg);
        }
    }
868919
public void onGeometryEditMove(GeometryEditMoveEvent event) {
		// Find the elements that need updating:
		Map<GeometryIndex, Boolean> indicesToUpdate = new HashMap<GeometryIndex, Boolean>();
		for (GeometryIndex index : event.getIndices()) {
			if (!indicesToUpdate.containsKey(index)) {
				indicesToUpdate.put(index, false);
				if (!Geometry.POINT.equals(editService.getGeometry().getGeometryType())
						&& !Geometry.MULTI_POINT.equals(editService.getGeometry().getGeometryType())) {
					try {
						List<GeometryIndex> neighbors;
						switch (editService.getIndexService().getType(index)) {
							case TYPE_VERTEX:
								// Move current vertex to the back. This helps the delete operation.
								indicesToUpdate.put(index, true);
								neighbors = editService.getIndexService().getAdjacentEdges(event.getGeometry(), index);
								if (neighbors != null) {
									for (GeometryIndex neighborIndex : neighbors) {
										if (!indicesToUpdate.containsKey(neighborIndex)) {
											indicesToUpdate.put(neighborIndex, false);
										}
									}
								}

								neighbors = editService.getIndexService().getAdjacentVertices(event.getGeometry(),
										index);
								if (neighbors != null) {
									for (GeometryIndex neighborIndex : neighbors) {
										if (!indicesToUpdate.containsKey(neighborIndex)) {
											indicesToUpdate.put(neighborIndex, false);
										}
									}
								}
								break;
							case TYPE_EDGE:
								neighbors = editService.getIndexService().getAdjacentVertices(event.getGeometry(),
										index);
								if (neighbors != null) {
									for (GeometryIndex neighborIndex : neighbors) {
										if (!indicesToUpdate.containsKey(neighborIndex)) {
											indicesToUpdate.put(neighborIndex, false);
										}
									}
								}
								break;
							default:
						}
					} catch (GeometryIndexNotFoundException e) {
						throw new IllegalStateException(e);
					}
				}
			}
		}

		// Check if we need to draw the background (nice, but slows down):
		if (styleProvider.getBackgroundStyle() != null && styleProvider.getBackgroundStyle().getFillOpacity() > 0) {
			if (event.getGeometry().getGeometryType().equals(Geometry.POLYGON)) {
				update(null, false);
			} else if (event.getGeometry().getGeometryType().equals(Geometry.MULTI_POLYGON)
					&& event.getGeometry().getGeometries() != null) {
				for (int i = 0; i < event.getGeometry().getGeometries().length; i++) {
					GeometryIndex index = editService.getIndexService().create(GeometryIndexType.TYPE_GEOMETRY, i);
					indicesToUpdate.put(index, false);
				}
			}
		}

		// Next, redraw the list:
		for (GeometryIndex index : indicesToUpdate.keySet()) {
			update(index, indicesToUpdate.get(index));
		}
	}