• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java MDCUtil类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.icthh.xm.commons.logging.util.MDCUtil的典型用法代码示例。如果您正苦于以下问题:Java MDCUtil类的具体用法?Java MDCUtil怎么用?Java MDCUtil使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MDCUtil类属于com.icthh.xm.commons.logging.util包,在下文中一共展示了MDCUtil类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: createSystemEvent

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
private String createSystemEvent(String tenant, String command) {
    SystemEvent event = new SystemEvent();
    event.setEventId(MDCUtil.getRid());
    event.setEventType(command);
    event.setTenantInfo(TenantContext.getCurrent());
    event.setMessageSource(appName);
    event.getData().put(Constants.EVENT_TENANT, tenant);
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    try {
        return mapper.writeValueAsString(event);
    } catch (JsonProcessingException e) {
        log.error("System Event mapping error", e);
        throw new BusinessException("Event mapping error", e.getMessage());
    }

}
 
开发者ID:xm-online,项目名称:xm-ms-timeline,代码行数:18,代码来源:KafkaService.java


示例2: registerAccount

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * POST /register : register the user.
 *
 * @param user the managed user View Model
 * @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad
 *         Request) if the login is already in use
 */
@PostMapping(path = "/register",
    produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
@Timed
public ResponseEntity registerAccount(@Valid @RequestBody ManagedUserVM user, HttpServletRequest request) {
    if (user.getEmail() == null) {
        throw new BusinessException("Email can't be empty");
    }
    user.getLogins().forEach(
        userLogin -> userLoginRepository.findOneByLoginIgnoreCase(userLogin.getLogin()).ifPresent(s -> {
            throw new BusinessException(LOGIN_IS_USED_ERROR_TEXT);
        }));
    if (captchaService.isCaptchaNeed(request.getRemoteAddr())) {
        captchaService.checkCaptcha(user.getCaptcha());
    }
    User newUser = accountService.register(user, request.getRemoteAddr());
    produceEvent(new UserDTO(newUser), Constants.CREATE_PROFILE_EVENT_TYPE);
    mailService.sendActivationEmail(
        newUser, TenantContext.getCurrent().getTenant(), TenantUtil.getApplicationUrl(), MDCUtil.getRid());
    return new ResponseEntity<>(HttpStatus.CREATED);
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:28,代码来源:AccountResource.java


示例3: createUser

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * POST /users : Creates a new user.
 *
 * <p>Creates a new user if the login and email are not already used, and sends an mail with an
 * activation link. The user needs to be activated on creation.
 * @param user the user to create
 * @return the ResponseEntity with status 201 (Created) and with body the new user, or with
 *         status 400 (Bad Request) if the login or email is already in use
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity createUser(@Valid @RequestBody UserDTO user) throws URISyntaxException {
    if (user.getId() != null) {
        return ResponseEntity.badRequest()
            .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new user cannot already have an ID"))
            .body(null);
    }
    user.getLogins().forEach(userLogin ->
        userLoginRepository.findOneByLoginIgnoreCase(userLogin.getLogin())
            .ifPresent(s -> {
                throw new BusinessException(Constants.LOGIN_IS_USED_ERROR_TEXT);
            })
    );
    User newUser = userService.createUser(user);
    produceEvent(new UserDTO(newUser), Constants.CREATE_PROFILE_EVENT_TYPE);
    mailService.sendCreationEmail(newUser, TenantUtil.getApplicationUrl(),
        TenantContext.getCurrent().getTenant(), MDCUtil.getRid());
    return ResponseEntity.created(new URI("/api/users/" + newUser.getUserKey()))
        .headers(HeaderUtil.createAlert("userManagement.created", newUser.getUserKey()))
        .body(new UserDTO(newUser));
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:34,代码来源:UserResource.java


示例4: createEventJson

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Build message for kafka's event.
 * @param user user data for kafka's event content
 * @param eventType event type for kafka's event content
 */
public String createEventJson(UserDTO user, String eventType) {
    try {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("eventId", MDCUtil.getRid());
        map.put("messageSource", appName);
        map.put("tenantInfo", TenantContext.getCurrent());
        map.put("eventType", eventType);
        map.put("startDate", Instant.now().toString());
        map.put("data", user);
        return mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        log.warn("Error creating profile event", e);
    }
    return null;
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:21,代码来源:ProfileEventProducer.java


示例5: testSendActivationEmail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Test
public void testSendActivationEmail() throws Exception {
    User user = new User();
    user.setLangKey("en");
    UserLogin userLogin = new UserLogin();
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin("[email protected]");
    user.getLogins().add(userLogin);
    mailService.sendActivationEmail(user, TENANT_NAME, URL, MDCUtil.getRid());
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo(EMAIL_FROM);
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:17,代码来源:MailServiceIntTest.java


示例6: testCreationEmail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Test
public void testCreationEmail() throws Exception {
    UserLogin userLogin = new UserLogin();
    userLogin.setTypeKey(UserLoginType.EMAIL.getValue());
    userLogin.setLogin("[email protected]");

    User user = new User();
    user.setFirstName("john");
    user.setUserKey("test");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.getLogins().add(userLogin);
    userLogin.setUser(user);

    mailService.sendCreationEmail(user, URL, TENANT_NAME, MDCUtil.getRid());
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo(EMAIL_FROM);
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:23,代码来源:MailServiceIntTest.java


示例7: testPutRid

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Test
public void testPutRid() {
    assertNull(MDCUtil.getRid());
    MDCUtil.put("key", "value");
    assertEquals("value", MDC.get("key"));

    assertNull(MDCUtil.getRid());

    MDCUtil.putRid("myRid");
    assertEquals("myRid", MDCUtil.getRid());
    assertEquals("myRid", MDC.get("rid"));

    MDCUtil.clear();

    assertNull(MDCUtil.getRid());
    assertNull(MDC.get("key"));
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:18,代码来源:MDCUtilTest.java


示例8: createEventJson

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Build message content for kafka's event.
 * @param profile data for kafka message content
 * @param eventType event type for kafka message content
 * @return event content
 */
public String createEventJson(Profile profile, String eventType) {
    try {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("eventId", MDCUtil.getRid());
        map.put("messageSource", appName);
        map.put("tenantInfo", TenantContext.getCurrent());
        map.put("eventType", eventType);
        map.put("startDate", Instant.now().toString());
        map.put("data", buildDataContent(profile));
        return mapper.writeValueAsString(map);
    } catch (JsonProcessingException e) {
        log.warn("Error creating profile event", e);
    }
    return null;
}
 
开发者ID:xm-online,项目名称:xm-ms-entity,代码行数:22,代码来源:ProfileEventProducer.java


示例9: main

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Main method, used to run the application.
 *
 * @param args the command line arguments
 * @throws UnknownHostException if the local host name could not be resolved into an address
 */
public static void main(String[] args) throws UnknownHostException {

    MDCUtil.put();

    SpringApplication app = new SpringApplication(UaaApp.class);
    DefaultProfileUtil.addDefaultProfile(app);
    Environment env = app.run(args).getEnvironment();
    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
        protocol = "https";
    }
    log.info("\n----------------------------------------------------------\n\t" +
            "Application '{}' is running! Access URLs:\n\t" +
            "Local: \t\t{}://localhost:{}\n\t" +
            "External: \t{}://{}:{}\n\t" +
            "Profile(s): \t{}\n----------------------------------------------------------",
        env.getProperty("spring.application.name"),
        protocol,
        env.getProperty("server.port"),
        protocol,
        InetAddress.getLocalHost().getHostAddress(),
        env.getProperty("server.port"),
        env.getActiveProfiles());

    String configServerStatus = env.getProperty("configserver.status");
    log.info("\n----------------------------------------------------------\n\t" +
            "Config Server: \t{}\n----------------------------------------------------------",
        configServerStatus == null ? "Not found or not setup for this application" : configServerStatus);
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:36,代码来源:UaaApp.java


示例10: requestPasswordReset

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * POST /account/reset_password/init : Send an email to reset the password of the user.
 *
 * @param mail the mail of the user
 * @return the ResponseEntity with status 200 (OK) if the email was sent, or status 400 (Bad
 *         Request) if the email address is not registered
 */
@PostMapping(path = "/account/reset_password/init",
    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Timed
public ResponseEntity requestPasswordReset(@RequestBody String mail) {
    return userService.requestPasswordReset(mail)
        .map(user -> {
            String rid = MDCUtil.getRid();
            mailService.sendPasswordResetMail(user, TenantUtil.getApplicationUrl(),
                TenantContext.getCurrent().getTenant(), rid);
            return new ResponseEntity<>("email was sent", HttpStatus.OK);
        }).orElseThrow(() -> new BusinessException("email address not registered"));
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:20,代码来源:AccountResource.java


示例11: consumeEvent

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Consume tenant command event message.
 * @param message the tenant command event message
 */
@Retryable(maxAttemptsExpression = "${application.retry.max-attempts}",
    backoff = @Backoff(delayExpression = "${application.retry.delay}",
        multiplierExpression = "${application.retry.multiplier}"))
public void consumeEvent(ConsumerRecord<String, String> message) {
    MDCUtil.put();
    try {
        log.info("Input message {}", message);
        ObjectMapper mapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.registerModule(new JavaTimeModule());
        try {
            SystemEvent event = mapper.readValue(message.value(), SystemEvent.class);
            String command = event.getEventType();
            String userKey = String.valueOf(event.getData().get(Constants.USER_KEY));
            TenantContext.setCurrent(event.getTenantInfo());
            if (Constants.UPDATE_ACCOUNT_EVENT_TYPE.equalsIgnoreCase(command)) {
                log.info("Start to update account for userKey='{}'", userKey);
                User user = userService.getUser(userKey);
                if (user == null) {
                    log.error("Failed to update account. User with userKey='{}' does not exists.", userKey);
                } else {
                    SystemEventMapper.toUser(event, user);
                    userService.saveUser(user);
                }
            }
        } catch (IOException e) {
            log.error("Kafka message has incorrect format ", e);
        }
    } finally {
        MDCUtil.remove();
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:37,代码来源:SystemQueueConsumer.java


示例12: consumeEvent

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Consume tenant command event message.
 * @param message the tenant command event message
 */
@Retryable(maxAttemptsExpression = "${application.retry.max-attempts}",
    backoff = @Backoff(delayExpression = "${application.retry.delay}",
        multiplierExpression = "${application.retry.multiplier}"))
public void consumeEvent(ConsumerRecord<String, String> message) {
    MDCUtil.put();
    try {
        log.info("Input message {}", message);

    } finally {
        MDCUtil.remove();
    }
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:17,代码来源:SystemTopicConsumer.java


示例13: sendActivationEmail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Send activation email.
 */
@Async
public void sendActivationEmail(User user, String tenant, String url, String rid) {
    MDCUtil.putRid(rid);
    String email = user.getEmail();
    log.info("Sending activation email to {}", email);

    sendEmailFromTemplate(user,
        "activationEmail",
        "email.activation.title",
        generateFrom(tenant),
        email, url, tenant);
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:16,代码来源:MailService.java


示例14: sendCreationEmail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Async
public void sendCreationEmail(User user, String url, String tenantName, String rid) {
    MDCUtil.putRid(rid);
    log.info("Sending creation email to '{}'", user.getEmail());
    sendEmailFromTemplate(
        user,
        "creationEmail",
        "email.activation.title",
        generateFrom(tenantName),
        user.getEmail(),
        url,
        tenantName
    );
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:15,代码来源:MailService.java


示例15: sendPasswordResetMail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Send password reset email.
 *
 * @param user object which stores info about user
 * @param url application url
 * @param tenantName tenant name
 * @param rid transaction id (use for logging)
 */
@Async
public void sendPasswordResetMail(User user, String url, String tenantName, String rid) {
    MDCUtil.putRid(rid);
    log.info("Sending password reset email to '{}'", user.getEmail());
    sendEmailFromTemplate(
        user,
        "passwordResetEmail",
        "email.reset.title",
        generateFrom(tenantName),
        user.getEmail(),
        url,
        tenantName
    );
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:23,代码来源:MailService.java


示例16: sendSocialRegistrationValidationEmail

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Send social registration validation email.
 */
@Async
public void sendSocialRegistrationValidationEmail(User user, String email, String provider, String tenantName, String rid) {
    MDCUtil.putRid(rid);
    log.info("Sending social registration validation email to {}", email);
    Locale locale = Locale.forLanguageTag(user.getLangKey());
    Context context = new Context(locale);
    context.setVariable(USER, user);
    context.setVariable("provider", StringUtils.capitalize(provider));
    String content = templateEngine.process("socialRegistrationValidationEmail", context);
    String subject = messageSource.getMessage("email.social.registration.title", null, locale);
    sendEmail(email, subject, content, generateFrom(tenantName));
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:16,代码来源:MailService.java


示例17: createSocialUser

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
/**
 * Create new user.
 * @param connection connection
 * @param langKey lang key
 */
public void createSocialUser(Connection<?> connection, String langKey) {
    if (connection == null) {
        log.error("Cannot create social user because connection is null");
        throw new IllegalArgumentException("Connection cannot be null");
    }
    UserProfile userProfile = connection.fetchUserProfile();
    String providerId = connection.getKey().getProviderId();
    String imageUrl = connection.getImageUrl();
    User user = createUserIfNotExist(userProfile, langKey, imageUrl);
    createSocialConnection(user.getUserKey(), connection);
    mailService.sendSocialRegistrationValidationEmail(user, userProfile.getEmail(), providerId,
        TenantContext.getCurrent().getTenant(), MDCUtil.getRid());
}
 
开发者ID:xm-online,项目名称:xm-uaa,代码行数:19,代码来源:SocialService.java


示例18: testGenerateRid

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Test
public void testGenerateRid() {
    System.out.println(MDCUtil.generateRid());
    assertNotNull(MDCUtil.generateRid());
    assertEquals(MDCUtil.generateRid().length(), RID_LEN);
    assertTrue(StringUtils.isAsciiPrintable(MDCUtil.generateRid()));
}
 
开发者ID:xm-online,项目名称:xm-ms-dashboard,代码行数:8,代码来源:MDCUtilTest.java


示例19: testGenerateRidUniqness

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Test
@Ignore("Run manually due to fail probability and long run time")
public void testGenerateRidUniqness() {

    int cardinality = 10000000;

    Set<String> rids = new HashSet<>(cardinality);

    for (int i = 0; i < cardinality; i++) {
        rids.add(MDCUtil.generateRid());
    }

    assertEquals(cardinality, rids.size());
}
 
开发者ID:xm-online,项目名称:xm-ms-dashboard,代码行数:15,代码来源:MDCUtilTest.java


示例20: doFilter

import com.icthh.xm.commons.logging.util.MDCUtil; //导入依赖的package包/类
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {

    StopWatch stopWatch = StopWatch.createStarted();

    String domain = request.getServerName();
    String remoteAddr = request.getRemoteAddr();
    Long contentLength = request.getContentLengthLong();

    String tenant = tenantMappingService != null ? tenantMappingService.getTenants().get(domain) : null;

    String method = null;
    String userLogin = null;
    String requestUri = null;

    try {

        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = HttpServletRequest.class.cast(request);
            method = req.getMethod();
            userLogin = req.getRemoteUser();
            requestUri = req.getRequestURI();
        }

        MDCUtil.putRid(MDCUtil.generateRid() + ":" + userLogin + ":" + tenant);

        log.info("START {}/{} --> {} {}, contentLength = {} ", remoteAddr, domain, method, requestUri,
                 contentLength);

        chain.doFilter(request, response);

        Integer status = null;

        if (response instanceof HttpServletResponse) {
            HttpServletResponse res = HttpServletResponse.class.cast(response);
            status = res.getStatus();
        }

        log.info("STOP  {}/{} --> {} {}, status = {}, time = {} ms", remoteAddr, domain, method, requestUri,
                 status, stopWatch.getTime());

    } catch (Exception e) {
        log.error("STOP  {}/{} --> {} {}, error = {}, time = {} ms", remoteAddr, domain, method, requestUri,
                  LogObjectPrinter.printException(e), stopWatch.getTime());
        throw e;
    } finally {
        MDCUtil.clear();
    }

}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:52,代码来源:LoggingFilter.java



注:本文中的com.icthh.xm.commons.logging.util.MDCUtil类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java CSObjectNotFoundException类代码示例发布时间:2022-05-23
下一篇:
Java PauseOnScrollListener类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap