/**
  * delete the event activity
  *
  * @param event
  * @param calendarId
  * @param eventType
  */
 private void deleteActivity(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 {
     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 && event.getActivityId() != null) {
       activityM.deleteActivity(event.getActivityId());
     }
   } catch (ExoSocialException e) {
     if (LOG.isDebugEnabled())
       LOG.error("Can not delete Activity for space when event deleted ", e);
   }
 }
  /**
   * 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);
    }
  }
 @Override
 public void preSave(User user, boolean isNew) throws Exception {
   if (passwordEncrypter != null && user.getPassword() != null) {
     User persistedUser = organizationService.getUserHandler().findUserByName(user.getUserName());
     if (persistedUser == null || persistedUser.getPassword() == null) {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Encrypting password for a new user " + user.getUserName());
       }
       String encodedPassword =
           new String(passwordEncrypter.encrypt(user.getPassword().getBytes()));
       user.setPassword(encodedPassword);
     } else if (!user.getPassword().equals(persistedUser.getPassword())) {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Encrypting changed password for user " + user.getUserName());
       }
       String encodedPassword =
           new String(passwordEncrypter.encrypt(user.getPassword().getBytes()));
       user.setPassword(encodedPassword);
     } else {
       if (LOG.isDebugEnabled()) {
         LOG.debug("Nothing to encrypt for user " + user.getUserName() + ": password no changed.");
       }
     }
   }
 }
예제 #4
0
 protected void executeQuery(final Statement statement, final String sql) throws SQLException {
   try {
     long start = 0;
     if (LOG.isDebugEnabled()) {
       start = System.currentTimeMillis();
       LOG.debug("Execute script: \n[" + sql + "]");
     }
     SecurityHelper.doPrivilegedSQLExceptionAction(
         new PrivilegedExceptionAction<Object>() {
           public Object run() throws Exception {
             statement.executeUpdate(sql);
             return null;
           }
         });
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Script "
               + sql
               + " executed in "
               + ((System.currentTimeMillis() - start) / 1000d)
               + " sec");
     }
   } catch (SQLException e) {
     LOG.error("Query execution \"" + sql + "\" failed: " + JDBCUtils.getFullMessage(e), e);
     throw e;
   }
 }
예제 #5
0
  private void handleCookie(String set_cookie, boolean cookie2, RoRequest req, Response resp)
      throws ProtocolException {
    Cookie[] cookies;
    if (cookie2) cookies = Cookie2.parse(set_cookie, req);
    else cookies = Cookie.parse(set_cookie, req);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Received and parsed " + cookies.length + " cookies:");
      for (int idx = 0; idx < cookies.length; idx++)
        LOG.debug("Cookie " + idx + ": " + cookies[idx]);
    }

    Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext());
    synchronized (cookie_list) {
      for (int idx = 0; idx < cookies.length; idx++) {
        Cookie cookie = (Cookie) cookie_list.get(cookies[idx]);
        if (cookie != null && cookies[idx].hasExpired()) {
          if (LOG.isDebugEnabled())
            LOG.debug("Cookie has expired and is " + "being removed: " + cookie);

          cookie_list.remove(cookie); // expired, so remove
        } else if (!cookies[idx].hasExpired()) // new or replaced
        {
          if (cookie_handler == null || cookie_handler.acceptCookie(cookies[idx], req, resp))
            cookie_list.put(cookies[idx], cookies[idx]);
        }
      }
    }
  }
예제 #6
0
  /**
   * Execute script on database. Set auto commit mode if needed.
   *
   * @param scripts the scripts for execution
   * @throws SQLException
   */
  protected void execute(List<String> scripts) throws SQLException {
    SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

    // set needed auto commit mode
    boolean autoCommit = connection.getAutoCommit();
    if (autoCommit != this.autoCommit) {
      connection.setAutoCommit(this.autoCommit);
    }

    Statement st = connection.createStatement();
    try {
      for (String scr : scripts) {
        String sql = JDBCUtils.cleanWhitespaces(scr.trim());
        if (!sql.isEmpty()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Execute script: \n[" + sql + "]");
          }

          executeQuery(st, sql);
        }
      }
    } finally {
      try {
        st.close();
      } catch (SQLException e) {
        LOG.error("Can't close the Statement." + e.getMessage());
      }

      // restore previous auto commit mode
      if (autoCommit != this.autoCommit) {
        connection.setAutoCommit(autoCommit);
      }
    }
  }
예제 #7
0
 @Managed
 @ManagedDescription("Clean all templates in Composer")
 public void cleanTemplates() throws Exception {
   this.templatesFilter = null;
   getTemplatesSQLFilter();
   if (LOG.isDebugEnabled()) LOG.debug("WCMComposer templates have been cleaned !");
 }
예제 #8
0
  public AbstractPageList<ResultNode> searchPageContents(
      SessionProvider sessionProvider,
      QueryCriteria queryCriteria,
      int pageSize,
      boolean isSearchContent)
      throws Exception {
    ManageableRepository currentRepository = repositoryService.getCurrentRepository();
    Session session = sessionProvider.getSession("portal-system", currentRepository);
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    long startTime = System.currentTimeMillis();
    Query query = createSearchPageQuery(queryCriteria, queryManager);
    String suggestion = getSpellSuggestion(queryCriteria.getKeyword(), currentRepository);
    if (LOG.isDebugEnabled()) {
      LOG.debug("execute query: " + query.getStatement().toLowerCase());
    }
    AbstractPageList<ResultNode> pageList =
        PageListFactory.createPageList(
            query.getStatement(),
            session.getWorkspace().getName(),
            query.getLanguage(),
            true,
            new PageNodeFilter(),
            new PageDataCreator(),
            pageSize,
            0);

    long queryTime = System.currentTimeMillis() - startTime;
    pageList.setQueryTime(queryTime);
    pageList.setSpellSuggestion(suggestion);
    return pageList;
  }
예제 #9
0
 /** As getTemplatePath() but it will return value NULL in case of exception. */
 public String getTemplate() {
   try {
     return getTemplatePath();
   } catch (Exception e) {
     if (LOG.isDebugEnabled())
       LOG.debug("Catch an exception when getting template, return value NULL.\n Cause by: ", e);
     return null;
   }
 }
예제 #10
0
 public static boolean isUserExisted(OrganizationService orgSevice, String value) {
   try {
     return (!isEmpty(value) && orgSevice.getUserHandler().findUserByName(value) != null);
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug("Fail to check if user exist", e);
     }
     return false;
   }
 }
예제 #11
0
 // save a default view type for Calendar Setting when cannot get the view type
 private static void resetViewInSetting(CalendarSetting calendarSetting) {
   try {
     calendarSetting.setViewType(CalendarSetting.DAY_VIEW);
     getCalendarService().saveCalendarSetting(getCurrentUser(), calendarSetting);
     setCurrentCalendarSetting(calendarSetting);
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug("Cant save Calendar Setting", e);
     }
   }
 }
예제 #12
0
 public static String parseEmailAddress(String address) {
   try {
     InternetAddress[] iAdds = InternetAddress.parse(address, true);
     return iAdds[0].getAddress();
   } catch (AddressException e) {
     if (log.isDebugEnabled()) {
       log.debug("The mail address is not valid", e);
     }
     return null;
   }
 }
 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;
   }
 }
