コード例 #1
1
 /**
  * Make url for the event of the calendar application. Format of the url is:
  *
  * <ul>
  *   <li>/[portal]/[space]/[calendar]/[username]/invitation/detail/[event id]/[calendar type]
  * </ul>
  *
  * The format is used to utilize the invitation email feature implemented before. <br>
  * <strong>[NOTE]</strong> Keep in mind that this function calls {@link PortalRequestContext}
  * which is in webui layer while this function is usually invoked in the service layer. Need to be
  * improved in the future for ensuring the system design convention.
  *
  * @param event have to be not null
  * @return empty string if the process is failed.
  */
 private String makeEventLink(CalendarEvent event) {
   StringBuffer sb = new StringBuffer("");
   PortalRequestContext requestContext = Util.getPortalRequestContext();
   sb.append(requestContext.getPortalURI())
       .append(requestContext.getNodePath())
       .append(INVITATION_DETAIL)
       .append(ConversationState.getCurrent().getIdentity().getUserId())
       .append("/")
       .append(event.getId())
       .append("/")
       .append(event.getCalType());
   return sb.toString();
 }
コード例 #2
1
  /**
   * publish a new event activity
   *
   * @param event
   * @param calendarId
   * @param eventType
   */
  private void publishActivity(CalendarEvent event, String calendarId, String eventType) {
    try {
      Class.forName("org.exoplatform.social.core.space.spi.SpaceService");
    } catch (ClassNotFoundException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("eXo Social components not found!", e);
      }
      return;
    }
    if (calendarId == null
        || calendarId.indexOf(CalendarDataInitialize.SPACE_CALENDAR_ID_SUFFIX) < 0) {
      return;
    }
    try {
      IdentityManager identityM =
          (IdentityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(IdentityManager.class);
      ActivityManager activityM =
          (ActivityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(ActivityManager.class);
      SpaceService spaceService =
          (SpaceService)
              PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class);

      String spaceGroupId = Utils.getSpaceGroupIdFromCalendarId(calendarId);
      Space space = spaceService.getSpaceByGroupId(spaceGroupId);
      if (space != null) {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        Identity spaceIdentity =
            identityM.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName(), false);
        Identity userIdentity =
            identityM.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
        ExoSocialActivity activity = new ExoSocialActivityImpl();
        activity.setUserId(userIdentity.getId());
        activity.setTitle(event.getSummary());
        activity.setBody(event.getDescription());
        activity.setType("cs-calendar:spaces");
        activity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
        activityM.saveActivityNoReturn(spaceIdentity, activity);
        event.setActivityId(activity.getId());
      }
    } catch (ExoSocialException e) {
      if (LOG.isDebugEnabled()) LOG.error("Can not record Activity for space when event added ", e);
    }
  }
コード例 #3
0
  private ChromatticSession safeGet() throws IllegalStateException {
    if (effective == null) {
      if (builder == null) {
        throw new IllegalStateException("Chromattic session proxy is currently not associated");
      }

      //
      ConversationState cs = ConversationState.getCurrent();
      String userId = cs.getIdentity().getUserId();
      String rootNodePath = provider.rootNodePath + userId;
      String rootNodeType = provider.rootNodeType;

      //
      ChromatticBuilder.Configuration config =
          new ChromatticBuilder.Configuration(builder.getConfiguration());
      config.setOptionValue(ChromatticBuilder.ROOT_NODE_PATH, rootNodePath, true);
      if (rootNodeType != null) {
        config.setOptionValue(ChromatticBuilder.ROOT_NODE_TYPE, rootNodeType, true);
      }
      Chromattic chromattic = builder.build(config);

      //
      effective = chromattic.openSession();
      current.set(this);
    }
    return effective;
  }
