Java Code Examples for org.apache.log4j.MDC#put()

The following examples show how to use org.apache.log4j.MDC#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoggerUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Makes MDC properties
 */
public static void setupMDC(String service)
{
  MDC.put("apex.service", service);

  String value = StramClientUtils.getHostName();
  MDC.put("apex.node", value == null ? "unknown" : value);

  value = System.getenv(Environment.USER.key());
  if (value != null) {
    MDC.put("apex.user", value);
  }

  value = System.getenv(Environment.CONTAINER_ID.name());
  if (value != null) {
    ContainerId containerId = ConverterUtils.toContainerId(value);
    ApplicationId applicationId = containerId.getApplicationAttemptId().getApplicationId();
    MDC.put("apex.containerId", containerId.toString());
    MDC.put("apex.applicationId", applicationId.toString());
  }

  value = System.getProperty(APPLICATION_NAME.getLongName());
  if (value != null) {
    MDC.put("apex.application", value);
  }
}
 
Example 2
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public synchronized void setApprovedPhaseNumber(long runId, int approvedPhaseNumber, DictionaryValuesContainer mergedDictionary) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		
		WatchDog watchDog = getWatchDog(runId);
		setDictionary(watchDog, mergedDictionary);
		watchDog.setApprovedPhaseNumber(approvedPhaseNumber);
		
		notifyAll();
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 3
Source File: DefaultConsoleAppenderTest.java    From lambda-monitoring with Apache License 2.0 6 votes vote down vote up
@Test
public void testMDC() {
    PrintStream original = System.out;
    try {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outputStream, true));

        MDC.put("AWSRequestId", "AWS-REQUEST-ID");
        Logger logger = LoggerFactory.getLogger("TEST-LOGGER");

        logger.info("TEST-MESSAGE");
        assertThat(outputStream.toString(), matchesPattern("^\\[[0-9\\-:\\. ]{23}\\] AWS-REQUEST-ID INFO TEST-LOGGER - TEST-MESSAGE \\r\\n$"));
    } finally {
        System.setOut(original);
    }
}
 
Example 4
Source File: LogUtilities.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public static void setupExecutorLog4j(final String context,
                                      final String rootLoggerName) {

    final Logger logger = LogManager.getLogger(rootLoggerName);

    for (final Enumeration e = LogManager.getRootLogger().getAllAppenders(); e.hasMoreElements(); ) {
        final Appender a = (Appender) e.nextElement();
        if (a instanceof ConsoleAppender) {
            final Layout layout = a.getLayout();
            if (layout instanceof PatternLayout) {
                final PatternLayout patternLayout = (PatternLayout) layout;
                final String conversionPattern = "%d{ISO8601} [%t] [%X{context}] %-5p [%c] %m%n";
                if (! conversionPattern.equals(patternLayout.getConversionPattern())) {
                    a.setLayout(new PatternLayout(conversionPattern));
                }
            }
        }
    }

    MDC.put("context", context);

    logger.setLevel(Level.DEBUG);
}
 
Example 5
Source File: BlanketApproveAction.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public void recordAction() throws InvalidActionTakenException {
        MDC.put("docId", getRouteHeader().getDocumentId());
        updateSearchableAttributesIfPossible();

        List<ActionRequestValue> actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_COMPLETE_REQ);
        String errorMessage = validateActionRules(actionRequests);
        if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
            throw new InvalidActionTakenException(errorMessage);
        }

        LOG.debug("Checking to see if the action is legal");

            LOG.debug("Blanket approving document : " + annotation);

            if (getRouteHeader().isStateInitiated() || getRouteHeader().isStateSaved()) {
                markDocumentEnroute(getRouteHeader());
                getRouteHeader().setRoutedByUserWorkflowId(getPrincipal().getPrincipalId());
            }

            LOG.debug("Record the blanket approval action");
            Recipient delegator = findDelegatorForActionRequests(actionRequests);
            ActionTakenValue actionTaken = saveActionTaken(delegator);

            LOG.debug("Deactivate pending action requests for user");
            getActionRequestService().deactivateRequests(actionTaken, actionRequests);
            notifyActionTaken(actionTaken);

        DocumentRouteHeaderValue routeHeaderValue = KEWServiceLocator.getRouteHeaderService().
                saveRouteHeader(getRouteHeader());
        setRouteHeader(routeHeaderValue);