예제 #14
0
 public UISpaceSummaryInfoPortlet() throws Exception {
   iteratorAdministrators =
       createUIComponent(UIPageIterator.class, null, ITERATOR_ADMINISTRATORS_ID);
   addChild(iteratorAdministrators);
   SpaceService spaceService = getSpaceService();
   Space space = spaceService.getSpaceByUrl(SpaceUtils.getSpaceUrl());
   if (space != null) {
     isSpace = true;
   } else {
     if (LOG.isDebugEnabled()) {
       LOG.debug(
           "Can not add the portlet to this page navigation.\nSPACE_URL preference could not be set.");
     }
   }
 }
  @Override
  public void saveAnswer(String questionId, Answer[] answers, boolean isNew) {
    try {
      Class.forName("org.exoplatform.social.core.manager.IdentityManager");
      if (answers != null) {
        for (Answer a : answers) {
          saveAnswer(questionId, a, isNew);
        }
      }

    } catch (ClassNotFoundException e) {
      if (LOG.isDebugEnabled())
        LOG.debug("Please check the integrated project does the social deploy? " + e.getMessage());
    }
    // catch other type of exception in saveAnswer(String questionId, Answer answers, boolean isNew)
  }
 private boolean isAllDayEvent(CalendarEvent eventCalendar) {
   try {
     TimeZone tz = getUserTimeZone();
     Calendar cal1 = new GregorianCalendar(tz);
     Calendar cal2 = new GregorianCalendar(tz);
     cal1.setLenient(false);
     cal1.setTime(eventCalendar.getFromDateTime());
     // cal1.setTimeZone(tz);
     cal2.setLenient(false);
     cal2.setTime(eventCalendar.getToDateTime());
     // cal2.setTimeZone(tz);
     return (cal1.get(Calendar.HOUR_OF_DAY) == 0
         && cal1.get(Calendar.MINUTE) == 0
         && cal2.get(Calendar.HOUR_OF_DAY) == cal2.getActualMaximum(Calendar.HOUR_OF_DAY)
         && cal2.get(Calendar.MINUTE) == cal2.getActualMaximum(Calendar.MINUTE));
   } catch (Exception e) {
     if (LOG.isDebugEnabled()) LOG.error("Can not check all day event when event updated ", e);
   }
   return false;
 }
예제 #17
0
 /**
  * This function will change email address in 'from' field by address of mail service which is
  * configured as system property : <code>gatein.email.smtp.from</code> or <code>mail.from</code>.
  * <br>
  * That ensures that 'emailAddress' part of 'from' field in a message object is always the same
  * identity with authentication of smtp configuration.<br>
  * It's because of 2 reasons:
  * <li>we don't want notification message to show email address of user as sender. Instead, we use
  *     mail service of kernel.
  * <li>Almost authenticated smtp systems do not allow to separate email address in <code>from
  *     </code> field of message from smtp authentication</b> (for now, GMX, MS exchange deny,
  *     Gmail efforts to modify the such value)
  *
  * @param from
  * @return null if can not find suitable sender.
  */
 public static String makeNotificationSender(String from) {
   if (from == null) return null;
   Properties props = new Properties(System.getProperties());
   String mailAddr = props.getProperty(FROM_KEY);
   if (mailAddr == null || mailAddr.length() == 0) mailAddr = props.getProperty("mail.from");
   if (mailAddr != null) {
     try {
       return new InternetAddress(from + "<" + mailAddr + ">").toUnicodeString();
     } catch (AddressException e) {
       if (log.isDebugEnabled()) {
         log.debug(
             "value of 'gatein.email.smtp.from' or 'mail.from' in configuration file is not in format of mail address",
             e);
       }
       return null;
     }
   } else {
     return null;
   }
 }
예제 #18
0
 /**
  * @return return the JCR path of the mop:page nodes that have gtn:name (page's title) containing
  *     the given specified <code>keyword</code>
  * @throws Exception
  */
 private List<String> searchPageByTitle(String siteName, String keyword) throws Exception {
   SessionProvider sessionProvider = WCMCoreUtils.getSystemSessionProvider();
   ManageableRepository currentRepository = repositoryService.getCurrentRepository();
   Session session = sessionProvider.getSession("portal-system", currentRepository);
   QueryManager queryManager = session.getWorkspace().getQueryManager();
   QueryCriteria queryCriteria = new QueryCriteria();
   queryCriteria.setSiteName(siteName);
   queryCriteria.setKeyword(keyword);
   queryCriteria.setSearchWebpage(true);
   Query query = createSearchPageByTitleQuery(queryCriteria, queryManager);
   if (LOG.isDebugEnabled()) {
     LOG.debug("execute query: " + query.getStatement().toLowerCase());
   }
   List<String> pageList =
       PageListFactory.createPageList(
           query.getStatement(),
           session.getWorkspace().getName(),
           query.getLanguage(),
           true,
           new PageTitleDataCreator());
   return pageList;
 }
예제 #19
0
 public static String getDataSource(Attachment attach, DownloadService dservice) throws Exception {
   if (attach != null) {
     try {
       InputStream input = attach.getInputStream();
       byte[] imageBytes = null;
       if (input != null) {
         imageBytes = new byte[input.available()];
         input.read(imageBytes);
         ByteArrayInputStream byteImage = new ByteArrayInputStream(imageBytes);
         InputStreamDownloadResource dresource =
             new InputStreamDownloadResource(byteImage, attach.getMimeType());
         dresource.setDownloadName(attach.getName());
         return dservice.getDownloadLink(dservice.addDownloadResource(dresource));
       }
     } catch (PathNotFoundException ex) {
       if (log.isDebugEnabled()) {
         log.debug("The attachment has no data source", ex);
       }
       return null;
     }
   }
   return null;
 }
예제 #20
0
  /*
   * (non-Javadoc)
   * @see
   * org.exoplatform.services.wcm.search.SiteSearchService#searchSiteContents
   * (org.exoplatform.services.wcm.search.QueryCriteria,
   * org.exoplatform.services.jcr.ext.common.SessionProvider, int)
   */
  public AbstractPageList<ResultNode> searchSiteContents(
      SessionProvider sessionProvider,
      QueryCriteria queryCriteria,
      int pageSize,
      boolean isSearchContent)
      throws Exception {
    ManageableRepository currentRepository = repositoryService.getCurrentRepository();
    NodeLocation location = configurationService.getLivePortalsLocation();
    Session session = sessionProvider.getSession(location.getWorkspace(), currentRepository);
    if (queryCriteria.isSearchWebpage()) {
      session = sessionProvider.getSession("portal-system", WCMCoreUtils.getRepository());
    }
    QueryManager queryManager = session.getWorkspace().getQueryManager();
    long startTime = System.currentTimeMillis();
    Query query = createQuery(queryCriteria, queryManager);
    String suggestion = getSpellSuggestion(queryCriteria.getKeyword(), currentRepository);
    AbstractPageList<ResultNode> pageList = null;
    if (LOG.isDebugEnabled()) {
      LOG.debug("execute query: " + query.getStatement().toLowerCase());
    }
    pageList =
        PageListFactory.createPageList(
            query.getStatement(),
            session.getWorkspace().getName(),
            query.getLanguage(),
            IdentityConstants.SYSTEM.equals(session.getUserID()),
            new NodeFilter(isSearchContent, queryCriteria),
            new DataCreator(),
            pageSize,
            0,
            queryCriteria);

    long queryTime = System.currentTimeMillis() - startTime;
    pageList.setQueryTime(queryTime);
    pageList.setSpellSuggestion(suggestion);
    return pageList;
  }