コード例 #4
0
  /**
   * Gets the current user's spaces and pending spaces.
   *
   * @param uriInfo The requested URI information.
   * @param portalName The name of the current container.
   * @param format The format of the returned result.
   * @anchor SpacesRestService.showMySpaceList
   * @return response
   * @throws Exception @LevelAPI Platform
   * @deprecated Deprecated from 4.3.x. Replaced by a new API {@link
   *     UserRestResourcesV1#getSpacesOfUser(org.exoplatform.social.rest.impl.user.UriInfo, String,
   *     int, int, boolean, String)}
   */
  @GET
  @Path("mySpaces/show.{format}")
  public Response showMySpaceList(
      @Context UriInfo uriInfo,
      @PathParam("portalName") String portalName,
      @PathParam("format") String format)
      throws Exception {
    MediaType mediaType = Util.getMediaType(format);
    ConversationState state = ConversationState.getCurrent();
    portalContainerName = portalName;

    String userId = null;
    if (state != null) {
      userId = state.getIdentity().getUserId();
    }

    Identity identity =
        getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
    if (identity == null) {
      userId = Util.getViewerId(uriInfo);
    }

    SpaceList mySpaceList = showMySpaceList(userId);

    this.fillUrlAllSpaces(mySpaceList, portalName);
    return Util.getResponse(mySpaceList, uriInfo, mediaType, Response.Status.OK);
  }
コード例 #5
0
ファイル: Utils.java プロジェクト: hanhvq/integration
  public static ExoSocialActivity createActivity(
      IdentityManager identityManager,
      String activityOwnerId,
      Node node,
      String activityMsgBundleKey,
      String activityType,
      boolean isSystemComment,
      String systemComment)
      throws Exception {
    // Populate activity data
    Map<String, String> activityParams =
        populateActivityData(
            node, activityOwnerId, activityMsgBundleKey, isSystemComment, systemComment);

    String title =
        node.hasProperty(NodetypeConstant.EXO_TITLE)
            ? node.getProperty(NodetypeConstant.EXO_TITLE).getString()
            : org.exoplatform.ecm.webui.utils.Utils.getTitle(node);
    ExoSocialActivity activity = new ExoSocialActivityImpl();
    String userId = "";
    if (ConversationState.getCurrent() != null) {
      userId = ConversationState.getCurrent().getIdentity().getUserId();
    } else {
      userId = activityOwnerId;
    }
    Identity identity =
        identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
    activity.setUserId(identity.getId());
    activity.setType(activityType);
    activity.setUrl(node.getPath());
    activity.setTitle(title);
    activity.setTemplateParams(activityParams);
    return activity;
  }
コード例 #6
0
 public static final String[] getUserGroups(String username) throws Exception {
   ConversationState conversationState = ConversationState.getCurrent();
   Identity identity = conversationState.getIdentity();
   Set<String> objs = identity.getGroups();
   String[] groups = new String[objs.size()];
   int i = 0;
   for (String obj : objs) {
     groups[i++] = obj;
   }
   return groups;
 }
コード例 #7
0
  private Identity getIdentity() {
    ConversationState conv = ConversationState.getCurrent();
    if (conv == null) {
      return guest;
    }

    Identity id = conv.getIdentity();
    if (id == null) {
      return guest;
    }

    return id;
  }
コード例 #8
0
ファイル: FAQUtils.java プロジェクト: phuonglm/forum
 public static User getCurrentUserObject() throws Exception {
   try {
     ConversationState state = ConversationState.getCurrent();
     User user = (User) state.getAttribute(CacheUserProfileFilter.USER_PROFILE);
     if (user == null) {
       user =
           UserHelper.getOrganizationService().getUserHandler().findUserByName(getCurrentUser());
     }
     return user;
   } catch (Exception e) {
     return null;
   }
 }
コード例 #9
0
ファイル: Utils.java プロジェクト: hanhvq/integration
 /**
  * get activity owner
  *
  * @return activity owner
  */
 private static String getActivityOwnerId(Node node) {
   String activityOwnerId = "";
   ConversationState conversationState = ConversationState.getCurrent();
   if (conversationState != null) {
     activityOwnerId = conversationState.getIdentity().getUserId();
   } else {
     try {
       activityOwnerId = node.getProperty("publication:lastUser").getString();
     } catch (Exception e) {
       LOG.info("No lastUser publication");
     }
   }
   return activityOwnerId;
 }
コード例 #10
0
 public void setUp() throws Exception {
   begin();
   ConversationState conversionState = ConversationState.getCurrent();
   if (conversionState == null) {
     conversionState = new ConversationState(new Identity(USER_ROOT));
     ConversationState.setCurrent(conversionState);
   }
   PortalContainer portalContainer = (PortalContainer) ExoContainerContext.getCurrentContainer();
   resourceBinder =
       (ResourceBinder) portalContainer.getComponentInstanceOfType(ResourceBinder.class);
   // resourceBinder = (ResourceBinder) getService(ResourceBinder.class);
   // requestHandler = (RequestHandlerImpl)
   // portalContainer.getComponentInstanceOfType(RequestHandlerImpl.class);
   requestHandler = (RequestHandlerImpl) getService(RequestHandlerImpl.class);
 }