//        } else {
//            LOG.warn("Document not in state to be approved.");
//            throw new InvalidActionTakenException("Document is not in a state to be approved");
//        }
            
          queueDeferredWork(actionTaken);
    }
 
Example 6
Source File: InboundCorrelationEnabledHttpServerWorker.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    // Reset the correlation id MDC thread local value.
    MDC.remove(CorrelationConstants.CORRELATION_MDC_PROPERTY);
    MDC.put(CorrelationConstants.CORRELATION_MDC_PROPERTY, correlationId);
    // Log the time taken to switch from the previous thread to this thread
    correlationLog.info((System.currentTimeMillis() - initiationTimestamp) + "|Thread switch latency");
    super.run();
}
 
Example 7
Source File: CancelAction.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public void recordAction() throws InvalidActionTakenException {
    MDC.put("docId", getRouteHeader().getDocumentId());
    updateSearchableAttributesIfPossible();

    LOG.debug("Canceling document : " + annotation);

    List actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_COMPLETE_REQ);
    LOG.debug("Checking to see if the action is legal");
    String errorMessage = validateActionRules(actionRequests);
    if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
        throw new InvalidActionTakenException(errorMessage);
    }

    LOG.debug("Record the cancel action");
    ActionTakenValue actionTaken = saveActionTaken(findDelegatorForActionRequests(actionRequests));

    LOG.debug("Deactivate all pending action requests");
    actionRequests = getActionRequestService().findPendingByDoc(getDocumentId());

    getActionRequestService().deactivateRequests(actionTaken, actionRequests);
    notifyActionTaken(actionTaken);

    LOG.debug("Canceling document");

    try {
        String oldStatus = getRouteHeader().getDocRouteStatus();
        markDocumentStatus();
        String newStatus = getRouteHeader().getDocRouteStatus();
        DocumentRouteHeaderValue routeHeaderValue = KEWServiceLocator.getRouteHeaderService().
                saveRouteHeader(getRouteHeader());
        setRouteHeader(routeHeaderValue);
        notifyStatusChange(newStatus, oldStatus);
    } catch (WorkflowException ex) {
        LOG.warn(ex, ex);
        throw new InvalidActionTakenException(ex.getMessage());
    }
}
 
Example 8
Source File: CloverJMX.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public GraphTracking getGraphTracking(long runId) {
	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, runId);
	try {
		return getWatchDog(runId).getGraphTracking();
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 9
Source File: LogAppender.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public void doAppend(PaxLoggingEvent event) {
    try {
        if (MDC.get(MDC_IN_LOG_APPENDER) != null) {
            // Avoid recursion
            return;
        }
        MDC.put(MDC_IN_LOG_APPENDER, "true");
        appendInternal(event);
    } catch (Exception e) {
        LOGGER.warn("Error while appending event", e);
    } finally {
        MDC.remove(MDC_IN_LOG_APPENDER);
    }
}
 
Example 10
Source File: TrackingLogger.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void handleNotification(Notification notification, Object handback) {
	JMXNotificationMessage message = (JMXNotificationMessage) notification.getUserData();

	Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY);
	MDC.put(LogUtils.MDC_RUNID_KEY, Long.valueOf(message.getRunId()));

	try {
		if(notification.getType().equals(CloverJMX.GRAPH_STARTED)) {
			graphStarted();
		} else if(notification.getType().equals(CloverJMX.TRACKING_UPDATED)) {
			trackingUpdated();
		} else if(notification.getType().equals(CloverJMX.PHASE_FINISHED)) {
			phaseFinished();
		} else if(notification.getType().equals(CloverJMX.PHASE_ABORTED)) {
			phaseAborted();
		} else if(notification.getType().equals(CloverJMX.PHASE_ERROR)) {
			phaseError();
		} else if(notification.getType().equals(CloverJMX.GRAPH_FINISHED)
				|| notification.getType().equals(CloverJMX.GRAPH_ABORTED)
				|| notification.getType().equals(CloverJMX.GRAPH_ERROR)) {
			graphFinished();
			try {
				CloverJMX.getInstance().removeNotificationListener(this);
			} catch (ListenerNotFoundException e) {
				logger.warn("Unexpected error while graph logging will be ignored.");
			}
		}
	} finally {
		if (oldRunId == null) {
			MDC.remove(LogUtils.MDC_RUNID_KEY);
		} else {
			MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId);
		}
	}
}
 