예제 #21
0
  /** Invoked by the HTTPClient. */
  public int responsePhase2Handler(Response resp, Request req) throws IOException {
    /* handle various response status codes until satisfied */

    int sts = resp.getStatusCode();
    switch (sts) {
      case 302: // General (temporary) Redirection (handle like 303)

        /*
         * Note we only do this munging for POST and PUT. For GET it's not
         * necessary; for HEAD we probably want to do another HEAD. For all
         * others (i.e. methods from WebDAV, IPP, etc) it's somewhat unclear -
         * servers supporting those should really return a 307 or 303, but some
         * don't (guess who...), so we just don't touch those.
         */
        if (req.getMethod().equals("POST") || req.getMethod().equals("PUT")) {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Received status: " + sts + " " + resp.getReasonLine() + " - treating as 303");

          sts = 303;
        }

      case 301: // Moved Permanently
      case 303: // See Other (use GET)
      case 307: // Moved Temporarily (we mean it!)
        if (LOG.isDebugEnabled()) LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());

        // the spec says automatic redirection may only be done if
        // the second request is a HEAD or GET.
        if (!req.getMethod().equals("GET") && !req.getMethod().equals("HEAD") && sts != 303) {
          if (LOG.isDebugEnabled())
            LOG.debug("Not redirected because method is neither HEAD nor GET");

          if (sts == 301 && resp.getHeader("Location") != null)
            update_perm_redir_list(req, resLocHdr(resp.getHeader("Location"), req));

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

      case 305: // Use Proxy
      case 306: // Switch Proxy
        if (sts == 305 || sts == 306) {
          if (LOG.isDebugEnabled())
            LOG.debug("Handling status: " + sts + " " + resp.getReasonLine());
        }

        // Don't accept 305 from a proxy
        if (sts == 305 && req.getConnection().getProxyHost() != null) {
          if (LOG.isDebugEnabled()) LOG.debug("305 ignored because a proxy is already in use");

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }

        /*
         * the level is a primitive way of preventing infinite redirections.
         * RFC-2068 set the max to 5, but RFC-2616 has loosened this. Since some
         * sites (notably M$) need more levels, this is now set to the
         * (arbitrary) value of 15 (god only knows why they need to do even 5
         * redirections...).
         */
        if (level >= 15 || resp.getHeader("Location") == null) {
          if (LOG.isDebugEnabled()) {
            if (level >= 15) LOG.debug("Not redirected because of too many levels of redirection");
            else LOG.debug("Not redirected because no Location header was present");
          }

          resp.setEffectiveURI(lastURI);
          return RSP_CONTINUE;
        }
        level++;

        URI loc = resLocHdr(resp.getHeader("Location"), req);

        HTTPConnection mvd;
        String nres;
        new_con = false;

        if (sts == 305) {
          mvd =
              new HTTPConnection(
                  req.getConnection().getProtocol(),
                  req.getConnection().getHost(),
                  req.getConnection().getPort());
          mvd.setCurrentProxy(loc.getHost(), loc.getPort());
          mvd.setContext(req.getConnection().getContext());
          new_con = true;

          nres = req.getRequestURI();

          /*
           * There was some discussion about this, and especially Foteos
           * Macrides (Lynx) said a 305 should also imply a change to GET (for
           * security reasons) - see the thread starting at
           * http://www.ics.uci.edu/pub/ietf/http/hypermail/1997q4/0351.html
           * However, this is not in the latest draft, but since I agree with
           * Foteos we do it anyway...
           */
          req.setMethod("GET");
          req.setData(null);
          req.setStream(null);
        } else if (sts == 306) {
          // We'll have to wait for Josh to create a new spec here.
          return RSP_CONTINUE;
        } else {
          if (req.getConnection().isCompatibleWith(loc)) {
            mvd = req.getConnection();
            nres = loc.getPathAndQuery();
          } else {
            try {
              mvd = new HTTPConnection(loc);
              nres = loc.getPathAndQuery();
            } catch (ProtocolNotSuppException e) {
              if (req.getConnection().getProxyHost() == null
                  || !loc.getScheme().equalsIgnoreCase("ftp")) return RSP_CONTINUE;

              // We're using a proxy and the protocol is ftp -
              // maybe the proxy will also proxy ftp...
              mvd =
                  new HTTPConnection(
                      "http",
                      req.getConnection().getProxyHost(),
                      req.getConnection().getProxyPort());
              mvd.setCurrentProxy(null, 0);
              nres = loc.toExternalForm();
            }

            mvd.setContext(req.getConnection().getContext());
            new_con = true;
          }

          /*
           * copy query if present in old url but not in new url. This isn't
           * strictly conforming, but some scripts fail to propagate the query
           * properly to the Location header. See comment on line 126. String
           * oquery = Util.getQuery(req.getRequestURI()), nquery =
           * Util.getQuery(nres); if (nquery == null && oquery != null) nres +=
           * "?" + oquery;
           */

          if (sts == 303) {
            // 303 means "use GET"

            if (!req.getMethod().equals("HEAD")) req.setMethod("GET");
            req.setData(null);
            req.setStream(null);
          } else {
            // If they used an output stream then they'll have
            // to do the resend themselves
            if (req.getStream() != null) {
              if (!HTTPConnection.deferStreamed) {
                if (LOG.isDebugEnabled())
                  LOG.debug("Status " + sts + " not handled - request has an output stream");

                return RSP_CONTINUE;
              }

              saved_req = (Request) req.clone();
              deferred_redir_list.put(req.getStream(), this);
              req.getStream().reset();
              resp.setRetryRequest(true);
            }

            if (sts == 301) {
              // update permanent redirection list
              try {
                update_perm_redir_list(req, new URI(loc, nres));
              } catch (ParseException pe) {
                throw new Error(
                    "HTTPClient Internal Error: " + "unexpected exception '" + pe + "'", pe);
              }
            }
          }

          // Adjust Referer, if present
          NVPair[] hdrs = req.getHeaders();
          for (int idx = 0; idx < hdrs.length; idx++)
            if (hdrs[idx].getName().equalsIgnoreCase("Referer")) {
              HTTPConnection con = req.getConnection();
              hdrs[idx] = new NVPair("Referer", con + req.getRequestURI());
              break;
            }
        }

        req.setConnection(mvd);
        req.setRequestURI(nres);

        try {
          resp.getInputStream().close();
        } catch (IOException ioe) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + ioe.getMessage());
          }
        }

        if (sts != 305 && sts != 306) {
          try {
            lastURI = new URI(loc, nres);
          } catch (ParseException pe) {
            if (LOG.isTraceEnabled()) {
              LOG.trace("An exception occurred: " + pe.getMessage());
            }
          }

          if (LOG.isDebugEnabled())
            LOG.debug(
                "Request redirected to "
                    + lastURI.toExternalForm()
                    + " using method "
                    + req.getMethod());
        } else {
          if (LOG.isDebugEnabled())
            LOG.debug(
                "Resending request using "
                    + "proxy "
                    + mvd.getProxyHost()
                    + ":"
                    + mvd.getProxyPort());
        }

        if (req.getStream() != null) return RSP_CONTINUE;
        else if (new_con) return RSP_NEWCON_REQ;
        else return RSP_REQUEST;

      default:
        return RSP_CONTINUE;
    }
  }