コード例 #11
0
ファイル: GadgetConnector.java プロジェクト: rdenarie/ecms
  /**
   * Creates the file element.
   *
   * @param document the document
   * @param applicationCategory the application category
   * @return the element
   * @throws Exception the exception
   */
  private Element createFileElement(
      Document document, ApplicationCategory applicationCategory, String host) throws Exception {
    Element files = document.createElement("Files");
    List<Application> listApplication =
        applicationRegistryService.getApplications(applicationCategory, ApplicationType.GADGET);
    for (Application application : listApplication) {
      Gadget gadget = gadgetRegistryService.getGadget(application.getApplicationName());
      Element file = document.createElement("File");
      file.setAttribute("name", gadget.getName());
      file.setAttribute("fileType", "nt_unstructured");
      file.setAttribute("size", "0");
      file.setAttribute("thumbnail", gadget.getThumbnail());
      file.setAttribute("description", gadget.getDescription());

      String fullurl = "";
      if (gadget.isLocal()) {
        fullurl = "/" + PortalContainer.getCurrentRestContextName() + "/" + gadget.getUrl();
      } else {
        fullurl = gadget.getUrl();
      }
      file.setAttribute("url", fullurl);

      String data =
          "{\"context\":{\"country\":\"US\",\"language\":\"en\"},\"gadgets\":[{\"moduleId\":0,\"url\":\""
              + fullurl
              + "\",\"prefs\":[]}]}";
      URL url = new URL(host + "/eXoGadgetServer/gadgets/metadata");
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
      wr.write(data);
      wr.flush();
      String strMetadata = IOUtils.toString(conn.getInputStream(), "UTF-8");
      wr.close();
      JSONObject metadata = new JSONObject(strMetadata.toString());

      ConversationState conversationState = ConversationState.getCurrent();
      String userId = conversationState.getIdentity().getUserId();
      String token =
          createToken(gadget.getUrl(), userId, userId, new Random().nextLong(), "default");
      JSONObject obj = metadata.getJSONArray("gadgets").getJSONObject(0);
      obj.put("secureToken", token);

      file.setAttribute("metadata", metadata.toString());
      files.appendChild(file);
    }
    return files;
  }
コード例 #12
0
    @Override
    public void execute(Event<UIMeetingDetail> event) throws Exception {
      UIMeetingDetail detail = event.getSource();
      UIApplication uiApp = event.getRequestContext().getUIApplication();
      if (detail.selectedOptions.isEmpty()) {
        uiApp.addMessage(
            new ApplicationMessage(
                "You need to select at least one option",
                new Object[0],
                AbstractApplicationMessage.ERROR));
        return;
      }

      Identity identity = ConversationState.getCurrent().getIdentity();
      if (!identity.getUserId().equals(detail.getMeeting().getOwner())) {
        uiApp.addMessage(
            new ApplicationMessage(
                "Only owner can make plan for this meeting",
                new Object[0],
                AbstractApplicationMessage.ERROR));
        return;
      }

      MeetingService service = detail.getApplicationComponent(MeetingService.class);
      Meeting m =
          service.finalMeeting(detail.meeting, new ArrayList<String>(detail.selectedOptions));
      detail.setMeeting(m);
    }