Example 11
Source File: MoveDocumentAction.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public void recordAction() throws InvalidActionTakenException {
    MDC.put("docId", getRouteHeader().getDocumentId());
    updateSearchableAttributesIfPossible();
    LOG.debug("Moving document " + getRouteHeader().getDocumentId() + " to point: " + displayMovePoint(movePoint) + ", annotation: " + annotation);

    List actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_COMPLETE_REQ);
    Collection activeNodes = KEWServiceLocator.getRouteNodeService().getActiveNodeInstances(getRouteHeader().getDocumentId());
    String errorMessage = validateActionRules(actionRequests,activeNodes);
    if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
        throw new InvalidActionTakenException(errorMessage);
    }

    //KULRICE-12283:Modified the logic so this action moves the document to enroute status before attempting to move it to another node if it is initialized or saved
    if (getRouteHeader().isStateInitiated() || getRouteHeader().isStateSaved()) {
        markDocumentEnroute(getRouteHeader());
        getRouteHeader().setRoutedByUserWorkflowId(getPrincipal().getPrincipalId());
    }
        RouteNodeInstance startNodeInstance = determineStartNode(activeNodes, movePoint);

        LOG.debug("Record the move action");
        Recipient delegator = findDelegatorForActionRequests(actionRequests);
        ActionTakenValue actionTaken = saveActionTaken(delegator);
        getActionRequestService().deactivateRequests(actionTaken, actionRequests);
        notifyActionTaken(actionTaken);

        // TODO this whole bit is a bit hacky at the moment
        if (movePoint.getStepsToMove() > 0) {
            Set<String> targetNodeNames = new HashSet<String>();
            targetNodeNames.add(determineFutureNodeName(startNodeInstance, movePoint));

    	    final boolean shouldIndex = getRouteHeader().getDocumentType().hasSearchableAttributes() && RouteContext.getCurrentRouteContext().isSearchIndexingRequestedForContext();
            String applicationId = routeHeader.getDocumentType().getApplicationId();
            DocumentOrchestrationQueue orchestrationQueue = KewApiServiceLocator.getDocumentOrchestrationQueue(
                    routeHeader.getDocumentId(), applicationId);
            org.kuali.rice.kew.api.document.OrchestrationConfig orchestrationConfig =
                org.kuali.rice.kew.api.document.OrchestrationConfig.create(actionTaken.getActionTakenId(), targetNodeNames);
            //KULRICE-12283: Modified this to pass along two new flags to indicate that acks and FYIs should be deactivated with the move
            DocumentProcessingOptions options = DocumentProcessingOptions.create(true, shouldIndex, false, true, true);
            orchestrationQueue.orchestrateDocument(routeHeader.getDocumentId(), getPrincipal().getPrincipalId(), orchestrationConfig, options);
        } else {
            String targetNodeName = determineReturnNodeName(startNodeInstance, movePoint);
            ReturnToPreviousNodeAction returnAction = new ReturnToPreviousNodeAction(KewApiConstants.ACTION_TAKEN_MOVE_CD, getRouteHeader(), getPrincipal(), annotation, targetNodeName, false);
            
            returnAction.recordAction();
        }
}
 