예제 #22
0
  /** Invoked by the HTTPClient. */
  public int requestHandler(Request req, Response[] resp) {
    // First remove any Cookie headers we might have set for a previous
    // request

    NVPair[] hdrs = req.getHeaders();
    int length = hdrs.length;
    for (int idx = 0; idx < hdrs.length; idx++) {
      int beg = idx;
      while (idx < hdrs.length && hdrs[idx].getName().equalsIgnoreCase("Cookie")) idx++;

      if (idx - beg > 0) {
        length -= idx - beg;
        System.arraycopy(hdrs, idx, hdrs, beg, length - beg);
      }
    }
    if (length < hdrs.length) {
      hdrs = Util.resizeArray(hdrs, length);
      req.setHeaders(hdrs);
    }

    // Now set any new cookie headers

    Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext());
    if (cookie_list.size() == 0) return REQ_CONTINUE; // no need to create a lot of objects

    Vector names = new Vector();
    Vector lens = new Vector();
    int version = 0;

    synchronized (cookie_list) {
      Enumeration list = cookie_list.elements();
      Vector remove_list = null;

      while (list.hasMoreElements()) {
        Cookie cookie = (Cookie) list.nextElement();

        if (cookie.hasExpired()) {
          if (LOG.isDebugEnabled()) LOG.debug("Cookie has expired and is being removed: " + cookie);

          if (remove_list == null) remove_list = new Vector();
          remove_list.addElement(cookie);
          continue;
        }

        if (cookie.sendWith(req)
            && (cookie_handler == null || cookie_handler.sendCookie(cookie, req))) {
          int len = cookie.getPath().length();
          int idx;

          // insert in correct position
          for (idx = 0; idx < lens.size(); idx++)
            if (((Integer) lens.elementAt(idx)).intValue() < len) break;

          names.insertElementAt(cookie.toExternalForm(), idx);
          lens.insertElementAt(new Integer(len), idx);

          if (cookie instanceof Cookie2)
            version = Math.max(version, ((Cookie2) cookie).getVersion());
        }
      }

      // remove any marked cookies
      // Note: we can't do this during the enumeration!
      if (remove_list != null) {
        for (int idx = 0; idx < remove_list.size(); idx++)
          cookie_list.remove(remove_list.elementAt(idx));
      }
    }

    if (!names.isEmpty()) {
      StringBuffer value = new StringBuffer();

      if (version > 0) value.append("$Version=\"" + version + "\"; ");

      value.append((String) names.elementAt(0));
      for (int idx = 1; idx < names.size(); idx++) {
        value.append("; ");
        value.append((String) names.elementAt(idx));
      }
      hdrs = Util.resizeArray(hdrs, hdrs.length + 1);
      hdrs[hdrs.length - 1] = new NVPair("Cookie", value.toString());

      // add Cookie2 header if necessary
      if (version != 1) // we currently know about version 1 only
      {
        int idx;
        for (idx = 0; idx < hdrs.length; idx++)
          if (hdrs[idx].getName().equalsIgnoreCase("Cookie2")) break;
        if (idx == hdrs.length) {
          hdrs = Util.resizeArray(hdrs, hdrs.length + 1);
          hdrs[hdrs.length - 1] = new NVPair("Cookie2", "$Version=\"1\"");
        }
      }

      req.setHeaders(hdrs);

      if (LOG.isDebugEnabled()) LOG.debug("Sending cookies '" + value + "'");
    }

    return REQ_CONTINUE;
  }
예제 #23
0
  public Result getPaginatedContents(
      NodeLocation nodeLocation, HashMap<String, String> filters, SessionProvider sessionProvider)
      throws Exception {
    String path = nodeLocation.getPath();
    String workspace = nodeLocation.getWorkspace();

    String mode = filters.get(FILTER_MODE);
    String version = filters.get(FILTER_VERSION);
    String orderBy = filters.get(FILTER_ORDER_BY);
    String orderType = filters.get(FILTER_ORDER_TYPE);
    String visibility = filters.get(FILTER_VISIBILITY);
    long offset = (filters.get(FILTER_OFFSET) != null) ? new Long(filters.get(FILTER_OFFSET)) : 0;
    long totalSize = (filters.get(FILTER_TOTAL) != null) ? new Long(filters.get(FILTER_TOTAL)) : 0;

    String remoteUser = getRemoteUser();

    if (MODE_EDIT.equals(mode) && "publication:liveDate".equals(orderBy)) {
      orderBy = "exo:dateModified";
      filters.put(FILTER_ORDER_BY, orderBy);
    }
    if (MODE_LIVE.equals(mode) && "exo:title".equals(orderBy)) {
      orderBy = "exo:titlePublished " + orderType + ", exo:title";
      filters.put(FILTER_ORDER_BY, orderBy);
    }

    if (LOG.isDebugEnabled())
      LOG.debug(
          "##### " + path + ":" + version + ":" + remoteUser + ":" + orderBy + ":" + orderType);

    NodeIterator nodeIterator;
    if (totalSize == 0) {
      SessionProvider systemProvider = WCMCoreUtils.getSystemSessionProvider();
      nodeIterator = getViewableContents(workspace, path, filters, systemProvider, false);
      if (nodeIterator != null) {
        totalSize = nodeIterator.getSize();
      }
    }

    if (WCMComposer.VISIBILITY_PUBLIC.equals(visibility) && MODE_LIVE.equals(mode)) {
      sessionProvider =
          remoteUser == null
              ? aclSessionProviderService.getAnonymSessionProvider()
              : aclSessionProviderService.getACLSessionProvider(getAnyUserACL());
    }

    nodeIterator = getViewableContents(workspace, path, filters, sessionProvider, true);
    List<Node> nodes = new ArrayList<Node>();
    Node node = null, viewNode = null;
    if (nodeIterator != null) {
      while (nodeIterator.hasNext()) {
        node = nodeIterator.nextNode();
        viewNode = getViewableContent(node, filters);
        if (viewNode != null) {
          nodes.add(viewNode);
        }
      }
    }
    Result result = new Result(nodes, offset, totalSize, nodeLocation, filters);

    return result;
  }
예제 #24
0
  public List<Node> getContents(
      String workspace,
      String path,
      HashMap<String, String> filters,
      SessionProvider sessionProvider)
      throws Exception {
    String mode = filters.get(FILTER_MODE);
    String version = filters.get(FILTER_VERSION);
    String orderBy = filters.get(FILTER_ORDER_BY);
    String orderType = filters.get(FILTER_ORDER_TYPE);
    String visibility = filters.get(FILTER_VISIBILITY);
    String remoteUser = null;
    if (WCMComposer.VISIBILITY_PUBLIC.equals(visibility)) {
      remoteUser = "******";
    } else {
      remoteUser = getRemoteUser();
    }

    if (MODE_EDIT.equals(mode) && "publication:liveDate".equals(orderBy)) {
      orderBy = "exo:dateModified";
      filters.put(FILTER_ORDER_BY, orderBy);
    }
    if ("exo:title".equals(orderBy)) {
      if (MODE_LIVE.equals(mode)) {
        orderBy = "exo:titlePublished " + orderType + ", exo:title";
      }
      if ("exo:taxonomy".equals(this.getTypeFromPath(workspace, path, sessionProvider))) {
        orderBy = "exo:name " + orderType + ", " + orderBy;
      }
      filters.put(FILTER_ORDER_BY, orderBy);
    }

    List<Node> nodes = new ArrayList<Node>();
    try {
      if (WCMComposer.VISIBILITY_PUBLIC.equals(visibility)
          && MODE_LIVE.equals(mode)
          && remoteUser != null) {
        sessionProvider = aclSessionProviderService.getACLSessionProvider(getAnyUserACL());
      }
      if (LOG.isDebugEnabled())
        LOG.debug(
            "##### " + path + ":" + version + ":" + remoteUser + ":" + orderBy + ":" + orderType);
      NodeIterator nodeIterator =
          getViewableContents(workspace, path, filters, sessionProvider, false);

      Node node = null, viewNode = null;
      while (nodeIterator != null && nodeIterator.hasNext()) {
        node = nodeIterator.nextNode();
        viewNode = getViewableContent(node, filters);
        if (viewNode != null) {
          nodes.add(viewNode);
        }
      }
    } catch (Exception e) {
      if (LOG.isWarnEnabled()) {
        LOG.warn(e.getMessage());
      }
    }

    return nodes;
  }