コード例 #13
0
  /**
   * Provides a way to get the latest spaces ordered by last access and to be able to filter spaces,
   * based on the application Id in the spaces.
   *
   * @param uriInfo The requested URI information.
   * @param portalName The portal container name.
   * @param format The format of the returned result, for example, JSON, or XML.
   * @param offset Specifies the staring point of the returned results. It must be greater than or
   *     equal to 0.
   * @param limit Specifies the ending point of the returned results. It must be less than or equal
   *     to 10.
   * @param appId The application Id which is contained in spaces to filter, such as, Wiki,
   *     Discussion, Documents, Agenda and more.
   * @authentication
   * @request GET:
   *     http://localhost:8080/rest/private/social/spaces/lastVisitedSpace/list.json?appId=Wiki&offset=0&limit=10
   * @response { "spaces":[
   *     {"groupId":"/spaces/space_2","spaceUrl":null,"name":"space_2","displayName":"space
   *     2","url":"space_2"},
   *     {"groupId":"/spaces/space_1","spaceUrl":null,"name":"space_1","displayName":"space
   *     1","url":"space_1"} ], "moreSpacesUrl":null }
   * @return the response @LevelAPI Platform
   * @anchor SpacesRestService.getLastVisitedSpace
   */
  @GET
  @Path("lastVisitedSpace/list.{format}")
  public Response getLastVisitedSpace(
      @Context UriInfo uriInfo,
      @PathParam("portalName") String portalName,
      @PathParam("format") String format,
      @QueryParam("appId") String appId,
      @QueryParam("offset") int offset,
      @QueryParam("limit") int limit)
      throws Exception {
    checkAuthenticatedRequest();

    MediaType mediaType = Util.getMediaType(format, new String[] {format});
    ConversationState state = ConversationState.getCurrent();
    portalContainerName = portalName;

    String userId = null;
    if (state != null) {
      userId = state.getIdentity().getUserId();
    }

    Identity identity =
        getIdentityManager().getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);
    if (identity == null) {
      userId = Util.getViewerId(uriInfo);
    }

    //
    int newLimit = Math.min(limit, 100);
    int newOffset = 0;
    if (offset > 0) {
      newOffset = Math.min(offset, newLimit);
    } else {
      newOffset = 0;
    }

    //
    String newAppId = null;
    if (appId != null && appId.trim().length() > 0) {
      newAppId = appId;
    }

    SpaceList mySpaceList = getLastVisitedSpace(userId, newAppId, newOffset, newLimit);
    return Util.getResponse(mySpaceList, uriInfo, mediaType, Response.Status.OK);
  }
コード例 #14
0
 @Override
 public void execute(Event<UIMeetingDetail> event) throws Exception {
   String optionId = event.getRequestContext().getRequestParameter(OBJECTID);
   UIMeetingDetail detail = event.getSource();
   Identity identity = ConversationState.getCurrent().getIdentity();
   boolean isVoted = detail.meeting.isVotedOption(identity.getUserId(), optionId);
   MeetingService service = detail.getApplicationComponent(MeetingService.class);
   Map<String, String> voted = new HashMap<String, String>();
   voted.put(optionId, isVoted ? "0" : "1");
   Meeting meeting1 = service.updateVote(detail.meeting, identity.getUserId(), voted);
   detail.setMeeting(meeting1);
 }
コード例 #15
0
  /**
   * @param group
   * @return
   */
  public boolean isUserInGroup(String group) {
    ConversationState conv = ConversationState.getCurrent();
    Identity id = null;
    if (conv != null) {
      id = conv.getIdentity();
    }

    if (id == null) {
      return false;
    }

    Iterator<String> iter = id.getGroups().iterator();

    while (iter.hasNext()) {
      if (iter.next().equals(group)) {
        return true;
      }
    }

    return false;
  }
コード例 #16
0
 private void loginUser(String userId, boolean hasPing) {
   Collection<MembershipEntry> membershipEntries = new ArrayList<MembershipEntry>();
   MembershipEntry membershipEntry = new MembershipEntry("/platform/administrators", "*");
   membershipEntries.add(membershipEntry);
   Identity identity = new Identity(userId, membershipEntries);
   ConversationState state = new ConversationState(identity);
   ConversationState.setCurrent(state);
   //
   if (hasPing) {
     userStateService.ping(userId);
   }
 }
コード例 #17
0
 private TimeZone getUserTimeZone() {
   try {
     String username = ConversationState.getCurrent().getIdentity().getUserId();
     CalendarService calService =
         (CalendarService)
             PortalContainer.getInstance().getComponentInstanceOfType(CalendarService.class);
     CalendarSetting setting = calService.getCalendarSetting(username);
     return TimeZone.getTimeZone(setting.getTimeZone());
   } catch (Exception e) {
     if (LOG.isDebugEnabled()) LOG.error("Can not get time zone from user setting ", e);
     return null;
   }
 }
