/*
(non-Javadoc)

@see com.ibm.ws.runtime.update.RuntimeUpdateManager#createNotification(java.lang.String, boolean)
557269
@Override
    public RuntimeUpdateNotification createNotification(String name, boolean ignoreOnQuiesce) {

        if (FrameworkState.isStopping()) {
            // we are in the process of stopping, so just ignore any updates at this point
            return null;
        }

        final Future<Boolean> future = futureMonitor.createFuture(Boolean.class);
        RuntimeUpdateNotification notification = new NotificationImpl(name, future, futureMonitor, normalServerStop, ignoreOnQuiesce);

        Collection<RuntimeUpdateListener> listenerSnapshot;
        synchronized (notifications) {
            notifications.put(name, notification);
            // get a snapshot of listeners while holding the lock to avoid sending the same notification twice
            // to the same listener that happens to be getting registered at the same time as the notification is getting created.
            listenerSnapshot = new ArrayList<RuntimeUpdateListener>(updateListeners);
        }

        for (RuntimeUpdateListener updateListener : listenerSnapshot) {
            updateListener.notificationCreated(this, notification);
        }

        notification.onCompletion(cleanupListener);
        return notification;
    }
363139
@Override
    public BlockingMessage createBLO() {
        BlockingMessageImpl blo = new BlockingMessageImpl(_BLO_HOLDER.mandatoryCodes, _BLO_HOLDER.mandatoryVariableCodes,
                _BLO_HOLDER.optionalCodes, _BLO_HOLDER.mandatoryCodeToIndex, _BLO_HOLDER.mandatoryVariableCodeToIndex,
                _BLO_HOLDER.optionalCodeToIndex);
        return blo;
    }
1070522
@Override
    public void sendNotification(NotificationContext notificationContext) {
        SystemAssert.requireArgument(notificationContext != null, "Notification context cannot be null.");

        Map<String, String> additionalFields = new HashMap<>();

        additionalFields.put("Notification status", "Notification created.");
        _createAnnotation(notificationContext, additionalFields);
        sendAdditionalNotification(notificationContext);
        _dispose();
    }
451524
@Override
	public synchronized void addNotification(IntegerID consumerId, AbstractMessage prefetchedMessage)
    {
		NotificationPacket notifPacket = new NotificationPacket();
    	notifPacket.setSessionId(sessionId);
        notifPacket.setConsumerId(consumerId);
        notifPacket.setMessage(prefetchedMessage);
        
        notificationBuffer.add(notifPacket);
    }
486700
private void notifyOfEntityEvent(Collection<ITypedReferenceableInstance> entityDefinitions,
                                     EntityNotification.OperationType operationType) throws AtlasException {
        List<EntityNotification> messages = new LinkedList<>();

        for (IReferenceableInstance entityDefinition : entityDefinitions) {
            Referenceable       entity                  = new Referenceable(entityDefinition);
            Map<String, Object> attributesMap           = entity.getValuesMap();
            List<String>        entityNotificationAttrs = getNotificationAttributes(entity.getTypeName());

            if (MapUtils.isNotEmpty(attributesMap) && CollectionUtils.isNotEmpty(entityNotificationAttrs)) {
                for (String entityAttr : attributesMap.keySet()) {
                    if (!entityNotificationAttrs.contains(entityAttr)) {
                        entity.setNull(entityAttr);
                    }
                }
            }

            EntityNotificationImpl notification = new EntityNotificationImpl(entity, operationType, getAllTraits(entity, typeSystem));

            messages.add(notification);
        }

        notificationInterface.send(NotificationInterface.NotificationType.ENTITIES, messages);
    }
1163812
public static void sendNotification (
        ClientObject target, String receiverCode, int methodId, Object[] args)
    {
        sendNotification(target, receiverCode, methodId, args, Transport.DEFAULT);
    }
297717
public final SubscriptionMessage createNewSubscriptionMessage() throws MessageCreateFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewSubscriptionMessage");
    SubscriptionMessage msg = null;
    try {
      msg = new SubscriptionMessageImpl(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, "createNewSubscriptionMessage");
    return msg;
  }
459715
public synchronized ApptentiveNotificationCenter addObserver(String notification, ApptentiveNotificationObserver observer) {
		addObserver(notification, observer, false);
		return this;
	}
340481
@Override
    public void addNotify() {
        super.addNotify();

        float size = Driver.getFontSize();

        JMenuBar menubar = getJMenuBar();
        if (menubar != null) {
            menubar.setFont(menubar.getFont().deriveFont(size));
            for (int i = 0; i < menubar.getMenuCount(); i++) {
                for (int j = 0; j < menubar.getMenu(i).getMenuComponentCount(); j++) {
                    Component temp = menubar.getMenu(i).getMenuComponent(j);
                    temp.setFont(temp.getFont().deriveFont(size));
                }
            }
            mainFrameTree.updateFonts(size);
        }
    }
282194
@Override
	public void onReceiveNotification(ApptentiveNotification notification) {
		checkConversationQueue();

		if (notification.hasName(NOTIFICATION_ACTIVITY_STARTED) ||
			notification.hasName(NOTIFICATION_ACTIVITY_RESUMED)) {
			final Activity activity = notification.getRequiredUserInfo(NOTIFICATION_KEY_ACTIVITY, Activity.class);
			setCurrentForegroundActivity(activity);
		} else if (notification.hasName(NOTIFICATION_APP_ENTERED_FOREGROUND)) {
			appWentToForeground();
		} else if (notification.hasName(NOTIFICATION_APP_ENTERED_BACKGROUND)) {
			setCurrentForegroundActivity(null);
			appWentToBackground();
		} else if (notification.hasName(NOTIFICATION_PAYLOAD_WILL_START_SEND)) {
			final PayloadData payload = notification.getRequiredUserInfo(NOTIFICATION_KEY_PAYLOAD, PayloadData.class);
			if (payload.getType().equals(PayloadType.message)) {
				resumeSending();
			}
		} else if (notification.hasName(NOTIFICATION_PAYLOAD_DID_FINISH_SEND)) {
			final boolean successful = notification.getRequiredUserInfo(NOTIFICATION_KEY_SUCCESSFUL, Boolean.class);
			final PayloadData payload = notification.getRequiredUserInfo(NOTIFICATION_KEY_PAYLOAD, PayloadData.class);
			final Integer responseCode = notification.getRequiredUserInfo(NOTIFICATION_KEY_RESPONSE_CODE, Integer.class);
			final JSONObject responseData = successful ? notification.getRequiredUserInfo(NOTIFICATION_KEY_RESPONSE_DATA, JSONObject.class) : null;
			if (responseCode == -1) {
				pauseSending(SEND_PAUSE_REASON_NETWORK);
			}

			if (payload.getType().equals(PayloadType.message)) {
				onSentMessage(payload.getNonce(), responseCode, responseData);
			}
		}
	}
445670
public void onNotify(RequestEvent event, ActivityContextInterface aci) {
		if (tracer.isFineEnabled())
			tracer.fine("Received Notify, on activity: " + aci.getActivity() + "\nRequest:\n" + event.getRequest());
		
		Request request = event.getRequest();
		SubscriptionData subscriptionData = getSubscriptionDataCMP();
		EventHeader eventHeader = (EventHeader) request.getHeader(EventHeader.NAME);
		if (eventHeader == null || !eventHeader.getEventType().equals(subscriptionData.getEventPackage())) {
			try {
				Response badEventResponse = this.messageFactory.createResponse(Response.BAD_EVENT, request);
				event.getServerTransaction().sendResponse(badEventResponse);
				// TODO: terminate dialog?
			} catch (Exception e) {
				if (tracer.isSevereEnabled()) {
					tracer.severe("Failed to create 489 answer to NOTIFY", e);
				}

			}
			return;
			
		} else {

			try {
				Response okResponse = this.messageFactory.createResponse(Response.OK, request);
				event.getServerTransaction().sendResponse(okResponse);				
			} catch (Exception e) {
				if (tracer.isSevereEnabled()) {
					tracer.severe("Failed to create 200 answer to NOTIFY", e);
				}
				return;
			}
		}
		// lets create Notify
		Notify notify = new Notify();
		notify.setSubscriber(subscriptionData.getSubscriberURI());

		ContentTypeHeader contentType = (ContentTypeHeader) request.getHeader(ContentTypeHeader.NAME);
		if (contentType != null) {
			// use CT Header?
			notify.setContentType(contentType.getContentType());
			notify.setContentSubType(contentType.getContentSubType());
			notify.setContent(new String(request.getRawContent()));
		}
		notify.setNotifier(subscriptionData.getNotifierURI());
		// check, whats in header.

		SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME);

		SubscriptionStatus state = SubscriptionStatus.fromString(subscriptionStateHeader.getState());
		notify.setStatus(state);
		
		// do magic
		switch (state) {
		case active:
		case pending:
			// check for exp
			if (subscriptionStateHeader.getExpires() != Notify.NO_TIMEOUT) {
				notify.setExpires(subscriptionStateHeader.getExpires());
				// set timer if needed
				SubscribeRequestType subscribeRequestType = getSubscribeRequestTypeCMP();
				if (subscribeRequestType == SubscribeRequestType.NEW || subscribeRequestType == SubscribeRequestType.REFRESH) {
					startExpiresTimer(aci,subscriptionStateHeader.getExpires());
					setSubscribeRequestTypeCMP(null);
				}								
			}

			break;
		case waiting:
			// nothing...
			break;
		case extension:
			notify.setStatusExtension(subscriptionStateHeader.getState());
		case terminated:
		 	// check reason
			String reasonString = subscriptionStateHeader.getReasonCode();
			TerminationReason reason = TerminationReason.fromString(reasonString);
			notify.setTerminationReason(reason);
			if (reason != null) {
				switch (reason) {
				case rejected:
				case noresource:
				case deactivated:
				case timeout:
					break;
				case probation:
				case giveup:
					if (subscriptionStateHeader.getRetryAfter() != Notify.NO_TIMEOUT) {
						notify.setRetryAfter(subscriptionStateHeader.getRetryAfter());
					}
					break;

				case extension:
					notify.setTerminationReasonExtension(reasonString);
					break;
				}
			}
			break;

		}
		// deliver to parent
		try {
			SbbLocalObjectExt sbbLocalObjectExt = sbbContext.getSbbLocalObject();
			if(state == SubscriptionStatus.terminated)
			{
				cancelExpiresTimer(aci);
				aci.detach(sbbLocalObjectExt);
				event.getDialog().delete();
			}
			((SubscriptionClientParentSbbLocalObject)sbbLocalObjectExt.getParent()).onNotify(notify, (SubscriptionClientChildSbbLocalObject) sbbLocalObjectExt);
		} catch (Exception e) {
			if (tracer.isSevereEnabled()) {
				tracer.severe("Received exception from parent on notify callback", e);
			}
		}

	}
1179889
@Trivial  //trace is manually added.
    @Override
    public void notificationCreated(RuntimeUpdateManager updateManager, RuntimeUpdateNotification notification) {
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "notificationCreated", notification.getName());
            
        if (configChecked) {
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "notificationCreated: early return.", notification.getName());
            return;
        }

        if (!configChecked && RuntimeUpdateNotification.APPLICATIONS_STARTING.equals(notification.getName())) {
            configChecked = true;
            
            try {
                String sessionCacheConfigFilter = FilterUtils.createPropertyFilter(Constants.SERVICE_PID, "com.ibm.ws.session.cache");

                Configuration[] sessionCacheConfigurations = configAdmin.listConfigurations(sessionCacheConfigFilter);
                
                if (sessionCacheConfigurations.length != 1) {
                    if (trace && tc.isDebugEnabled())
                        Tr.debug(this, tc, "There should always be one exactly one sessionCacheConfiguration. "
                                        + "Number of sessionCacheConfigurations found = " + sessionCacheConfigurations.length);
                }
                
                if (sessionCacheConfigurations != null) {
                    for (Configuration configuration : sessionCacheConfigurations) {
                        if (configuration == null) {
                            continue;
                        }

                        Dictionary<String, Object> props = configuration.getProperties();
                        String[] libraryRefs = (String[]) props.get("libraryRef");

                        if (libraryRefs == null) {               
                            if (!isSessionCacheBellConfigured()) {
                                Tr.error(tc, "ERROR_CONFIG_INVALID_HTTPSESSIONCACHE", Tr.formatMessage(tc, "SESSION_CACHE_CONFIG_MESSAGE", sampleConfig));
                            }
                        } else if (libraryRefs.length == 0) {
                            Tr.debug(tc, "The libraryRef attribute of the httpSessionCache in the server configuration could not be resolved. "
                                            + "Check for possible CWWKG0033W messages.");
                        } else {
                            //verify that the libraryRef points to a valid library configuration object.
                            Configuration libraryConfiguration = configAdmin.getConfiguration(libraryRefs[0]);
                            if(libraryConfiguration != null) {
                                //We found nothing wrong with the configuration.
                                if (trace && tc.isDebugEnabled())
                                    Tr.debug(this, tc, "A httpSessionCache configuration with a valid libraryRef was found.");
                            } else {
                                //This case should not be possible. 
                                //If the libraryRef is missing then libraryRefs is null.
                                //If the libraryRef points to an invalid library, libraryRefs length is 0.
                                //If there is more than one libraryRef, a CWWKG0014E error will have already been thrown.
                                if (trace && tc.isDebugEnabled())
                                    Tr.debug(this, tc, "A httpSessionCache configuration with a valid libraryRef was found, "
                                                    + "but the configuration the libraryRef points to is null. "
                                                    + "This should never happen.");
                            }
                        }
                    }
                }
            } catch ( InvalidSyntaxException | IOException ex) {
                //Something unexpected happened, log the exception as an error.
                Tr.error(tc, "ERROR_SESSION_INIT", ex);
            }
        }
        
        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "notificationCreated", notification.getName());
    }
102973
public void add(T notification) {
        notificationArray.remove(notification.getId());
        notificationArray.put(notification.getId(), notification);
    }
687491
public void updateClientNotificationListener(RESTRequest request, String objectNameStr, NotificationFilter[] filters, JSONConverter converter) {
        NotificationTargetInformation nti = toNotificationTargetInformation(request, objectNameStr);

        ClientNotificationListener listener = listeners.get(nti);

        if (listener == null) {
            throw ErrorHelper.createRESTHandlerJsonException(new RuntimeException("There are no listeners registered for " + nti), converter, APIConstants.STATUS_BAD_REQUEST);
        }

        //Make the update
        listener.addClientNotification(filters);
    }
486436
public NotificationArea createNotificationArea(RESTRequest request, String basePath, NotificationSettings notificationSettings) {
        //Cleanup old clients
        cleanUp(request);

        //Fetch a new ID
        int clientID = getNewClientID();

        //Make the new inbox and insert into map
        ClientNotificationArea newInbox = new ClientNotificationArea(notificationSettings.deliveryInterval, notificationSettings.inboxExpiry, clientID);

        //Don't need to use "putIfAbsent" here because the key is guaranteed to be unique
        inboxes.put(clientID, newInbox);

        //Create the notification area to be returned to the client
        NotificationArea newArea = new NotificationArea();
        newArea.clientURL = basePath + clientID;
        newArea.inboxURL = newArea.clientURL + "/inbox";
        newArea.registrationsURL = newArea.clientURL + "/registrations";
        newArea.serverRegistrationsURL = newArea.clientURL + "/serverRegistrations";

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Created notification area for client ID " + clientID);
        }

        return newArea;
    }
306650
public static void localRunnerNotification(JobConf conf, JobStatus status) {
    JobEndStatusInfo notification = createNotification(conf, status);
    if (notification != null) {
      while (notification.configureForRetry()) {
        try {
          int code = httpNotification(notification.getUri());
          if (code != 200) {
            throw new IOException("Invalid response status code: " + code);
          }
          else {
            break;
          }
        }
        catch (IOException ioex) {
          LOG.error("Notification error [" + notification.getUri() + "]", ioex);
        }
        catch (Exception ex) {
          LOG.error("Notification error [" + notification.getUri() + "]", ex);
        }
        try {
          synchronized (Thread.currentThread()) {
            Thread.currentThread().sleep(notification.getRetryInterval());
          }
        }
        catch (InterruptedException iex) {
          LOG.error("Notification retry error [" + notification + "]", iex);
        }
      }
    }
  }
323161
public static InternalEvent createActivityNotifyMessage(ActivityInstance ai,
            Integer eventType, String masterRequestId, String compCode) {
        InternalEvent event = new InternalEvent();
        event.workId = ai.getActivityId();
        event.transitionInstanceId = null;
        event.eventType = eventType;
        event.ownerType = OwnerType.PROCESS_INSTANCE;
        event.ownerId = ai.getProcessInstanceId();
        event.masterRequestId = masterRequestId;
        event.workInstanceId = ai.getId();
        event.completionCode = compCode;
        return event;
    }