예제 #25
0
 @Override
 public void execute(Event<UIWeekView> event) throws Exception {
   UIWeekView calendarview = event.getSource();
   String eventId = event.getRequestContext().getRequestParameter(OBJECTID);
   String calendarId = event.getRequestContext().getRequestParameter(eventId + CALENDARID);
   String calType = event.getRequestContext().getRequestParameter(eventId + CALTYPE);
   String startTime = event.getRequestContext().getRequestParameter(eventId + START_TIME);
   String finishTime = event.getRequestContext().getRequestParameter(eventId + FINISH_TIME);
   Boolean isOccur = false;
   if (!Utils.isEmpty(event.getRequestContext().getRequestParameter(eventId + ISOCCUR))) {
     isOccur =
         Boolean.parseBoolean(event.getRequestContext().getRequestParameter(eventId + ISOCCUR));
   }
   String recurId = null;
   if (isOccur) recurId = event.getRequestContext().getRequestParameter(eventId + RECURID);
   try {
     String username = CalendarUtils.getCurrentUser();
     CalendarEvent eventCalendar = null;
     if (isOccur && !Utils.isEmpty(recurId)) {
       eventCalendar = calendarview.getRecurrenceMap().get(eventId).get(recurId);
     } else {
       eventCalendar = calendarview.getDataMap().get(eventId);
     }
     if (eventCalendar != null) {
       CalendarService calendarService = CalendarUtils.getCalendarService();
       Calendar calBegin = calendarview.getInstanceTempCalendar();
       Calendar calEnd = calendarview.getInstanceTempCalendar();
       long unit = 15 * 60 * 1000;
       calBegin.setTimeInMillis((Long.parseLong(startTime) / unit) * unit);
       eventCalendar.setFromDateTime(calBegin.getTime());
       calEnd.setTimeInMillis((Long.parseLong(finishTime) / unit) * unit);
       eventCalendar.setToDateTime(calEnd.getTime());
       if (eventCalendar.getToDateTime().before(eventCalendar.getFromDateTime())) {
         return;
       }
       org.exoplatform.calendar.service.Calendar calendar = null;
       if (CalendarUtils.PRIVATE_TYPE.equals(calType)) {
         calendar = calendarService.getUserCalendar(username, calendarId);
       } else if (CalendarUtils.SHARED_TYPE.equals(calType)) {
         if (calendarService.getSharedCalendars(username, true) != null)
           calendar =
               calendarService.getSharedCalendars(username, true).getCalendarById(calendarId);
       } else if (CalendarUtils.PUBLIC_TYPE.equals(calType)) {
         calendar = calendarService.getGroupCalendar(calendarId);
       }
       if (calendar == null) {
         event
             .getRequestContext()
             .getUIApplication()
             .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
       } else {
         if ((CalendarUtils.SHARED_TYPE.equals(calType)
                 && !CalendarUtils.canEdit(
                     calendarview.getApplicationComponent(OrganizationService.class),
                     Utils.getEditPerUsers(calendar),
                     username))
             || (CalendarUtils.PUBLIC_TYPE.equals(calType)
                 && !CalendarUtils.canEdit(
                     calendarview.getApplicationComponent(OrganizationService.class),
                     calendar.getEditPermission(),
                     username))) {
           event
               .getRequestContext()
               .getUIApplication()
               .addMessage(
                   new ApplicationMessage(
                       "UICalendars.msg.have-no-permission-to-edit-event", null, 1));
           calendarview.refresh();
           event.getRequestContext().addUIComponentToUpdateByAjax(calendarview.getParent());
           return;
         }
         // if it's a 'virtual' occurrence
         if (isOccur && !Utils.isEmpty(recurId)) {
           List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
           listEvent.add(eventCalendar);
           calendarService.updateOccurrenceEvent(
               calendarId, calendarId, calType, calType, listEvent, username);
         } else {
           if (calType.equals(CalendarUtils.PRIVATE_TYPE)) {
             calendarService.saveUserEvent(username, calendarId, eventCalendar, false);
           } else if (calType.equals(CalendarUtils.SHARED_TYPE)) {
             calendarService.saveEventToSharedCalendar(
                 username, calendarId, eventCalendar, false);
           } else if (calType.equals(CalendarUtils.PUBLIC_TYPE)) {
             calendarService.savePublicEvent(calendarId, eventCalendar, false);
           }
         }
         calendarview.setLastUpdatedEventId(eventId);
         calendarview.refresh();
         UIMiniCalendar uiMiniCalendar =
             calendarview
                 .getAncestorOfType(UICalendarPortlet.class)
                 .findFirstComponentOfType(UIMiniCalendar.class);
         event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar);
         event.getRequestContext().addUIComponentToUpdateByAjax(calendarview.getParent());
       }
     }
   } catch (Exception e) {
     if (log.isDebugEnabled()) {
       log.debug("Fail to save the event to the calendar", e);
     }
     return;
   }
 }