コード例 #18
0
 /**
  * Gets a user's pending spaces.
  *
  * @param uriInfo The requested URI information.
  * @param portalName The portal container name.
  * @param format The format of the returned result, for example, JSON, or XML.
  * @anchor SpacesRestService.showPendingSpaceList
  * @return response
  * @throws Exception @LevelAPI Platform
  */
 @GET
 @Path("pendingSpaces/show.{format}")
 public Response showPendingSpaceList(
     @Context UriInfo uriInfo,
     @PathParam("portalName") String portalName,
     @PathParam("format") String format)
     throws Exception {
   MediaType mediaType = Util.getMediaType(format);
   String userId = ConversationState.getCurrent().getIdentity().getUserId();
   portalContainerName = portalName;
   if (!userId.equals(Util.getViewerId(uriInfo))) {
     return null;
   }
   SpaceList pendingSpaceList = showPendingSpaceList(userId);
   return Util.getResponse(pendingSpaceList, uriInfo, mediaType, Response.Status.OK);
 }
コード例 #19
0
 private void initDatas() {
   String str = "/:*.*";
   rand = new Random();
   Identity identity = ConversationState.getCurrent().getIdentity();
   currentUser = identity.getUserId();
   Set<String> set = new HashSet<String>(identity.getGroups());
   groupShare = new String[set.size() + 1];
   int i = 0;
   for (String string : set) {
     groupShare[i] = string + str;
     i++;
   }
   groupShare[i] = currentUser;
   set.add(currentUser);
   groups = set.toArray(new String[set.size()]);
 }
コード例 #20
0
ファイル: RESTRegistryTest.java プロジェクト: rdenarie/jcr
  @Override
  public void setUp() throws Exception {

    super.setUp();
    this.sessionProviderService =
        (ThreadLocalSessionProviderService)
            container.getComponentInstanceOfType(ThreadLocalSessionProviderService.class);
    sessionProviderService.setSessionProvider(
        null, new SessionProvider(ConversationState.getCurrent()));
    restRegService =
        (RESTRegistryService) container.getComponentInstanceOfType(RESTRegistryService.class);
    binder = (ResourceBinder) container.getComponentInstanceOfType(ResourceBinder.class);
    handler = (RequestHandler) container.getComponentInstanceOfType(RequestHandler.class);

    baseUri = new URI("http://localhost:8080/rest");
  }
コード例 #21
0
 @Override
 public void doPrepare(TestCase tc, JCRTestContext context) throws Exception {
   super.doPrepare(tc, context);
   container = StandaloneContainer.getInstance();
   registryService = (RegistryService) container.getComponentInstanceOfType(RegistryService.class);
   sessionProvider = new SessionProvider(ConversationState.getCurrent());
   // fill class field sumIterations with adequate number
   if ((tc.hasParam("japex.runIterations")) && (tc.getIntParam("japex.runIterations") > 0)) {
     sumIterations += tc.getIntParam("japex.runIterations");
   }
   if ((tc.hasParam("japex.warmupIterations")) && (tc.getIntParam("japex.warmupIterations") > 0)) {
     sumIterations += tc.getIntParam("japex.warmupIterations");
   }
   // create content. May be overridden in child class with stub method to
   // avoid any preparation.
   createContent(tc, context);
 }
コード例 #22
0
  /**
   * convert date to user date format using calendar setting
   *
   * @param date
   * @return
   */
  private String getDateFormattedAfterUserSetting(String date) {
    try {
      String userId = ConversationState.getCurrent().getIdentity().getUserId();
      calService_ =
          (CalendarService)
              PortalContainer.getInstance().getComponentInstance(CalendarService.class); // not null
      CalendarSetting calSetting = calService_.getCalendarSetting(userId); // not null
      WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();
      Locale locale = requestContext.getParentAppRequestContext().getLocale();
      DateFormat format = new SimpleDateFormat(calSetting.getDateFormat(), locale);

      /* recurrenceId to Date then re-convert it to user date format */
      DateFormat format1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
      Date eventDate = format1.parse(date);

      return format.format(eventDate);
    } catch (Exception e) {
      LOG.debug(e.getMessage());
    }
    return null;
  }