Example 12
Source File: TaskLogger.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
private void updateMdcWithTaskLogFilename(TaskId id) {
    MDC.put(FileAppender.FILE_NAME, getTaskLogRelativePath(id));
}
 
Example 13
Source File: SaveActionEvent.java    From rice with Educational Community License v2.0 4 votes vote down vote up
public void recordAction() throws InvalidActionTakenException {
MDC.put("docId", getRouteHeader().getDocumentId());
LOG.debug("Checking to see if the action is legal");
/* Code below for variable 'checkIfActionIsValid' is used to identify when the 
 * DocumentRouteHeaderValue 'legal actions' should be checked for the current
 * document.  The 'legal actions' for a document that is in status ENROUTE or 
 * EXCEPTION will currently say that a Save action is not valid to be performed
 * however we still want to allow the Save action to occur if called for backward
 * compatibility issues.
 */
boolean checkIfActionIsValid = true;
if (getRouteHeader().isEnroute() || getRouteHeader().isInException()) {
    // if document is enroute or exception... don't check if the action is valid... we will assume it is valid
    checkIfActionIsValid = false;
}
String errorMessage = validateActionRulesCustom(checkIfActionIsValid);
if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
    throw new InvalidActionTakenException(errorMessage);
}

updateSearchableAttributesIfPossible();

//    if (getRouteHeader().isValidActionToTake(getActionTakenCode())) {
if (getRouteHeader().isStateInitiated()) {
    LOG.debug("Record the save action");
    ActionTakenValue actionTaken = saveActionTaken();
    //getRouteHeader().getActionRequests().add(generateSaveRequest());
    this.getActionRequestService().saveActionRequest(generateSaveRequest());
    notifyActionTaken(actionTaken);
    LOG.debug("Marking document saved");
    try {
	String oldStatus = getRouteHeader().getDocRouteStatus();
	getRouteHeader().markDocumentSaved();
	String newStatus = getRouteHeader().getDocRouteStatus();
	notifyStatusChange(newStatus, oldStatus);
           DocumentRouteHeaderValue routeHeaderValue = KEWServiceLocator.getRouteHeaderService().
                   saveRouteHeader(routeHeader);
           setRouteHeader(routeHeaderValue);
    } catch (WorkflowException ex) {
	LOG.warn(ex, ex);
	throw new InvalidActionTakenException(ex.getMessage());
    }
}
   }
 
Example 14
Source File: KualiRequestProcessor.java    From rice with Educational Community License v2.0 4 votes vote down vote up
@Override
public void process(final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // indicates that we are running in legacy KNS context
    LegacyUtils.beginLegacyContext();
    try {
        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer("Started processing request: '").append(request.getRequestURI()).append(
                    "' w/ query string: '").append(request.getQueryString()).append("'"));
        }

        try {
            strutsProcess(request, response);
        } catch (FileUploadLimitExceededException e) {
            ActionForward actionForward = processException(request, response, e, e.getActionForm(),
                    e.getActionMapping());
            processForwardConfig(request, response, actionForward);
        } finally {
            KNSGlobalVariables.setKualiForm(null);
        }

        try {
            ActionForm form = WebUtils.getKualiForm(request);

            if (form != null && form instanceof KualiDocumentFormBase) {
                String docId = ((KualiDocumentFormBase) form).getDocId();
                if (docId != null) {
                    MDC.put(MDC_DOC_ID, docId);
                }
            }

            String refreshCaller = request.getParameter(KRADConstants.REFRESH_CALLER);
            if (form != null && KualiDocumentFormBase.class.isAssignableFrom(form.getClass()) && !KRADConstants
                    .QUESTION_REFRESH.equalsIgnoreCase(refreshCaller)) {
                KualiDocumentFormBase docForm = (KualiDocumentFormBase) form;
                Document document = docForm.getDocument();
                String docFormKey = docForm.getFormKey();

                UserSession userSession = (UserSession) request.getSession().getAttribute(
                        KRADConstants.USER_SESSION_KEY);

                if (WebUtils.isDocumentSession(document, docForm)) {
                    getSessionDocumentService().setDocumentForm(docForm, userSession, request.getRemoteAddr());
                }

                Boolean exitingDocument = (Boolean) request.getAttribute(KRADConstants.EXITING_DOCUMENT);

                if (exitingDocument != null && exitingDocument.booleanValue()) {
                    // remove KualiDocumentFormBase object from session and
                    // table.
                    getSessionDocumentService().purgeDocumentForm(docForm.getDocument().getDocumentNumber(),
                            docFormKey, userSession, request.getRemoteAddr());
                }
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(new StringBuffer("Finished processing request: '").append(request.getRequestURI()).append(
                        "' w/ query string: '").append(request.getQueryString()).append("'"));
            }

        } finally {
            // MDC docId key is set above, and also during super.process() in the call to processActionForm
            MDC.remove(MDC_DOC_ID);
        }
    } finally {
        LegacyUtils.endLegacyContext();
    }
}
 