예제 #26
0
    @Override
    public void execute(Event<UIWeekView> event) throws Exception {

      UIWeekView calendarview = event.getSource();
      UICalendarPortlet uiCalendarPortlet = calendarview.getAncestorOfType(UICalendarPortlet.class);
      String eventId = event.getRequestContext().getRequestParameter(OBJECTID);
      String calendarId = event.getRequestContext().getRequestParameter(eventId + CALENDARID);
      String calType = event.getRequestContext().getRequestParameter(eventId + CALTYPE);
      String startTime = event.getRequestContext().getRequestParameter(eventId + START_TIME);
      String finishTime = event.getRequestContext().getRequestParameter(eventId + FINISH_TIME);
      String currentDate = event.getRequestContext().getRequestParameter(eventId + CURRENT_DATE);

      Boolean isOccur = false;
      if (!Utils.isEmpty(event.getRequestContext().getRequestParameter(eventId + ISOCCUR))) {
        isOccur =
            Boolean.parseBoolean(event.getRequestContext().getRequestParameter(eventId + ISOCCUR));
      }
      String recurId = null;
      if (isOccur) recurId = event.getRequestContext().getRequestParameter(eventId + RECURID);

      String username = CalendarUtils.getCurrentUser();
      CalendarService calendarService = CalendarUtils.getCalendarService();

      CalendarEvent eventCalendar = calendarview.getDataMap().get(eventId);
      if (isOccur && !Utils.isEmpty(recurId)) {
        eventCalendar = calendarview.getRecurrenceMap().get(eventId).get(recurId);
      }

      if (eventCalendar != null) {
        CalendarService calService = CalendarUtils.getCalendarService();
        boolean isMove = false;
        try {
          org.exoplatform.calendar.service.Calendar calendar = null;
          if (eventCalendar.getCalType().equals(CalendarUtils.PRIVATE_TYPE)) {
            calendar = calService.getUserCalendar(username, calendarId);
          } else if (eventCalendar.getCalType().equals(CalendarUtils.SHARED_TYPE)) {
            if (calService.getSharedCalendars(username, true) != null)
              calendar = calService.getSharedCalendars(username, true).getCalendarById(calendarId);
          } else if (eventCalendar.getCalType().equals(CalendarUtils.PUBLIC_TYPE)) {
            calendar = calService.getGroupCalendar(calendarId);
          }
          if (calendar == null) {
            event
                .getRequestContext()
                .getUIApplication()
                .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
          } else {
            Calendar cal = calendarview.getInstanceTempCalendar();
            int hoursBg = (Integer.parseInt(startTime) / 60);
            int minutesBg = (Integer.parseInt(startTime) % 60);
            int hoursEnd = (Integer.parseInt(finishTime) / 60);
            int minutesEnd = (Integer.parseInt(finishTime) % 60);
            try {
              cal.setTimeInMillis(Long.parseLong(currentDate));
              if (hoursBg < cal.getMinimum(Calendar.HOUR_OF_DAY)) {
                hoursBg = 0;
                minutesBg = 0;
              }
              cal.set(Calendar.HOUR_OF_DAY, hoursBg);
              cal.set(Calendar.MINUTE, minutesBg);
              isMove = (eventCalendar.getFromDateTime().getTime() != cal.getTimeInMillis());
              eventCalendar.setFromDateTime(cal.getTime());
              if (hoursEnd >= 24) {
                hoursEnd = 23;
                minutesEnd = 59;
              }
              cal.set(Calendar.HOUR_OF_DAY, hoursEnd);
              cal.set(Calendar.MINUTE, minutesEnd);
              eventCalendar.setToDateTime(cal.getTime());
            } catch (Exception e) {
              if (log.isDebugEnabled()) {
                log.debug("Fail when calculate the time for calendar", e);
              }
              return;
            }
            if (eventCalendar.getToDateTime().before(eventCalendar.getFromDateTime())) {
              return;
            }
            // if it's a 'virtual' occurrence
            if (isOccur && !Utils.isEmpty(recurId)) {
              if (!isMove) {
                UIPopupAction pAction = uiCalendarPortlet.getChild(UIPopupAction.class);
                UIConfirmForm confirmForm = pAction.activate(UIConfirmForm.class, 480);
                confirmForm.setConfirmMessage("update-recurrence-event-confirm-msg");
                confirmForm.setDelete(false);
                confirmForm.setConfig_id(calendarview.getId());
                calendarview.setCurrentOccurrence(eventCalendar);
                event.getRequestContext().addUIComponentToUpdateByAjax(pAction);
              } else {
                calService = CalendarUtils.getCalendarService();
                CalendarEvent originEvent = calService.getRepetitiveEvent(eventCalendar);
                calService.saveOneOccurrenceEvent(originEvent, eventCalendar, username);
              }
              // return;
              // List<CalendarEvent> listEvent = new ArrayList<CalendarEvent>();
              // listEvent.add(eventCalendar);
              // calendarService.updateOccurrenceEvent(calendarId, calendarId, calType, calType,
              // listEvent, username);
            } else {
              if (calType.equals(CalendarUtils.PRIVATE_TYPE)) {
                calendarService.saveUserEvent(username, calendarId, eventCalendar, false);
              } else if (calType.equals(CalendarUtils.SHARED_TYPE)) {
                calendarService.saveEventToSharedCalendar(
                    username, calendarId, eventCalendar, false);
              } else if (calType.equals(CalendarUtils.PUBLIC_TYPE)) {
                calendarService.savePublicEvent(calendarId, eventCalendar, false);
              }
            }
            calendarview.setLastUpdatedEventId(eventId);
            calendarview.refresh();
            UIMiniCalendar uiMiniCalendar =
                uiCalendarPortlet.findFirstComponentOfType(UIMiniCalendar.class);
            event.getRequestContext().addUIComponentToUpdateByAjax(uiMiniCalendar);
            if (isOccur) {
              event.getRequestContext().addUIComponentToUpdateByAjax(calendarview);
            } else {
              JavascriptManager jsManager = event.getRequestContext().getJavascriptManager();
              RequireJS requireJS = jsManager.getRequireJS();
              requireJS.require("PORTLET/calendar/CalendarPortlet", "cal");
              requireJS.addScripts("cal.UIWeekView.setSize();cal.UIWeekView.cleanUp();");
            }
          }
        } catch (PathNotFoundException e) {
          if (log.isDebugEnabled()) {
            log.debug("The calendar is not found", e);
          }
          event
              .getRequestContext()
              .getUIApplication()
              .addMessage(new ApplicationMessage("UICalendars.msg.have-no-calendar", null, 1));
        } catch (Exception ex) {
          if (log.isDebugEnabled()) {
            log.debug("The calendar is not found", ex);
          }
        }
      }
    }
  /**
   * 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);
    }
  }
예제 #28
0
  /** Invoked by the HTTPClient. */
  public int requestHandler(Request req, Response[] resp) {
    HTTPConnection con = req.getConnection();
    URI new_loc, cur_loc;

    // check for retries

    HttpOutputStream out = req.getStream();
    if (out != null && deferred_redir_list.get(out) != null) {
      copyFrom((RedirectionModule) deferred_redir_list.remove(out));
      req.copyFrom(saved_req);

      if (new_con) return REQ_NEWCON_RST;
      else return REQ_RESTART;
    }

    // handle permanent redirections

    try {
      cur_loc =
          new URI(
              new URI(con.getProtocol(), con.getHost(), con.getPort(), null), req.getRequestURI());
    } catch (ParseException pe) {
      throw new Error("HTTPClient Internal Error: unexpected exception '" + pe + "'", pe);
    }

    // handle permanent redirections

    Hashtable perm_redir_list =
        Util.getList(perm_redir_cntxt_list, req.getConnection().getContext());
    if ((new_loc = (URI) perm_redir_list.get(cur_loc)) != null) {
      /*
       * copy query if present in old url but not in new url. This isn't
       * strictly conforming, but some scripts fail to properly propagate the
       * query string to the Location header. Unfortunately it looks like we're
       * f****d either way: some scripts fail if you don't propagate the query
       * string, some fail if you do... God, don't you just love it when people
       * can't read a spec? Anway, since we can't get it right for all scripts
       * we opt to follow the spec. String nres = new_loc.getPathAndQuery(),
       * oquery = Util.getQuery(req.getRequestURI()), nquery =
       * Util.getQuery(nres); if (nquery == null && oquery != null) nres += "?"
       * + oquery;
       */
      String nres = new_loc.getPathAndQuery();
      req.setRequestURI(nres);

      try {
        lastURI = new URI(new_loc, nres);
      } catch (ParseException pe) {
        if (LOG.isTraceEnabled()) {
          LOG.trace("An exception occurred: " + pe.getMessage());
        }
      }

      if (LOG.isDebugEnabled())
        LOG.debug(
            "Matched request in permanent redirection list - redoing request to "
                + lastURI.toExternalForm());

      if (!con.isCompatibleWith(new_loc)) {
        try {
          con = new HTTPConnection(new_loc);
        } catch (ProtocolNotSuppException e) {
          throw new Error("HTTPClient Internal Error: unexpected " + "exception '" + e + "'", e);
        }

        con.setContext(req.getConnection().getContext());
        req.setConnection(con);
        return REQ_NEWCON_RST;
      } else {
        return REQ_RESTART;
      }
    }

    return REQ_CONTINUE;
  }