コード例 #23
0
  public void testPing() throws Exception {
    UserStateModel userModel =
        new UserStateModel(
            session.getUserID(), new Date().getTime(), UserStateService.DEFAULT_STATUS);
    userStateService.save(userModel);
    userStateService.ping(userModel.getUserId());

    assertTrue(
        userModel.getLastActivity()
            != userStateService.getUserState(session.getUserID()).getLastActivity());

    Calendar currentTime = new GregorianCalendar();
    Calendar time = (Calendar) currentTime.clone();
    time.add(Calendar.MINUTE, -10);
    userModel.setLastActivity(time.getTime().getTime());

    userStateService.save(userModel);
    userStateService.ping(userModel.getUserId());

    assertTrue(
        userModel.getLastActivity()
            != userStateService.getUserState(session.getUserID()).getLastActivity());

    //
    loginUser("mary", true);
    assertTrue(
        userStateService.getUserState("mary").getStatus().equals(UserStateService.DEFAULT_STATUS));
    //
    loginUser("demo", false);
    // get status of user Mary by current user Demo
    assertTrue(
        userStateService.getUserState("mary").getStatus().equals(UserStateService.DEFAULT_STATUS));
    // get status of user Demo by anonymous user
    ConversationState.setCurrent(null);
    assertNull(userStateService.getUserState("demo"));
  }