Example 15
Source File: UserFilter.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
public void doFilter(final ServletRequest req, final ServletResponse resp, final FilterChain chain) throws IOException, ServletException
{
  HttpServletRequest request = (HttpServletRequest) req;
  if (log.isDebugEnabled() == true) {
    log.debug("doFilter " + request.getRequestURI() + ": " + request.getSession().getId());
    final Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (final Cookie cookie : cookies) {
        log.debug("Cookie "
            + cookie.getName()
            + ", path="
            + cookie.getPath()
            + ", value="
            + cookie.getValue()
            + ", secure="
            + cookie.getVersion()
            + ", maxAge="
            + cookie.getMaxAge()
            + ", domain="
            + cookie.getDomain());
      }
    }
  }
  final HttpServletResponse response = (HttpServletResponse) resp;
  PFUserDO user = null;
  try {
    MDC.put("ip", request.getRemoteAddr());
    MDC.put("session", request.getSession().getId());
    if (ignoreFilterFor(request) == true) {
      // Ignore the filter for this request:
      if (log.isDebugEnabled() == true) {
        log.debug("Ignore: " + request.getRequestURI());
      }
      chain.doFilter(request, response);
    } else {
      // final boolean sessionTimeout = request.isRequestedSessionIdValid() == false;
      user = (PFUserDO) request.getSession().getAttribute(SESSION_KEY_USER);
      if (user != null) {
        if (updateRequiredFirst == false) {
          // Get the fresh user from the user cache (not in maintenance mode because user group cache is perhaps not initialized correctly
          // if updates of e. g. the user table are necessary.
          user = Registry.instance().getUserGroupCache().getUser(user.getId());
        }
        if (log.isDebugEnabled() == true) {
          log.debug("User found in session: " + request.getRequestURI());
        }
      } else if (updateRequiredFirst == false) {
        // Ignore stay-logged-in if redirect to update page is required.
        user = checkStayLoggedIn(request, response);
        if (user != null) {
          if (log.isDebugEnabled() == true) {
            log.debug("User's stay logged-in cookie found: " + request.getRequestURI());
          }
          user.setAttribute(USER_ATTR_STAY_LOGGED_IN, true); // Used by MenuMobilePage.
          UserFilter.login(request, user);
        }
      }
      if (user != null) {
        MDC.put("user", user.getUsername());
        PFUserContext.setUser(user);
        request = decorateWithLocale(request, user);
        chain.doFilter(request, response);
      } else {
        if (((HttpServletRequest) req).getRequestURI().startsWith(WICKET_PAGES_PREFIX) == true) {
          // Access-checking is done by Wicket, not by this filter:
          request = decorateWithLocale(request, user);
          chain.doFilter(request, response);
        } else {
          response.getWriter().append("No access.");
        }
      }
    }
  } finally {
    PFUserContext.setUser(null);
    MDC.remove("ip");
    MDC.remove("session");
    if (user != null) {
      MDC.remove("user");
    }
    if (log.isDebugEnabled() == true) {
      log.debug("doFilter finished for " + request.getRequestURI() + ": " + request.getSession().getId());
    }
  }
}
 