예제 #29
0
  public void execute(JobExecutionContext context) throws JobExecutionException {
    Session session = null;
    try {
      if (LOG.isInfoEnabled()) {
        LOG.info("Start Execute ImportXMLJob");
      }
      if (stagingStorage == null) {

        JobDataMap jdatamap = context.getJobDetail().getJobDataMap();
        stagingStorage = jdatamap.getString("stagingStorage");
        temporaryStorge = jdatamap.getString("temporaryStorge");
        if (LOG.isDebugEnabled()) {
          LOG.debug("Init parameters first time :");
        }
      }
      SessionProvider sessionProvider = SessionProvider.createSystemProvider();
      String containerName = WCMCoreUtils.getContainerNameFromJobContext(context);
      RepositoryService repositoryService_ =
          WCMCoreUtils.getService(RepositoryService.class, containerName);
      ManageableRepository manageableRepository = repositoryService_.getCurrentRepository();
      PublicationService publicationService =
          WCMCoreUtils.getService(PublicationService.class, containerName);
      PublicationPlugin publicationPlugin =
          publicationService
              .getPublicationPlugins()
              .get(AuthoringPublicationConstant.LIFECYCLE_NAME);
      XMLInputFactory factory = XMLInputFactory.newInstance();

      File stagingFolder = new File(stagingStorage);
      File tempfolder = new File(temporaryStorge);

      File[] files = null;
      File xmlFile = null;
      XMLStreamReader reader = null;
      InputStream xmlInputStream = null;
      int eventType;
      List<LinkObject> listLink = new ArrayList<LinkObject>();
      LinkObject linkObj = new LinkObject();
      boolean hasNewContent = false;
      if (stagingFolder.exists()) {
        files = stagingFolder.listFiles();
        if (files != null) {
          hasNewContent = true;
          for (int i = 0; i < files.length; i++) {
            xmlFile = files[i];
            if (xmlFile.isFile()) {
              MimeTypeResolver resolver = new MimeTypeResolver();
              String fileName = xmlFile.getName();
              String hashCode = fileName.split("-")[0];
              String mimeType = resolver.getMimeType(xmlFile.getName());
              if ("text/xml".equals(mimeType)) {
                xmlInputStream = new FileInputStream(xmlFile);
                reader = factory.createXMLStreamReader(xmlInputStream);
                while (reader.hasNext()) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT && "data".equals(reader.getLocalName())) {
                    String data = reader.getElementText();

                    if (!tempfolder.exists()) tempfolder.mkdirs();
                    long time = System.currentTimeMillis();
                    File file =
                        new File(
                            temporaryStorge
                                + File.separator
                                + "-"
                                + hashCode
                                + "-"
                                + time
                                + ".xml.tmp");
                    InputStream inputStream = new ByteArrayInputStream(data.getBytes());
                    OutputStream out = new FileOutputStream(file);
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len);
                    out.close();
                    inputStream.close();
                  }
                  try {
                    if (eventType == XMLEvent.START_ELEMENT
                        && "published-content".equals(reader.getLocalName())) {
                      linkObj.setSourcePath(reader.getAttributeValue(0)); // --Attribute
                      // number
                      // 0 =
                      // targetPath
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "type".equals(reader.getLocalName())) {
                      linkObj.setLinkType(reader.getElementText());
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "title".equals(reader.getLocalName())) {
                      linkObj.setLinkTitle(reader.getElementText());
                    }
                    if (eventType == XMLEvent.START_ELEMENT
                        && "targetPath".equals(reader.getLocalName())) {
                      linkObj.setLinkTargetPath(reader.getElementText());
                      listLink.add(linkObj);
                    }

                    if (eventType == XMLEvent.START_ELEMENT
                        && "unpublished-content".equals(reader.getLocalName())) {

                      String contentTargetPath = reader.getAttributeValue(0);
                      String[] strContentPath = contentTargetPath.split(":");
                      StringBuffer sbContPath = new StringBuffer();
                      boolean flag = true;
                      for (int index = 2; index < strContentPath.length; index++) {
                        if (flag) {
                          sbContPath.append(strContentPath[index]);
                          flag = false;
                        } else {
                          sbContPath.append(":").append(strContentPath[index]);
                        }
                      }
                      sessionProvider = SessionProvider.createSystemProvider();

                      manageableRepository = repositoryService_.getCurrentRepository();
                      String workspace = strContentPath[1];
                      session = sessionProvider.getSession(workspace, manageableRepository);
                      String contentPath = sbContPath.toString();
                      if (session.itemExists(contentPath)) {
                        Node currentContent = (Node) session.getItem(contentPath);
                        HashMap<String, String> variables = new HashMap<String, String>();
                        variables.put("nodePath", contentTargetPath);
                        variables.put("workspaceName", workspace);
                        if (currentContent.hasProperty(
                                StageAndVersionPublicationConstant.PUBLICATION_LIFECYCLE_NAME)
                            && AuthoringPublicationConstant.LIFECYCLE_NAME.equals(
                                currentContent
                                    .getProperty(
                                        StageAndVersionPublicationConstant
                                            .PUBLICATION_LIFECYCLE_NAME)
                                    .getString())
                            && PublicationDefaultStates.PUBLISHED.equals(
                                currentContent
                                    .getProperty(StageAndVersionPublicationConstant.CURRENT_STATE)
                                    .getString())) {

                          publicationPlugin.changeState(
                              currentContent, PublicationDefaultStates.UNPUBLISHED, variables);
                          if (LOG.isInfoEnabled()) {
                            LOG.info(
                                "Change the status of the node "
                                    + currentContent.getPath()
                                    + " from "
                                    + PublicationDefaultStates.PUBLISHED
                                    + " to "
                                    + PublicationDefaultStates.UNPUBLISHED);
                          }
                        }
                      } else {
                        if (LOG.isWarnEnabled()) {
                          LOG.warn("The node " + contentPath + " does not exist");
                        }
                      }
                    }

                  } catch (Exception ie) {
                    if (LOG.isWarnEnabled()) {
                      LOG.warn("Error in ImportContentsJob: " + ie.getMessage());
                    }
                  }
                }
                reader.close();
                xmlInputStream.close();
                xmlFile.delete();
              }
            }
          }
        }
      }
      files = tempfolder.listFiles();
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          xmlFile = files[i];
          InputStream inputStream = new FileInputStream(xmlFile);
          reader = factory.createXMLStreamReader(inputStream);
          String workspace = null;
          String nodePath = new String();

          while (reader.hasNext()) {
            eventType = reader.next();
            if (eventType == XMLEvent.START_ELEMENT) {
              if (reader.getLocalName().equals("property")) {
                String value = reader.getAttributeValue(0);
                if (MIX_TARGET_PATH.equals(value)) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT) {
                    reader.next();
                    nodePath = reader.getText();
                  }
                } else if (MIX_TARGET_WORKSPACE.equals(value)) {
                  eventType = reader.next();
                  if (eventType == XMLEvent.START_ELEMENT) {
                    reader.next();
                    workspace = reader.getText();
                  }
                }
              }
            }
          }
          reader.close();
          inputStream.close();
          session = sessionProvider.getSession(workspace, manageableRepository);
          if (session.itemExists(nodePath)) session.getItem(nodePath).remove();
          session.save();

          String path = nodePath.substring(0, nodePath.lastIndexOf(JCR_File_SEPARATOR));
          if (!session.itemExists(path)) {
            String[] pathTab = path.split(JCR_File_SEPARATOR);
            Node node_ = session.getRootNode();
            StringBuffer path_ = new StringBuffer(JCR_File_SEPARATOR);
            for (int j = 1; j < pathTab.length; j++) {
              path_ = path_.append(pathTab[j] + JCR_File_SEPARATOR);
              if (!session.itemExists(path_.toString())) {
                node_.addNode(pathTab[j], "nt:unstructured");
              }
              node_ = (Node) session.getItem(path_.toString());
            }
          }

          session.importXML(path, new FileInputStream(xmlFile), 0);
          session.save();
          xmlFile.delete();

          if (hasNewContent) {
            for (LinkObject obj : listLink) {
              String[] linkTarget = obj.getLinkTargetPath().split(":");
              StringBuffer itemPath = new StringBuffer();
              boolean flag = true;
              for (int index = 2; index < linkTarget.length; index++) {
                if (flag) {
                  itemPath.append(linkTarget[index]);
                  flag = false;
                } else {
                  itemPath.append(":");
                  itemPath.append(linkTarget[index]);
                }
              }
              String[] linkSource = obj.getSourcePath().split(":");
              session = sessionProvider.getSession(linkTarget[1], manageableRepository);
              Node parentNode = (Node) session.getItem(itemPath.toString());

              StringBuffer sourcePath = new StringBuffer();
              boolean flagSource = true;
              for (int index = 2; index < linkSource.length; index++) {
                if (flagSource) {
                  sourcePath.append(linkSource[index]);
                  flagSource = false;
                } else {
                  sourcePath.append(":");
                  sourcePath.append(linkSource[index]);
                }
              }

              if (parentNode.hasNode(obj.getLinkTitle())) {
                Node existedNode = (Node) session.getItem(itemPath + "/" + obj.getLinkTitle());
                existedNode.remove();
              }
              session = sessionProvider.getSession(linkSource[1], manageableRepository);
              Node targetNode = (Node) session.getItem(sourcePath.toString());
              LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class, containerName);
              linkManager.createLink(parentNode, obj.getLinkType(), targetNode, obj.getLinkTitle());
            }
          }
        }
      }
      if (LOG.isInfoEnabled()) {
        LOG.info("End Execute ImportXMLJob");
      }
    } catch (RepositoryException ex) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Repository 'repository ' not found.");
      }
    } catch (Exception ex) {
      if (LOG.isErrorEnabled()) {
        LOG.error("Error when importing Contents : " + ex.getMessage(), ex);
      }
    } finally {
      if (session != null) session.logout();
    }
  }
  private Map<String, String> buildParams(CalendarEvent oldEvent, CalendarEvent newEvent) {
    Map<String, String> messagesParams = new LinkedHashMap<String, String>();
    try {
      if (CalendarEvent.TYPE_EVENT.equals(newEvent.getEventType())) {
        if (!oldEvent.getSummary().equals(newEvent.getSummary())) {
          messagesParams.put(SUMMARY_UPDATED, newEvent.getSummary());
        }

        /* change description */
        if (newEvent.getDescription() != null
            && !newEvent.getDescription().equals(oldEvent.getDescription())) {
          messagesParams.put(DESCRIPTION_UPDATED, newEvent.getDescription());
        }
        /* remove description */
        else if ((newEvent.getDescription() == null) && (oldEvent.getDescription() != null)) {
          messagesParams.put(DESCRIPTION_REMOVED, "");
        }

        /* change location */
        if (newEvent.getLocation() != null
            && !newEvent.getLocation().equals(oldEvent.getLocation())) {
          messagesParams.put(LOCATION_UPDATED, newEvent.getLocation());
        }
        /* remove location */
        else if ((newEvent.getLocation() == null) && (oldEvent.getLocation() != null)) {
          messagesParams.put(LOCATION_REMOVED, "");
        }

        if (newEvent.getPriority() != null
            && !newEvent.getPriority().equals(oldEvent.getPriority())) {
          messagesParams.put(PRIORITY_UPDATED, newEvent.getPriority());
        }
        if (newEvent.getAttachment() != null)
          if (oldEvent.getAttachment() == null) {
            messagesParams.put(ATTACH_UPDATED, "");
          } else if (newEvent.getAttachment().size() != oldEvent.getAttachment().size()) {
            messagesParams.put(ATTACH_UPDATED, "");
          }
        if (isAllDayEvent(newEvent)
            && !isAllDayEvent(oldEvent)
            && CalendarEvent.TYPE_EVENT.equals(oldEvent.getEventType())) {
          messagesParams.put(ALLDAY_UPDATED, "");
        } else if (!isAllDayEvent(newEvent)) {
          if (newEvent.getFromDateTime().compareTo(oldEvent.getFromDateTime()) != 0) {
            messagesParams.put(FROM_UPDATED, String.valueOf(newEvent.getFromDateTime().getTime()));
          }
          if (newEvent.getToDateTime().compareTo(oldEvent.getToDateTime()) != 0) {
            messagesParams.put(TO_UPDATED, String.valueOf(newEvent.getToDateTime().getTime()));
          }
        }

        /*=== compare the repeat type ===*/
        String repeatSummary = buildRepeatSummary(newEvent);
        if (!repeatSummary.equals(buildRepeatSummary(oldEvent))) {
          messagesParams.put(REPEAT_UPDATED, repeatSummary);
        }

        /*=== compare the activity id ===*/
        // oldEvent -- occurrence or instance of repetitive event -- no activity
        // newEvent -- repetitiveEvent - with activity
        if (!newEvent.getActivityId().equals(oldEvent.getActivityId())) {
          messagesParams.put(
              REPEAT_EVENT_INSTANCE_REMOVED,
              getDateFormattedAfterUserSetting(oldEvent.getRecurrenceId()));
        }

      } else {
        if (!oldEvent.getSummary().equals(newEvent.getSummary())) {
          messagesParams.put(NAME_UPDATED, newEvent.getSummary());
        }
        /* change note */
        if (newEvent.getDescription() != null
            && !newEvent.getDescription().equals(oldEvent.getDescription())) {
          messagesParams.put(NOTE_UPDATED, newEvent.getDescription());
        }
        /* removed note */
        else if ((newEvent.getDescription() == null) && (oldEvent.getDescription() != null)) {
          messagesParams.put(NOTE_REMOVED, "");
        }

        if (!isAllDayEvent(newEvent)) {
          if (newEvent.getFromDateTime().compareTo(oldEvent.getFromDateTime()) != 0) {
            messagesParams.put(FROM_UPDATED, String.valueOf(newEvent.getFromDateTime().getTime()));
          }
          if (newEvent.getToDateTime().compareTo(oldEvent.getToDateTime()) != 0) {
            messagesParams.put(TO_UPDATED, String.valueOf(newEvent.getToDateTime().getTime()));
          }
        }
        if (newEvent.getPriority() != null
            && !newEvent.getPriority().equals(oldEvent.getPriority())) {
          messagesParams.put(PRIORITY_UPDATED, newEvent.getPriority());
        }
        if (newEvent.getAttachment() != null)
          if (oldEvent.getAttachment() == null) {
            messagesParams.put(TASK_ATTACH_UPDATED, "");
          } else if (newEvent.getAttachment().size() != oldEvent.getAttachment().size()) {
            messagesParams.put(TASK_ATTACH_UPDATED, "");
          }
        if (newEvent.getEventState() != null
            && !newEvent.getEventState().equals(oldEvent.getEventState())) {
          if (CalendarEvent.NEEDS_ACTION.equals(newEvent.getEventState())) {
            messagesParams.put(TASK_NEED_ACTION, newEvent.getEventState());
          } else if (CalendarEvent.IN_PROCESS.equals(newEvent.getEventState())) {
            messagesParams.put(TASK_IN_PROCESS_ACTION, newEvent.getEventState());
          } else if (CalendarEvent.COMPLETED.equals(newEvent.getEventState())) {
            messagesParams.put(TASK_COMPLETED_ACTION, newEvent.getEventState());
          } else if (CalendarEvent.CANCELLED.equals(newEvent.getEventState())) {
            messagesParams.put(TASK_CANCELLED_ACTION, newEvent.getEventState());
          }
        }
      }
    } catch (Exception e) {
      if (LOG.isDebugEnabled()) LOG.error("Can not build message for space when event updated ", e);
    }
    return messagesParams;
  }