コード例 #24
0
  /**
   * Build the repeating summary, i.e: daily every 2 days, until 02/03/2011. <br>
   * The summary structure is defined in resource bundle, it contains some parameters and </br> will
   * be replaced by values from repeatEvent. <br>
   *
   * <p>There are 6 parameters: {count}, {until}, {interval}, {byDays}, {theDay}, {theNumber}.<br>
   * Some labels in resource bundle to define numbers (the first, the second, ...) which were used
   * in summary
   *
   * @param repeatEvent the repeating event
   * @return summary string about repeating event
   * @throws Exception
   */
  public String buildRepeatSummary(CalendarEvent repeatEvent) {
    if (repeatEvent == null) return "";
    String repeatType = repeatEvent.getRepeatType();
    if (CalendarEvent.RP_NOREPEAT.equals(repeatType) || repeatType == null) return "";

    try {
      String userId = ConversationState.getCurrent().getIdentity().getUserId();
      calService_ =
          (CalendarService)
              PortalContainer.getInstance().getComponentInstance(CalendarService.class);
      CalendarSetting calSetting = calService_.getCalendarSetting(userId);
      WebuiRequestContext requestContext = WebuiRequestContext.getCurrentInstance();

      Locale locale = requestContext.getParentAppRequestContext().getLocale();
      DateFormat format = new SimpleDateFormat(calSetting.getDateFormat(), locale);
      DateFormatSymbols symbols = new DateFormatSymbols(locale);
      String[] dayOfWeeks = symbols.getWeekdays();

      int interval = (int) repeatEvent.getRepeatInterval();
      int count = (int) repeatEvent.getRepeatCount();
      Date until = repeatEvent.getRepeatUntilDate();
      String endType = RP_END_NEVER;
      if (count > 0) endType = RP_END_AFTER;
      if (until != null) endType = RP_END_BYDATE;

      StringBuilder pattern = new StringBuilder("");
      if (repeatType.equals(CalendarEvent.RP_DAILY)) {
        if (interval == 1) {
          // pattern = "Daily";
          pattern.append(CalendarUIActivity.getUICalendarLabel("daily"));
        } else {
          // pattern = "Every {interval} days";
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-day"));
        }
        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Daily, {count} times";
          // pattern = "Every {interval} days, {count} times";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Daily, until {until}";
          // pattern = "Every {interval} days, until {until}";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()));
      }

      if (repeatType.equals(CalendarEvent.RP_WEEKLY)) {
        if (interval == 1) {
          // pattern = "Weekly on {byDays}";
          pattern.append(CalendarUIActivity.getUICalendarLabel("weekly"));
        } else {
          // pattern = "Every {interval} weeks on {byDays}";
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-week"));
        }
        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Weekly on {byDays}, {count} times";
          // pattern = "Every {interval} weeks on {byDays}, {count} times";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Weekly on {byDays}, until {until}";
          // pattern = "Every {interval} weeks on {byDays}, until {until}";
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String[] weeklyByDays = repeatEvent.getRepeatByDay();
        StringBuffer byDays = new StringBuffer();
        for (int i = 0; i < weeklyByDays.length; i++) {
          if (i == 0) {
            byDays.append(dayOfWeeks[convertToDayOfWeek(weeklyByDays[0])]);
          } else {
            byDays.append(", ");
            byDays.append(dayOfWeeks[convertToDayOfWeek(weeklyByDays[i])]);
          }
        }
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{byDays}", byDays.toString());
      }

      if (repeatType.equals(CalendarEvent.RP_MONTHLY)) {
        String monthlyType = RP_MONTHLY_BYMONTHDAY;
        if (repeatEvent.getRepeatByDay() != null && repeatEvent.getRepeatByDay().length > 0)
          monthlyType = RP_MONTHLY_BYDAY;

        if (interval == 1) {
          // pattern = "Monthly on"
          pattern.append(CalendarUIActivity.getUICalendarLabel("monthly"));
        } else {
          // pattern = "Every {interval} months on
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-month"));
        }

        if (monthlyType.equals(RP_MONTHLY_BYDAY)) {
          // pattern = "Monthly on {theNumber} {theDay}
          // pattern = "Every {interval} months on {theNumber} {theDay}
          pattern.append(" " + CalendarUIActivity.getUICalendarLabel("monthly-by-day"));
        } else {
          // pattern = "Monthly on day {theDay}
          // pattern = "Every {interval} months on day {theDay}
          pattern.append(" " + CalendarUIActivity.getUICalendarLabel("monthly-by-month-day"));
        }

        if (endType.equals(RP_END_AFTER)) {
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String theNumber = ""; // the first, the second, the third, ...
        String theDay =
            ""; // in monthly by day, it's Monday, Tuesday, ... (day of week), in monthly by
        // monthday, it's 1-31 (day of month)
        if (monthlyType.equals(RP_MONTHLY_BYDAY)) {
          java.util.Calendar temp = getCalendarInstanceBySetting(calSetting);
          temp.setTime(repeatEvent.getFromDateTime());
          int weekOfMonth = temp.get(java.util.Calendar.WEEK_OF_MONTH);
          java.util.Calendar temp2 = getCalendarInstanceBySetting(calSetting);
          temp2.setTime(temp.getTime());
          temp2.add(java.util.Calendar.DATE, 7);
          if (temp2.get(java.util.Calendar.MONTH) != temp.get(java.util.Calendar.MONTH))
            weekOfMonth = 5;
          int dayOfWeek = temp.get(java.util.Calendar.DAY_OF_WEEK);
          String[] weekOfMonths =
              new String[] {
                CalendarUIActivity.getUICalendarLabel("summary-the-first"),
                CalendarUIActivity.getUICalendarLabel("summary-the-second"),
                CalendarUIActivity.getUICalendarLabel("summary-the-third"),
                CalendarUIActivity.getUICalendarLabel("summary-the-fourth"),
                CalendarUIActivity.getUICalendarLabel("summary-the-last")
              };
          theNumber = weekOfMonths[weekOfMonth - 1];
          theDay = dayOfWeeks[dayOfWeek];
        } else {
          java.util.Calendar temp = getCalendarInstanceBySetting(calSetting);
          temp.setTime(repeatEvent.getFromDateTime());
          int dayOfMonth = temp.get(java.util.Calendar.DAY_OF_MONTH);
          theDay = String.valueOf(dayOfMonth);
        }
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{theDay}", theDay)
            .replace("{theNumber}", theNumber);
      }

      if (repeatType.equals(CalendarEvent.RP_YEARLY)) {
        if (interval == 1) {
          // pattern = "Yearly on {theDay}"
          pattern.append(CalendarUIActivity.getUICalendarLabel("yearly"));
        } else {
          // pattern = "Every {interval} years on {theDay}"
          pattern.append(CalendarUIActivity.getUICalendarLabel("every-year"));
        }

        if (endType.equals(RP_END_AFTER)) {
          // pattern = "Yearly on {theDay}, {count} times"
          // pattern = "Every {interval} years on {theDay}, {count} times"
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("count-times"));
        }
        if (endType.equals(RP_END_BYDATE)) {
          // pattern = "Yearly on {theDay}, until {until}"
          // pattern = "Every {interval} years on {theDay}, until {until}"
          pattern.append(", " + CalendarUIActivity.getUICalendarLabel("until"));
        }

        String theDay = format.format(repeatEvent.getFromDateTime()); //
        return new String(pattern)
            .replace("{interval}", String.valueOf(interval))
            .replace("{count}", String.valueOf(repeatEvent.getRepeatCount()))
            .replace(
                "{until}",
                repeatEvent.getRepeatUntilDate() == null
                    ? ""
                    : format.format(repeatEvent.getRepeatUntilDate()))
            .replace("{theDay}", theDay);
      }
    } catch (Exception e) {
      LOG.info(e.getLocalizedMessage());
    }
    return null;
  }