Example 16
Source File: IteratedRequestActivationNode.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Activates the action requests that are pending at this routelevel of the document. The requests are processed by priority and then request ID.
 * It is implicit in the access that the requests are activated according to the route level above all.
 * <p>
 * FYI and acknowledgement requests do not cause the processing to stop. Only action requests for approval or completion cause the processing to
 * stop and then only for route level with a serialized activation policy. Only requests at the current document's current route level are activated.
 * Inactive requests at a lower level cause a routing exception.
 * <p>
 * Exception routing and adhoc routing are processed slightly differently.
 * 
 * 
 * @param context the RouteContext
 * @param document the document we are processing
 * @param nodeInstance the node instance we are processing
 * @return True if the any blocking actions requests (approve or complete) were activated.
 * @throws org.kuali.rice.kew.api.exception.ResourceUnavailableException
 * @throws org.kuali.rice.kew.api.exception.WorkflowException
 */
private boolean activateRequests(RouteContext context, DocumentRouteHeaderValue document, RouteNodeInstance nodeInstance) throws WorkflowException {
    MDC.put("docId", document.getDocumentId());
    PerformanceLogger performanceLogger = new PerformanceLogger(document.getDocumentId());
    List generatedActionItems = new ArrayList();
    List<ActionRequestValue> requests = KEWServiceLocator.getActionRequestService().findPendingRootRequestsByDocIdAtRouteNode(document.getDocumentId(), nodeInstance.getRouteNodeInstanceId());
    if (context.isSimulation()) {
        requests.addAll(context.getEngineState().getGeneratedRequests());
    }
    // this will sort higher priority requests to the front
    // blocking requests are higher priority, so all blocking requests will be
    // activated before non-blocking requests
    Collections.sort(requests, new Utilities.PrioritySorter());
    LOG.info("Pending Root Requests " + requests.size());
    String activationType = nodeInstance.getRouteNode().getActivationType();
    boolean isParallel = KewApiConstants.ROUTE_LEVEL_PARALLEL.equals(activationType);
    boolean activatedApproveRequest = false;
    for (Iterator iter = requests.iterator(); iter.hasNext();) {
        if (activatedApproveRequest && !isParallel) {
            LOG.info("Already activated an apprve request and serial, so not activating any more");
            break;
        }
        ActionRequestValue request = (ActionRequestValue) iter.next();
        LOG.info("ActionRequestValue: " + request);
        if (request.getParentActionRequest() != null || request.getNodeInstance() == null) {
            // 1. disregard request if it's not a top-level request
            // 2. disregard request if it's a "future" request and hasn't been attached to a node instance yet
            continue; 
        }
        if (request.isActive()) {
            activatedApproveRequest = activatedApproveRequest || request.isApproveOrCompleteRequest();
            continue;
        }
        logProcessingMessage(request);   
        LOG.info("Activating request. " + request);
        activatedApproveRequest = activateRequest(context, request, nodeInstance, generatedActionItems) || activatedApproveRequest;
    }
    // now let's send notifications, since this code needs to be able to activate each request individually, we need
    // to collection all action items and then notify after all have been generated
    if (!context.isSimulation()) {
        KEWServiceLocator.getNotificationService().notify(generatedActionItems);
    }
    performanceLogger.log("Time to activate requests.");
    return activatedApproveRequest;
}
 
Example 17
Source File: ApproveAction.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * Records the approve action.
 * - Checks to make sure the document status allows the action.
 * - Checks that the user has not taken a previous action.
 * - Deactivates the pending requests for this user
 * - Records the action
 *
 * @throws InvalidActionTakenException
 * @throws org.kuali.rice.kew.api.exception.ResourceUnavailableException
 */
public void recordAction() throws InvalidActionTakenException {
    MDC.put("docId", getRouteHeader().getDocumentId());
    updateSearchableAttributesIfPossible();
    LOG.debug("Approving document : " + annotation);

    List actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_APPROVE_REQ);
    if (actionRequests == null || actionRequests.isEmpty()) {
        DocumentTypePolicy allowUnrequested = getRouteHeader().getDocumentType().getAllowUnrequestedActionPolicy();
        if (allowUnrequested != null) {
        	if (!allowUnrequested.getPolicyValue()) {
        		throw new InvalidActionTakenException("No request for the user is compatible " + "with the APPROVE action. " + "Doctype policy ALLOW_UNREQUESTED_ACTION is set to false and someone else likely just took action on the document.");
        	}
        }
    }
    String errorMessage = validateActionRules(actionRequests);
    if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) {
        throw new InvalidActionTakenException(errorMessage);
    }

    Recipient delegator = findDelegatorForActionRequests(actionRequests);

    LOG.debug("Record the approve action");
    ActionTakenValue actionTaken = saveActionTaken(delegator);

    LOG.debug("Deactivate all pending action requests");
    getActionRequestService().deactivateRequests(actionTaken, actionRequests);
    notifyActionTaken(actionTaken);

    boolean isException = getRouteHeader().isInException();
    boolean isSaved = getRouteHeader().isStateSaved();
    if (isException || isSaved) {
        String oldStatus = getRouteHeader().getDocRouteStatus();
        LOG.debug("Moving document back to Enroute from "+KewApiConstants.DOCUMENT_STATUSES.get(oldStatus));
        getRouteHeader().markDocumentEnroute();
        String newStatus = getRouteHeader().getDocRouteStatus();
        notifyStatusChange(newStatus, oldStatus);
        DocumentRouteHeaderValue routeHeaderValue = KEWServiceLocator.getRouteHeaderService().
                                        saveRouteHeader(getRouteHeader());
        setRouteHeader(routeHeaderValue);
    }
}
 
Example 18
Source File: Log4JRunnable.java    From tutorials with MIT License 3 votes vote down vote up
public void run() {

        MDC.put("transaction.id", tx.getTransactionId());
        MDC.put("transaction.owner", tx.getSender());

        log4jBusinessService.transfer(tx.getAmount());

        MDC.clear();

    }
 
Example 19
Source File: LogAOP.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 3 votes vote down vote up
private void putLogInfo2MDC(ProceedingJoinPoint pjp) {
    // 得到方法上的注解
    MethodSignature signature = (MethodSignature) pjp.getSignature();

    Log logAnnotation = signature.getMethod().getAnnotation(Log.class);


    SPELUtil spel = new SPELUtil(pjp);

    JSONObject json = new JSONObject();

    // 使用单字母而不是全名,是为了节省日志文件大小。

    // 用户
    User user = UserUtil.getUserIfLogin();

    if (user != null) {
        json.put("U", user.getName());
    }

    // 操作
    json.put("A", logAnnotation.action());

    // 对象类型
    json.put("T", logAnnotation.itemType());

    // 对象id,spel表达式
    json.put("I", spel.cacl(logAnnotation.itemId()));

    // 其他参数,spel表达式
    json.put("P", spel.cacl(logAnnotation.param()));

    MDC.put(JSON_KEY, json.toJSONString());
}
 
Example 20
Source File: ASTEvalHelper.java    From database with GNU General Public License v2.0 2 votes vote down vote up
private static void setupLoggingContext(final IEvaluationContext context) {

        MDC.put("tx", TimestampUtility.toString(context.getTimestamp()));

    }