protected void importMBDiscussion(CalEvent calEvent, long calendarBookingId)
      throws PortalException, SystemException {

    MBDiscussion mbDiscussion =
        mbDiscussionPersistence.fetchByC_C(
            classNameLocalService.getClassNameId(CalEvent.class), calEvent.getEventId());

    if (mbDiscussion == null) {
      return;
    }

    long threadId = importMBThread(mbDiscussion.getThreadId(), calendarBookingId);

    addMBDiscussion(
        PortalUUIDUtil.generate(),
        counterLocalService.increment(),
        mbDiscussion.getGroupId(),
        mbDiscussion.getCompanyId(),
        mbDiscussion.getUserId(),
        mbDiscussion.getUserName(),
        mbDiscussion.getCreateDate(),
        mbDiscussion.getModifiedDate(),
        classNameLocalService.getClassNameId(CalendarBooking.class.getName()),
        calendarBookingId,
        threadId);
  }
  public MDRRuleGroup copyRuleGroup(
      MDRRuleGroup ruleGroup, long groupId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    Group group = groupPersistence.findByPrimaryKey(groupId);

    Map<Locale, String> nameMap = ruleGroup.getNameMap();

    for (Map.Entry<Locale, String> entry : nameMap.entrySet()) {
      Locale locale = entry.getKey();
      String name = entry.getValue();

      if (Validator.isNull(name)) {
        continue;
      }

      String postfix =
          LanguageUtil.get(locale, PropsValues.MOBILE_DEVICE_RULES_RULE_GROUP_COPY_POSTFIX);

      nameMap.put(locale, name.concat(StringPool.SPACE).concat(postfix));
    }

    MDRRuleGroup newRuleGroup =
        addRuleGroup(group.getGroupId(), nameMap, ruleGroup.getDescriptionMap(), serviceContext);

    List<MDRRule> rules = mdrRulePersistence.findByRuleGroupId(ruleGroup.getRuleGroupId());

    for (MDRRule rule : rules) {
      serviceContext.setUuid(PortalUUIDUtil.generate());

      mdrRuleLocalService.copyRule(rule, newRuleGroup.getRuleGroupId(), serviceContext);
    }

    return newRuleGroup;
  }
  @Override
  public Ticket addTicket(
      long companyId,
      String className,
      long classPK,
      int type,
      String extraInfo,
      Date expirationDate,
      ServiceContext serviceContext) {

    long classNameId = classNameLocalService.getClassNameId(className);

    long ticketId = counterLocalService.increment();

    Ticket ticket = ticketPersistence.create(ticketId);

    ticket.setCompanyId(companyId);
    ticket.setCreateDate(new Date());
    ticket.setClassNameId(classNameId);
    ticket.setClassPK(classPK);
    ticket.setKey(PortalUUIDUtil.generate());
    ticket.setType(type);
    ticket.setExtraInfo(extraInfo);
    ticket.setExpirationDate(expirationDate);

    ticketPersistence.update(ticket);

    return ticket;
  }
  protected void initLocalClusterNode() {
    InetAddress inetAddress = getBindInetAddress(_controlJChannel);

    ClusterNode clusterNode = new ClusterNode(PortalUUIDUtil.generate(), inetAddress);

    if (Validator.isNull(PropsValues.PORTAL_INSTANCE_PROTOCOL)) {
      _localClusterNode = clusterNode;

      return;
    }

    if (Validator.isNull(PropsValues.PORTAL_INSTANCE_INET_SOCKET_ADDRESS)) {
      throw new IllegalArgumentException(
          "Portal instance host name and port needs to be set in the "
              + "property \"portal.instance.inet.socket.address\"");
    }

    String[] parts =
        StringUtil.split(PropsValues.PORTAL_INSTANCE_INET_SOCKET_ADDRESS, CharPool.COLON);

    if (parts.length != 2) {
      throw new IllegalArgumentException(
          "Unable to parse the portal instance host name and port from "
              + PropsValues.PORTAL_INSTANCE_INET_SOCKET_ADDRESS);
    }

    InetAddress hostInetAddress = null;

    try {
      hostInetAddress = InetAddress.getByName(parts[0]);
    } catch (UnknownHostException uhe) {
      throw new IllegalArgumentException(
          "Unable to parse the portal instance host name and port from "
              + PropsValues.PORTAL_INSTANCE_INET_SOCKET_ADDRESS,
          uhe);
    }

    int port = -1;

    try {
      port = GetterUtil.getIntegerStrict(parts[1]);
    } catch (NumberFormatException nfe) {
      throw new IllegalArgumentException(
          "Unable to parse portal InetSocketAddress port from "
              + PropsValues.PORTAL_INSTANCE_INET_SOCKET_ADDRESS,
          nfe);
    }

    clusterNode.setPortalInetSocketAddress(new InetSocketAddress(hostInetAddress, port));

    clusterNode.setPortalProtocol(PropsValues.PORTAL_INSTANCE_PROTOCOL);

    _localClusterNode = clusterNode;
  }
  protected long importMBMessage(
      MBMessage mbMessage, long threadId, long calendarBookingId, Map<Long, Long> mbMessageIds)
      throws PortalException, SystemException {

    Long messageId = mbMessageIds.get(mbMessage.getMessageId());

    if (messageId != null) {
      return messageId;
    }

    messageId = counterLocalService.increment();

    addMBMessage(
        PortalUUIDUtil.generate(),
        messageId,
        mbMessage.getGroupId(),
        mbMessage.getCompanyId(),
        mbMessage.getUserId(),
        mbMessage.getUserName(),
        mbMessage.getCreateDate(),
        mbMessage.getModifiedDate(),
        classNameLocalService.getClassNameId(CalendarBooking.class.getName()),
        calendarBookingId,
        mbMessage.getCategoryId(),
        threadId,
        mbMessage.getRootMessageId(),
        mbMessage.getParentMessageId(),
        mbMessage.getSubject(),
        mbMessage.getBody(),
        mbMessage.getFormat(),
        mbMessage.isAnonymous(),
        mbMessage.getPriority(),
        mbMessage.getAllowPingbacks(),
        mbMessage.isAnswer(),
        mbMessage.getStatus(),
        mbMessage.getStatusByUserId(),
        mbMessage.getStatusByUserName(),
        mbMessage.getStatusDate(),
        mbMessageIds);

    long mbDiscussionClassNameId =
        classNameLocalService.getClassNameId(MBDiscussion.class.getName());

    importRatings(
        mbDiscussionClassNameId, mbMessage.getMessageId(), mbDiscussionClassNameId, messageId);

    mbMessageIds.put(mbMessage.getMessageId(), messageId);

    return messageId;
  }
  public MemberRequest addMemberRequest(
      long userId,
      long groupId,
      long receiverUserId,
      String receiverEmailAddress,
      long invitedRoleId,
      long invitedTeamId,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Member request

    User user = userLocalService.getUserById(userId);

    Date now = new Date();

    long memberRequestId = counterLocalService.increment();

    MemberRequest memberRequest = memberRequestPersistence.create(memberRequestId);

    memberRequest.setGroupId(groupId);
    memberRequest.setCompanyId(user.getCompanyId());
    memberRequest.setUserId(userId);
    memberRequest.setUserName(user.getFullName());
    memberRequest.setCreateDate(now);
    memberRequest.setModifiedDate(now);
    memberRequest.setKey(PortalUUIDUtil.generate());
    memberRequest.setReceiverUserId(receiverUserId);
    memberRequest.setInvitedRoleId(invitedRoleId);
    memberRequest.setInvitedTeamId(invitedTeamId);
    memberRequest.setStatus(InviteMembersConstants.STATUS_PENDING);

    memberRequestPersistence.update(memberRequest, false);

    // Email

    try {
      sendEmail(receiverEmailAddress, memberRequest, serviceContext);
    } catch (Exception e) {
      throw new SystemException(e);
    }

    // Notifications

    sendNotificationEvent(memberRequest);

    return memberRequest;
  }
  public void afterPropertiesSet() {
    String jobName = _className;

    if (_className.length() > SchedulerEngine.JOB_NAME_MAX_LENGTH) {
      jobName = _className.substring(0, SchedulerEngine.JOB_NAME_MAX_LENGTH);
    }

    String groupName = _className;

    if (_className.length() > SchedulerEngine.GROUP_NAME_MAX_LENGTH) {
      groupName = _className.substring(0, SchedulerEngine.GROUP_NAME_MAX_LENGTH);
    }

    _key = jobName.concat(StringPool.PERIOD).concat(groupName);

    if (_messageListenerUUID == null) {
      _messageListenerUUID = PortalUUIDUtil.generate();
    }
  }
  protected File getFileItemTempFile(HttpServletRequest request) throws Exception {

    FileItem fileItem = getFileItem(request);

    if (fileItem == null) {
      return null;
    }

    File tempDir =
        new File(SystemProperties.get(SystemProperties.TMP_DIR), PortalUUIDUtil.generate());

    if (!tempDir.mkdirs()) {
      return null;
    }

    File tempFile = new File(tempDir, fileItem.getName());

    fileItem.write(tempFile);

    return tempFile;
  }
  protected long importMBThread(MBThread mbThread, long calendarBookingId)
      throws PortalException, SystemException {

    long threadId = counterLocalService.increment();

    addMBThread(
        PortalUUIDUtil.generate(),
        threadId,
        mbThread.getGroupId(),
        mbThread.getCompanyId(),
        mbThread.getUserId(),
        mbThread.getUserName(),
        mbThread.getCreateDate(),
        mbThread.getModifiedDate(),
        mbThread.getCategoryId(),
        0,
        mbThread.getRootMessageUserId(),
        mbThread.getMessageCount(),
        mbThread.getViewCount(),
        mbThread.getLastPostByUserId(),
        mbThread.getLastPostDate(),
        mbThread.getPriority(),
        mbThread.isQuestion(),
        mbThread.getStatus(),
        mbThread.getStatusByUserId(),
        mbThread.getStatusByUserName(),
        mbThread.getStatusDate());

    Map<Long, Long> mbMessageIds = new HashMap<Long, Long>();

    List<MBMessage> mbMessages = mbMessagePersistence.findByThreadId(mbThread.getThreadId());

    for (MBMessage mbMessage : mbMessages) {
      importMBMessage(mbMessage, threadId, calendarBookingId, mbMessageIds);
    }

    updateMBThreadRootMessageId(threadId, mbMessageIds.get(mbThread.getRootMessageId()));

    return threadId;
  }
  public DLFileEntryType addFileEntryType(
      long userId,
      long groupId,
      String name,
      String description,
      long[] ddmStructureIds,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(userId);

    String fileEntryTypeUuid = serviceContext.getUuid();

    if (Validator.isNull(fileEntryTypeUuid)) {
      fileEntryTypeUuid = PortalUUIDUtil.generate();
    }

    long fileEntryTypeId = counterLocalService.increment();

    long ddmStructureId =
        updateDDMStructure(
            userId, fileEntryTypeUuid, fileEntryTypeId, groupId, name, description, serviceContext);

    if (ddmStructureId > 0) {
      ddmStructureIds = ArrayUtil.append(ddmStructureIds, ddmStructureId);
    }

    Date now = new Date();

    validate(fileEntryTypeId, groupId, name, ddmStructureIds);

    DLFileEntryType dlFileEntryType = dlFileEntryTypePersistence.create(fileEntryTypeId);

    dlFileEntryType.setUuid(fileEntryTypeUuid);
    dlFileEntryType.setGroupId(groupId);
    dlFileEntryType.setCompanyId(user.getCompanyId());
    dlFileEntryType.setUserId(user.getUserId());
    dlFileEntryType.setUserName(user.getFullName());
    dlFileEntryType.setCreateDate(serviceContext.getCreateDate(now));
    dlFileEntryType.setModifiedDate(serviceContext.getModifiedDate(now));
    dlFileEntryType.setName(name);
    dlFileEntryType.setDescription(description);

    dlFileEntryTypePersistence.update(dlFileEntryType);

    dlFileEntryTypePersistence.addDDMStructures(fileEntryTypeId, ddmStructureIds);

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions());
    } else {
      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions());
    }

    return dlFileEntryType;
  }
  @Override
  public DLFileEntryType addFileEntryType(
      long userId,
      long groupId,
      String fileEntryTypeKey,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      long[] ddmStructureIds,
      ServiceContext serviceContext)
      throws PortalException {

    User user = userPersistence.findByPrimaryKey(userId);

    if (Validator.isNull(fileEntryTypeKey)) {
      fileEntryTypeKey = String.valueOf(counterLocalService.increment());
    } else {
      fileEntryTypeKey = StringUtil.toUpperCase(fileEntryTypeKey.trim());
    }

    String fileEntryTypeUuid = serviceContext.getUuid();

    if (Validator.isNull(fileEntryTypeUuid)) {
      fileEntryTypeUuid = PortalUUIDUtil.generate();
    }

    long fileEntryTypeId = counterLocalService.increment();

    long ddmStructureId =
        updateDDMStructure(
            userId,
            fileEntryTypeUuid,
            fileEntryTypeId,
            groupId,
            nameMap,
            descriptionMap,
            serviceContext);

    if (ddmStructureId > 0) {
      ddmStructureIds = ArrayUtil.append(ddmStructureIds, ddmStructureId);
    }

    validate(fileEntryTypeId, groupId, fileEntryTypeKey, ddmStructureIds);

    DLFileEntryType dlFileEntryType = dlFileEntryTypePersistence.create(fileEntryTypeId);

    dlFileEntryType.setUuid(fileEntryTypeUuid);
    dlFileEntryType.setGroupId(groupId);
    dlFileEntryType.setCompanyId(user.getCompanyId());
    dlFileEntryType.setUserId(user.getUserId());
    dlFileEntryType.setUserName(user.getFullName());
    dlFileEntryType.setFileEntryTypeKey(fileEntryTypeKey);
    dlFileEntryType.setNameMap(nameMap);
    dlFileEntryType.setDescriptionMap(descriptionMap);

    dlFileEntryTypePersistence.update(dlFileEntryType);

    addDDMStructureLinks(fileEntryTypeId, SetUtil.fromArray(ddmStructureIds));

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions());
    } else {
      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions());
    }

    return dlFileEntryType;
  }