コード例 #25
0
 public static Identity getCurrentIdentity() throws Exception {
   return ConversationState.getCurrent().getIdentity();
 }
コード例 #26
0
  /**
   * adds comment to existing event activity
   *
   * @param event
   * @param calendarId
   * @param eventType
   * @param messagesParams
   */
  private void updateToActivity(
      CalendarEvent event,
      String calendarId,
      String eventType,
      Map<String, String> messagesParams) {
    try {
      Class.forName("org.exoplatform.social.core.space.spi.SpaceService");
    } catch (ClassNotFoundException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("eXo Social components not found!", e);
      }
      return;
    }
    if (calendarId == null
        || calendarId.indexOf(CalendarDataInitialize.SPACE_CALENDAR_ID_SUFFIX) < 0) {
      return;
    }
    try {
      IdentityManager identityM =
          (IdentityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(IdentityManager.class);
      ActivityManager activityM =
          (ActivityManager)
              PortalContainer.getInstance().getComponentInstanceOfType(ActivityManager.class);
      SpaceService spaceService =
          (SpaceService)
              PortalContainer.getInstance().getComponentInstanceOfType(SpaceService.class);

      String spaceGroupId = Utils.getSpaceGroupIdFromCalendarId(calendarId);
      Space space = spaceService.getSpaceByGroupId(spaceGroupId);
      if (space != null) {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        Identity spaceIdentity =
            identityM.getOrCreateIdentity(SpaceIdentityProvider.NAME, space.getPrettyName(), false);
        Identity userIdentity =
            identityM.getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false);

        ExoSocialActivity activity = null;

        if (event.getActivityId() != null) {
          activity = activityM.getActivity(event.getActivityId());
        }

        /*
         * if activity is still null, that means:
         * - activity was deleted
         * - or this event is a public event from plf 3.5, it has no activityId
         * In this case, we create new activity and add comments about the changes to the activity
         */
        if (activity == null) {

          // create activity
          ExoSocialActivity newActivity = new ExoSocialActivityImpl();
          newActivity.setUserId(userIdentity.getId());
          newActivity.setTitle(event.getSummary());
          newActivity.setBody(event.getDescription());
          newActivity.setType("cs-calendar:spaces");
          newActivity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
          activityM.saveActivityNoReturn(spaceIdentity, newActivity);

          // add comments
          ExoSocialActivity newComment = createComment(userIdentity.getId(), messagesParams);
          activityM.saveComment(newActivity, newComment);

          // update activity id for event
          event.setActivityId(newActivity.getId());
          LOG.info(
              String.format(
                  "[CALENDAR] successfully re-created activity for event: %s", event.getSummary()));
        } else {
          activity.setTitle(event.getSummary());
          activity.setBody(event.getDescription());
          activity.setTemplateParams(makeActivityParams(event, calendarId, eventType));
          activityM.updateActivity(activity);
          ExoSocialActivity newComment = createComment(userIdentity.getId(), messagesParams);
          activityM.saveComment(activity, newComment);
          LOG.info(
              String.format(
                  "[CALENDAR] successfully added comment to activity of event: %s",
                  event.getSummary()));
        }
      }
    } catch (ExoSocialException e) {
      if (LOG.isDebugEnabled())
        LOG.error("Can not update Activity for space when event modified ", e);
    }
  }
コード例 #27
0
ファイル: Utils.java プロジェクト: RandomStuffs22/ecms
 public static List<String> getGroups() throws Exception {
   ConversationState conversationState = ConversationState.getCurrent();
   Identity identity = conversationState.getIdentity();
   Set<String> groups = identity.getGroups();
   return new ArrayList<String>(groups);
 }