Ejemplo n.º 1
0
  public Map<String, Object> unpublishEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    Map<String, Object> callbackData = new HashMap<String, Object>(); // DOTCMS-5199
    List<String> eventUnpublishErrors = new ArrayList<String>();
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);

    try {
      contAPI.unpublish(ev, user, respectFrontendRoles);
    } catch (DotSecurityException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } catch (DotDataException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } catch (DotContentletStateException e) {
      eventUnpublishErrors.add(e.getLocalizedMessage());
    } finally {
      if (eventUnpublishErrors.size() > 0) {
        callbackData.put("eventUnpublishErrors", eventUnpublishErrors);
      }
    }
    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }

    return callbackData;
  }
Ejemplo n.º 2
0
  public Map<String, Object> deleteEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();
    List<String> eventDeleteErrors = new ArrayList<String>();
    Map<String, Object> callbackData = new HashMap<String, Object>();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    if (ev.isLive()) {
      try {
        contAPI.unpublish(ev, user, respectFrontendRoles);
      } catch (DotSecurityException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotDataException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      } catch (DotContentletStateException e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    } else if (!ev.isArchived()) {
      try {
        contAPI.archive(ev, user, respectFrontendRoles);
      } catch (Exception e) {
        eventDeleteErrors.add(e.getLocalizedMessage());
      }
    }

    try {
      if (ev.isArchived()) {
        contAPI.delete(ev, user, respectFrontendRoles);
      }
    } catch (Exception e) {
      eventDeleteErrors.add(e.getLocalizedMessage());
    } finally {
      if (eventDeleteErrors.size() > 0) {
        callbackData.put("eventUnpublishErrors", eventDeleteErrors);
      }
    }
    if (eventDeleteErrors.size() <= 0) {
      HibernateUtil.commitTransaction();
    }

    // At this point we already deleted the content from the index on the delete call
    /*if(!contAPI.isInodeIndexed(ev.getInode())){
    	Logger.error(this, "Timed out while waiting for index to return");
    }*/

    return callbackData;
  }
Ejemplo n.º 3
0
  /**
   * Create a work flow task for the new content created and send a email to the corresponding role
   * moderator users
   *
   * @param contentlet The content
   * @param user The user that add the content
   * @param moderatorRole The role to assign the work flow
   * @throws DotDataException
   * @throws DotDataException
   */
  public static void createWorkFlowTask(Contentlet contentlet, String userId, String moderatorRole)
      throws DotDataException {

    User user = getUserFromId(userId);
    StringBuffer changeHist = new StringBuffer("Task Added<br>");
    WorkflowTask task = new WorkflowTask();

    changeHist.append("Title: " + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle()) + "<br>");
    task.setTitle(
        "A new content titled: "
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle())
            + " has been posted.");
    task.setDescription(
        "A new content titled \""
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle().trim())
            + "\" has been posted by "
            + UtilHTML.escapeHTMLSpecialChars(user.getFullName())
            + " ("
            + user.getEmailAddress()
            + ")");
    changeHist.append(
        "Description: " + UtilHTML.escapeHTMLSpecialChars(task.getDescription()) + "<br>");

    Role role = roleAPI.loadRoleByKey(moderatorRole);
    task.setBelongsTo(role.getId());
    task.setAssignedTo("Nobody");
    task.setModDate(new Date());
    task.setCreationDate(new Date());
    task.setCreatedBy(user.getUserId());

    task.setStatus(WorkflowStatuses.OPEN.toString());
    changeHist.append("Due Date: " + UtilMethods.dateToHTMLDate(task.getDueDate()) + " -> <br>");
    task.setDueDate(null);
    task.setWebasset(contentlet.getInode());

    // HibernateUtil.saveOrUpdate(task);

    // Save the work flow comment
    WorkflowComment taskComment = new WorkflowComment();
    taskComment.setComment(task.getDescription());
    taskComment.setCreationDate(new Date());
    taskComment.setPostedBy(user.getUserId());
    HibernateUtil.saveOrUpdate(taskComment);
    relAPI.addRelationship(task.getInode(), taskComment.getInode(), "child");

    // Save the work flow history
    WorkflowHistory hist = new WorkflowHistory();
    hist.setChangeDescription("Task Creation");
    hist.setCreationDate(new Date());
    hist.setMadeBy(user.getUserId());
    HibernateUtil.saveOrUpdate(hist);
    relAPI.addRelationship(task.getInode(), hist.getInode(), "child");

    // WorkflowEmailUtil.sendWorkflowChangeEmails (task, "New user content has been submitted", "New
    // Task", null);

  }
Ejemplo n.º 4
0
  public Folder getFileFolder(File file, String hostId) throws DotDataException {
    HibernateUtil hu = new HibernateUtil(Folder.class);
    hu.setSQLQuery(
        "select {folder.*} from folder,identifier,inode folder_1_ where folder.identifier = identifier.id and "
            + "folder_1_.inode = folder.inode and host_inode = ? and path =(select parent_path from identifier where id=?)");

    hu.setParam(hostId);
    hu.setParam(file.getIdentifier());
    return (Folder) hu.load();
  }
Ejemplo n.º 5
0
  public File getLiveFileByFileName(String fileName, Folder folder) throws DotDataException {

    Identifier id = APILocator.getIdentifierAPI().find(folder);

    HibernateUtil hu = new HibernateUtil(File.class);
    hu.setSQLQuery(liveFileByName);
    hu.setParam(id.getPath());
    hu.setParam(fileName);

    return (File) hu.load();
  }
Ejemplo n.º 6
0
 @SuppressWarnings("unchecked")
 public File getWorkingFileById(String identifier) throws DotDataException {
   HibernateUtil hu = new HibernateUtil(File.class);
   hu.setSQLQuery(
       "select {file_asset.*} from file_asset, inode file_asset_1_, fileasset_version_info vi "
           + " where file_asset.identifier = ? and vi.identifier=file_asset.identifier and vi.working_inode=file_asset.inode "
           + "and file_asset_1_.inode = file_asset.inode");
   hu.setParam(identifier);
   List<File> files = hu.list();
   if (files.size() == 0) return null;
   return files.get(0);
 }
 /**
  * Return all the CalendarReminders of the system
  *
  * @return
  * @throws DotDataException
  */
 public List<CalendarReminder> getAll() {
   List<CalendarReminder> returnValue = new ArrayList<CalendarReminder>();
   try {
     String query =
         "from calendar_reminder in class com.dotmarketing.portlets.calendar.model.CalendarReminder";
     HibernateUtil dh = new HibernateUtil(CalendarReminder.class);
     dh.setQuery(query);
     returnValue = (List<CalendarReminder>) dh.list();
   } catch (Exception ex) {
     Logger.warn(CalendarReminderFactoryImpl.class, "getAll failed:" + ex.getMessage(), ex);
   }
   return returnValue;
 }
  /**
   * Return all the CalendarReminders of the system
   *
   * @return
   * @throws DotDataException
   */
  public List<CalendarReminder> getAll() {
    List<CalendarReminder> returnValue = new ArrayList<CalendarReminder>();
    try {
      String query =
          "from calendar_reminder in class com.dotmarketing.portlets.calendar.model.CalendarReminder";
      HibernateUtil dh = new HibernateUtil(CalendarReminder.class);
      dh.setQuery(query);
      returnValue = (List<CalendarReminder>) dh.list();
    } catch (Exception ex) {

    } finally {
      return returnValue;
    }
  }
Ejemplo n.º 9
0
  @SuppressWarnings("unchecked")
  public File saveFile(
      File newFile, java.io.File dataFile, Folder parentFolder, Identifier identifier)
      throws DotDataException {

    boolean localTransation = false;

    try {
      localTransation = DbConnectionFactory.getConnection().getAutoCommit();
      if (localTransation) {
        HibernateUtil.startTransaction();
      }
      // old working file
      File oldFile = null;
      // if new identifier
      if (identifier == null || !InodeUtils.isSet(identifier.getInode())) {
        identifier = APILocator.getIdentifierAPI().createNew(newFile, parentFolder);
        newFile.setIdentifier(identifier.getInode());
        HibernateUtil.save(newFile);
        APILocator.getVersionableAPI().setWorking(newFile);
        saveFileData(newFile, null, dataFile);
      } else {
        APILocator.getVersionableAPI().removeLive(identifier.getId());
      }
      if (UtilMethods.isSet(dataFile)) {
        HibernateUtil.save(newFile);
        saveFileData(newFile, null, dataFile);
      }
      if (oldFile != null && InodeUtils.isSet(oldFile.getInode())) {
        APILocator.getFileAPI().invalidateCache(oldFile);
        fileCache.remove(oldFile);
        WorkingCache.removeAssetFromCache(oldFile);
      }
      LiveCache.removeAssetFromCache(newFile);
      if (newFile.isLive()) {
        LiveCache.addToLiveAssetToCache(newFile);
      }
      WorkingCache.addToWorkingAssetToCache(newFile);

      if (localTransation) {
        HibernateUtil.commitTransaction();
      }
    } catch (Exception e) {
      if (localTransation) {
        HibernateUtil.rollbackTransaction();
      }
      throw new DotDataException(e.getMessage(), e);
    }
    return newFile;
  }
 @SuppressWarnings("unchecked")
 public static java.util.List<ClickstreamRequest> getClickstreamRequestsByClickStream(
     Clickstream cs) {
   HibernateUtil dh = new HibernateUtil(ClickstreamRequest.class);
   try {
     dh.setSQLQuery(
         "SELECT    {clickstream_request.*}  FROM clickstream_request WHERE  clickstream_id = ? ORDER BY timestampper");
     dh.setParam(cs.getClickstreamId());
     return (List<ClickstreamRequest>) dh.list();
   } catch (DotHibernateException e) {
     Logger.error(
         ClickstreamRequestFactory.class, "getClickstreamRequestsByClickStream: failed", e);
     throw new DotRuntimeException(e.getMessage(), e);
   }
 }
Ejemplo n.º 11
0
  /**
   * Copy a file into the given directory OR host
   *
   * @param file File to be copied
   * @param parent Destination Folder
   * @param host Destination host
   * @return true if copy success, false otherwise
   * @throws IOException
   * @throws DotHibernateException
   */
  private File copyFile(File file, Folder parent, Host host) throws DotDataException, IOException {

    File newFile = new File();

    newFile.copy(file);

    // gets filename before extension
    String fileName = com.dotmarketing.util.UtilMethods.getFileName(file.getFileName());
    // gets file extension
    String fileExtension = com.dotmarketing.util.UtilMethods.getFileExtension(file.getFileName());

    Boolean fileNameExists;
    if (parent != null) {
      fileNameExists = fileNameExists(parent, file.getFileName());
    } else {
      fileNameExists =
          fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName());
    }

    // Setting file name
    if (fileNameExists) {
      // adds "copy" word to the filename
      newFile.setFileName(fileName + "_copy." + fileExtension);
      newFile.setFriendlyName(file.getFriendlyName() + " (COPY) ");
    } else {
      newFile.setFileName(fileName + "." + fileExtension);
    }

    Identifier identifier;
    if (parent != null) {
      identifier = APILocator.getIdentifierAPI().createNew(newFile, parent);
    } else {
      identifier = APILocator.getIdentifierAPI().createNew(newFile, host);
    }
    newFile.setIdentifier(identifier.getInode());

    // persists the webasset
    HibernateUtil.saveOrUpdate(newFile);

    saveFileData(file, newFile, null);

    Logger.debug(FileFactory.class, "identifier=" + identifier.getURI());

    WorkingCache.removeAssetFromCache(newFile);
    WorkingCache.addToWorkingAssetToCache(newFile);
    PermissionAPI permissionAPI = APILocator.getPermissionAPI();

    try {
      APILocator.getVersionableAPI().setWorking(newFile);
      if (file.isLive()) APILocator.getVersionableAPI().setLive(newFile);
    } catch (DotStateException e) {
      Logger.error(this, e.getMessage());
    } catch (DotSecurityException e) {
      Logger.error(this, e.getMessage());
    }
    // Copy permissions
    permissionAPI.copyPermissions(file, newFile);

    return newFile;
  }
 /** Save a CalendarReminder to the DB */
 public void saveCalendarReminder(CalendarReminder calendarReminder) {
   try {
     HibernateUtil.save(calendarReminder);
   } catch (DotHibernateException e) {
     Logger.error(CalendarReminderFactoryImpl.class, "saveCalendarReminder failed:" + e, e);
   }
 }
 /**
  * Retrieve all the CalendarReminders before the specified date
  *
  * @param sendDate The Date used to retrieve the CalendarReminders
  * @return
  */
 public List<CalendarReminder> getCalendarReminderBefore(Date sendDate) {
   List<CalendarReminder> returnValue = new ArrayList<CalendarReminder>();
   try {
     String query =
         "from calendar_reminder in class com.dotmarketing.portlets.calendar.model.CalendarReminder where send_date <= ?";
     HibernateUtil dh = new HibernateUtil(CalendarReminder.class);
     dh.setQuery(query);
     dh.setParam(sendDate);
     returnValue = (List<CalendarReminder>) dh.list();
   } catch (Exception ex) {
     Logger.warn(
         CalendarReminderFactoryImpl.class, "getCalendareReminder failed:" + ex.getMessage(), ex);
   } finally {
     return returnValue;
   }
 }
 /**
  * Delete a specific CalendarReminder
  *
  * @param calendarReminder CalendarReminder to delete
  * @throws DotDataException
  */
 public void deleteCalendarReminder(CalendarReminder calendarReminder) {
   try {
     HibernateUtil.delete(calendarReminder);
   } catch (DotHibernateException e) {
     Logger.warn(CalendarReminderFactoryImpl.class, "deleteCalendarReminder failed:" + e, e);
   }
 }
Ejemplo n.º 15
0
  public void unarchiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {

      if (UtilMethods.isSet(ev.getDisconnectedFrom())) {
        Event baseEvent = null;
        try {
          baseEvent = eventAPI.find(ev.getDisconnectedFrom(), false, user, respectFrontendRoles);
        } catch (Exception e) {
          Logger.error(this, "Base event not found");
        }
        if (baseEvent != null) {
          try {
            Date originalStartDate = ev.getOriginalStartDate();
            baseEvent.addDateToIgnore(originalStartDate);
            APILocator.getContentletAPI()
                .checkin(
                    baseEvent,
                    categoryAPI.getParents(baseEvent, user, true),
                    perAPI.getPermissions(baseEvent),
                    user,
                    false);
          } catch (Exception e) {
            Logger.error(this, "Could not delete event from recurrence");
          }
        }
      }
      contAPI.unarchive(ev, user, respectFrontendRoles);

    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
 public static void save(ClickstreamRequest clickstreamRequest) {
   try {
     HibernateUtil.saveOrUpdate(clickstreamRequest);
   } catch (DotHibernateException e) {
     Logger.error(ClickstreamRequestFactory.class, "save: failed", e);
     throw new DotRuntimeException(e.getMessage(), e);
   }
 }
Ejemplo n.º 17
0
  @SuppressWarnings("unchecked")
  public List<File> getAllHostFiles(Host host, boolean live) throws DotDataException {
    HibernateUtil hu = new HibernateUtil(File.class);
    StringBuilder queryBuilder =
        new StringBuilder(
            "select {file_asset.*} from file_asset, inode file_asset_1_,identifier ident, fileasset_version_info vi "
                + "where file_asset.inode = file_asset_1_.inode and "
                + "file_asset.identifier = ident.id and asset_type='file_asset' and ident.id=vi.identifier "
                + " and ident.host_inode = ? ");
    if (live) queryBuilder.append(" and vi.live_inode=file_asset.inode ");
    else queryBuilder.append(" and vi.working_inode=file_asset.inode ");

    hu.setSQLQuery(queryBuilder.toString());
    hu.setParam(host.getIdentifier());

    return hu.list();
  }
Ejemplo n.º 18
0
  @SuppressWarnings({"unchecked", "deprecation"})
  public boolean renameFile(File file, String newName)
      throws DotStateException, DotDataException, DotSecurityException {

    // getting old file properties
    String oldFileName = file.getFileName();
    String ext = UtilMethods.getFileExtension(oldFileName);
    Folder folder =
        APILocator.getFolderAPI()
            .findParentFolder(file, APILocator.getUserAPI().getSystemUser(), false);

    Identifier ident = APILocator.getIdentifierAPI().find(file);

    String newFileName = newName;
    if (UtilMethods.isSet(ext)) {
      newFileName = newFileName + "." + ext;
    }

    if (fileNameExists(folder, newFileName) || file.isLocked()) return false;

    List<Versionable> versions = APILocator.getVersionableAPI().findAllVersions(ident);

    boolean islive = false;

    for (Versionable version : versions) {
      File f = (File) version;

      // sets filename for this new file
      f.setFileName(newFileName);

      HibernateUtil.saveOrUpdate(f);

      if (f.isLive()) islive = true;
    }

    LiveCache.removeAssetFromCache(file);
    WorkingCache.removeAssetFromCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    ident.setURI(APILocator.getIdentifierAPI().find(folder).getPath() + newFileName);
    // HibernateUtil.saveOrUpdate(ident);
    APILocator.getIdentifierAPI().save(ident);

    if (islive) {
      LiveCache.removeAssetFromCache(file);
      LiveCache.addToLiveAssetToCache(file);
    }
    WorkingCache.removeAssetFromCache(file);
    WorkingCache.addToWorkingAssetToCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    // RefreshMenus.deleteMenus();
    RefreshMenus.deleteMenu(file);
    CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode());

    return true;
  }
Ejemplo n.º 19
0
  public void delete(File file) throws DotDataException, DotStateException, DotSecurityException {
    HibernateUtil.delete(file);

    fileCache.remove(file);
    WorkingCache.removeAssetFromCache(file);
    if (file.isLive()) {
      LiveCache.removeAssetFromCache(file);
    }
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);
  }
Ejemplo n.º 20
0
  /** Thread main method to start the calendar reminder process */
  @SuppressWarnings("unchecked")
  public void run() {
    Logger.debug(this, "Running Calendar Reminder Job");

    try {
      HibernateUtil.startTransaction();
      CalendarReminderAPI CRAI = APILocator.getCalendarReminderAPI();
      Date now = new Date();
      CRAI.sendCalendarRemainder(now);
      Logger.debug(this, "The Calendar Reminder Job End successfully");
    } catch (Exception e) {
      Logger.warn(this, e.toString());
    } finally {
      try {
        HibernateUtil.commitTransaction();
      } catch (Exception e) {
        Logger.warn(this, e.toString());
      }
    }
  }
 /**
  * Delete a List of Calendar Reminder
  *
  * @param calendarReminders List of CalendarReminder to delete
  * @throws DotDataException
  */
 public boolean deleteCalendarReminders(List<CalendarReminder> calendarReminders) {
   boolean errors = false;
   for (CalendarReminder calendarReminder : calendarReminders) {
     try {
       HibernateUtil.delete(calendarReminder);
     } catch (Exception ex) {
       Logger.warn(CalendarReminderFactoryImpl.class, ex.getMessage());
       errors = true;
     }
   }
   return errors;
 }
  // Gets
  public CalendarReminder getCalendarReminder(long userId, String eventId, Date sendDate) {

    /**
     * Find an CalenderReminder, based on the user, event and date of the reminder
     *
     * @param userId userId of the CalendarReminder to retrieve
     * @param eventId eventId of the CalendarReminder to retrieve
     * @param sendDate Date of the CalendarReminder to retrieve
     * @return
     */
    CalendarReminder returnValue = new CalendarReminder();
    try {
      String query =
          "from calendar_reminder in class com.dotmarketing.portlets.calendar.model.CalendarReminder where user_id = ? and event_id = ? and send_date = ?";
      HibernateUtil dh = new HibernateUtil(CalendarReminder.class);
      dh.setQuery(query);
      dh.setParam(userId);
      dh.setParam(eventId);
      dh.setParam(eventId);
      dh.setParam(sendDate);
      returnValue = (CalendarReminder) dh.load();
    } catch (Exception e) {
      Logger.warn(
          CalendarReminderFactoryImpl.class, "getCalendarReminder failed:" + e.getMessage(), e);
    } finally {
      return returnValue;
    }
  }
Ejemplo n.º 23
0
 public static void cleanInodeTableData() throws DotDataException {
   Map map = new HashMap();
   try {
     map = HibernateUtil.getSession().getSessionFactory().getAllClassMetadata();
   } catch (HibernateException e) {
     throw new DotDataException(e.getMessage(), e);
   }
   Iterator it = map.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry) it.next();
     Class x = (Class) pairs.getKey();
     if (!x.equals(Inode.class)) {
       Object o;
       try {
         o = x.newInstance();
       } catch (Exception e) {
         Logger.info(MaintenanceUtil.class, "Unable to instaniate object");
         Logger.debug(MaintenanceUtil.class, "Unable to instaniate object", e);
         continue;
       }
       if (o instanceof Inode) {
         Inode i = (Inode) o;
         String type = i.getType();
         String tableName =
             ((net.sf.hibernate.persister.AbstractEntityPersister) map.get(x)).getTableName();
         cleanInodeTableData(tableName, type);
       }
     }
   }
   it = map.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry) it.next();
     Class x = (Class) pairs.getKey();
     if (!x.equals(Inode.class)) {
       Object o;
       try {
         o = x.newInstance();
       } catch (Exception e) {
         Logger.info(MaintenanceUtil.class, "Unable to instaniate object");
         Logger.debug(MaintenanceUtil.class, "Unable to instaniate object", e);
         continue;
       }
       if (o instanceof Inode) {
         Inode i = (Inode) o;
         String type = i.getType();
         String tableName =
             ((net.sf.hibernate.persister.AbstractEntityPersister) map.get(x)).getTableName();
         removeOphanedInodes(tableName, type);
       }
     }
   }
 }
Ejemplo n.º 24
0
  public void archiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {
      contAPI.archive(ev, user, respectFrontendRoles);
    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
Ejemplo n.º 25
0
  /**
   * Copies the event changes from the form to the event object and saves it
   *
   * @param mapping
   * @param form
   * @param config
   * @param req
   * @param res
   * @param user
   * @throws DotSecurityException
   * @throws DotDataException
   */
  private void saveEvent(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig config,
      ActionRequest req,
      ActionResponse res,
      User user)
      throws DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    HttpServletRequest request = ((ActionRequestImpl) req).getHttpServletRequest();

    EventForm eventForm = (EventForm) form;
    Event event = (Event) req.getAttribute(WebKeys.EVENT_EDIT);
  }
Ejemplo n.º 26
0
  public File get(String inode) throws DotStateException, DotDataException, DotSecurityException {
    File file = fileCache.get(inode);

    if ((file == null) || !InodeUtils.isSet(file.getInode())) {
      file = (File) HibernateUtil.load(File.class, inode);

      fileCache.add(file);
      WorkingCache.removeAssetFromCache(file);
      WorkingCache.addToWorkingAssetToCache(file);
      LiveCache.removeAssetFromCache(file);
      if (file.isLive()) {
        LiveCache.addToLiveAssetToCache(file);
      }
    }

    return file;
  }
Ejemplo n.º 27
0
  public static int deleteOldAssetVersions(Date assetsOlderThan) {
    int counter = 0;
    int auxCount = 0;

    /*
     * Run the drop tasks interatively, moving forward in time
     * DROP_OLD_ASSET_ITERATE_BY_SECONDS controls how many seconds to
     * move forward in time for each iteration - default is to iterate by 30 days
     */
    Calendar runDate = Calendar.getInstance();
    runDate.setTime(assetsOlderThan);
    runDate.add(Calendar.YEAR, -2);

    try {
      DotConnect dc = new DotConnect();
      String minIdateSQL = "select idate from inode order by idate";

      dc.setSQL(minIdateSQL);
      dc.setMaxRows(1);
      List<Map<String, Object>> map = dc.loadObjectResults();
      Date d = (Date) map.get(0).get("idate");
      if (d != null) runDate.setTime(d);
    } catch (Exception e) {
      Logger.info(CMSMaintenanceFactory.class, "Can't get start date");
    }

    while (runDate.getTime().before(assetsOlderThan) || runDate.getTime().equals(assetsOlderThan)) {
      try {
        HibernateUtil.startTransaction();
        Logger.info(
            CMSMaintenanceFactory.class,
            "Starting deleteOldAssetVersions for date: "
                + UtilMethods.dateToHTMLDate(runDate.getTime(), "yyyy-MM-dd"));

        ContentletAPI conAPI = APILocator.getContentletAPI();

        Logger.info(CMSMaintenanceFactory.class, "Removing Contentlets");
        auxCount = conAPI.deleteOldContent(runDate.getTime());
        counter = auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Contentlets");

        Logger.info(CMSMaintenanceFactory.class, "Removing HTML Pages");
        auxCount = APILocator.getHTMLPageAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " HTML Pages");

        Logger.info(CMSMaintenanceFactory.class, "Removing Containers");
        auxCount = APILocator.getContainerAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Containers");

        Logger.info(CMSMaintenanceFactory.class, "Removing Templates");
        auxCount = APILocator.getTemplateAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Templates");

        Logger.info(CMSMaintenanceFactory.class, "Removing Links");
        auxCount = APILocator.getMenuLinkAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " Links");

        Logger.info(CMSMaintenanceFactory.class, "Removing File Assets");

        auxCount = APILocator.getFileAPI().deleteOldVersions(runDate.getTime());
        counter += auxCount;
        Logger.info(CMSMaintenanceFactory.class, "Removed " + auxCount + " File Assets");

        Logger.info(
            CMSMaintenanceFactory.class,
            "Finished removing old asset versions, removed " + counter + " assets");

        // This is the last run, break
        if (runDate.getTime().equals(assetsOlderThan)) {
          break;
        }
        runDate.add(
            Calendar.SECOND,
            Config.getIntProperty("DROP_OLD_ASSET_ITERATE_BY_SECONDS", 60 * 60 * 24 * 30));

        // we should never go past the date the user entered
        if (runDate.getTime().after(assetsOlderThan)) {
          runDate.setTime(assetsOlderThan);
        }

      } catch (Exception ex) {
        try {
          HibernateUtil.rollbackTransaction();
        } catch (DotHibernateException e) {
          Logger.error(CMSMaintenanceFactory.class, e.getMessage());
        }
        Logger.debug(
            CMSMaintenanceFactory.class, "There was a problem deleting old asset versions", ex);
        Logger.warn(
            CMSMaintenanceFactory.class, "There  was a problem deleting old asset versions", ex);
        Logger.error(ViewCMSMaintenanceAction.class, ex.toString(), ex);
        if (counter > 0) {
          CacheLocator.getCacheAdministrator().flushAll();
        }
        return -1;
      } finally {
        try {
          HibernateUtil.commitTransaction();
        } catch (DotHibernateException e) {
          Logger.error(CMSMaintenanceFactory.class, e.getMessage());
          try {
            HibernateUtil.rollbackTransaction();
          } catch (DotHibernateException ex) {
            Logger.error(CMSMaintenanceFactory.class, e.getMessage());
          }
          Logger.debug(
              CMSMaintenanceFactory.class, "There was a problem deleting old asset versions", e);
          Logger.warn(
              CMSMaintenanceFactory.class, "There  was a problem deleting old asset versions", e);
          Logger.error(ViewCMSMaintenanceAction.class, e.toString(), e);
          if (counter > 0) {
            CacheLocator.getCacheAdministrator().flushAll();
          }
          return -1;
        }
      }
    }
    if (counter > 0) {
      CacheLocator.getCacheAdministrator().flushAll();
    }
    return counter;
  }
Ejemplo n.º 28
0
  public List<File> findFiles(
      User user,
      boolean includeArchived,
      Map<String, Object> params,
      String hostId,
      String inode,
      String identifier,
      String parent,
      int offset,
      int limit,
      String orderBy)
      throws DotSecurityException, DotDataException {

    PaginatedArrayList<File> assets = new PaginatedArrayList<File>();
    List<Permissionable> toReturn = new ArrayList<Permissionable>();
    int internalLimit = 500;
    int internalOffset = 0;
    boolean done = false;

    StringBuilder conditionBuffer =
        new StringBuilder().append(" asset.inode=versioninfo.workingInode ");
    String condition =
        !includeArchived ? " and versioninfo.deleted = " + DbConnectionFactory.getDBFalse() : " ";
    conditionBuffer.append(condition);

    List<Object> paramValues = null;
    if (params != null && params.size() > 0) {
      conditionBuffer.append(" and (");
      paramValues = new ArrayList<Object>();
      int counter = 0;
      for (Map.Entry<String, Object> entry : params.entrySet()) {
        if (counter == 0) {
          if (entry.getValue() instanceof String) {
            if (entry.getKey().equalsIgnoreCase("inode")) {
              conditionBuffer
                  .append(" asset.")
                  .append(entry.getKey())
                  .append(" = '")
                  .append(entry.getValue())
                  .append("'");
            } else {
              conditionBuffer.append(" lower(asset.").append(entry.getKey()).append(") like ? ");
              paramValues.add("%" + ((String) entry.getValue()).toLowerCase() + "%");
            }
          } else {
            conditionBuffer
                .append(" asset.")
                .append(entry.getKey())
                .append(" = ")
                .append(entry.getValue());
          }
        } else {
          if (entry.getValue() instanceof String) {
            if (entry.getKey().equalsIgnoreCase("inode")) {
              conditionBuffer
                  .append(" OR asset.")
                  .append(entry.getKey())
                  .append(" = '")
                  .append(entry.getValue())
                  .append("'");
            } else {
              conditionBuffer.append(" OR lower(asset.").append(entry.getKey()).append(") like ? ");
              paramValues.add("%" + ((String) entry.getValue()).toLowerCase() + "%");
            }
          } else {
            conditionBuffer
                .append(" OR asset.")
                .append(entry.getKey())
                .append(" = ")
                .append(entry.getValue());
          }
        }

        counter += 1;
      }
      conditionBuffer.append(" ) ");
    }

    StringBuilder query = new StringBuilder();
    query
        .append("select asset from asset in class ")
        .append(File.class.getName())
        .append(", ")
        .append("inode in class ")
        .append(Inode.class.getName())
        .append(", identifier in class ")
        .append(Identifier.class.getName())
        .append(", versioninfo in class ")
        .append(FileAssetVersionInfo.class.getName());
    if (UtilMethods.isSet(parent)) {
      query
          .append(" ,tree in class ")
          .append(Tree.class.getName())
          .append(" where asset.inode=inode.inode ")
          .append("and asset.identifier = identifier.id and tree.parent = '")
          .append(parent)
          .append("' and tree.child=asset.inode");

    } else {
      query.append(" where asset.inode=inode.inode and asset.identifier = identifier.id");
    }
    query.append(" and versioninfo.identifier=identifier.id ");
    if (UtilMethods.isSet(hostId)) {
      query.append(" and identifier.hostId = '").append(hostId).append("'");
    }
    if (UtilMethods.isSet(inode)) {
      query.append(" and asset.inode = '").append(inode).append("'");
    }
    if (UtilMethods.isSet(identifier)) {
      query.append(" and asset.identifier = '").append(identifier).append("'");
    }
    if (!UtilMethods.isSet(orderBy)) {
      orderBy = "modDate desc";
    }

    List<File> resultList = new ArrayList<File>();
    HibernateUtil dh = new HibernateUtil(File.class);
    String type;
    int countLimit = 100;
    int size = 0;
    try {
      type = ((Inode) File.class.newInstance()).getType();
      query.append(" and asset.type='").append(type).append("' ");
      final String conditions = conditionBuffer.toString().trim();
      if (conditions.length() > 0) query.append(" and ").append(conditions);
      query.append(" order by asset.").append(orderBy);
      dh.setQuery(query.toString());

      if (paramValues != null && paramValues.size() > 0) {
        for (Object value : paramValues) {
          dh.setParam((String) value);
        }
      }

      while (!done) {
        dh.setFirstResult(internalOffset);
        dh.setMaxResults(internalLimit);
        resultList = dh.list();
        PermissionAPI permAPI = APILocator.getPermissionAPI();
        toReturn.addAll(
            permAPI.filterCollection(resultList, PermissionAPI.PERMISSION_READ, false, user));
        if (countLimit > 0 && toReturn.size() >= countLimit + offset) done = true;
        else if (resultList.size() < internalLimit) done = true;

        internalOffset += internalLimit;
      }

      if (offset > toReturn.size()) {
        size = 0;
      } else if (countLimit > 0) {
        int toIndex = offset + countLimit > toReturn.size() ? toReturn.size() : offset + countLimit;
        size = toReturn.subList(offset, toIndex).size();
      } else if (offset > 0) {
        size = toReturn.subList(offset, toReturn.size()).size();
      }
      assets.setTotalResults(size);

      if (limit != -1) {
        int from = offset < toReturn.size() ? offset : 0;
        int pageLimit = 0;
        for (int i = from; i < toReturn.size(); i++) {
          if (pageLimit < limit) {
            assets.add((File) toReturn.get(i));
            pageLimit += 1;
          } else {
            break;
          }
        }
      } else {
        for (int i = 0; i < toReturn.size(); i++) {
          assets.add((File) toReturn.get(i));
        }
      }

    } catch (Exception e) {

      Logger.error(FileFactoryImpl.class, "findFiles failed:" + e, e);
      throw new DotRuntimeException(e.toString());
    }

    return assets;
  }
Ejemplo n.º 29
0
 protected void saveInode(Inode inode) throws DotDataException {
   HibernateUtil.save(inode);
 }
Ejemplo n.º 30
0
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.MSSQL)
        && LicenseUtil.getLevel() < 299) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (DbConnectionFactory.getDBType().equals(DbConnectionFactory.ORACLE)
        && LicenseUtil.getLevel() < 399) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    if (!LicenseUtil.isASAllowed()) {
      request.getRequestDispatcher("/portal/no_license.jsp").forward(request, response);
      return;
    }
    Long profileTime = null;
    if (Config.getBooleanProperty("VELOCITY_PROFILING", false)) {
      profileTime = Calendar.getInstance().getTimeInMillis();
    }
    try {

      // Check if the uri is a physical file. Fix for the cases when the
      // site configure VELOCITY_PAGE_EXTENSION as htm, html or any known
      // extension.
      // Example:
      // /html/js/tinymce/jscripts/tiny_mce/plugins/advlink/link.htm
      String uri = request.getRequestURI();
      uri = URLDecoder.decode(uri, "UTF-8");
      File file = new File(Config.CONTEXT.getRealPath(uri));
      if (file.exists()) {
        FileInputStream fileIS = new FileInputStream(file);
        ServletOutputStream servletOS = response.getOutputStream();
        int b;
        for (; -1 < (b = fileIS.read()); ) {
          servletOS.write(b);
        }
        fileIS.close();
        servletOS.flush();
        servletOS.close();
        return;
      }

      // If we are at a directory, e.g. /home
      // we need to redirect to /home/
      String forwardFor = (String) request.getRequestURL().toString();
      if (request.getAttribute(Globals.MAPPING_KEY) == null
          && forwardFor != null
          && !forwardFor.endsWith("/")
          && !forwardFor.endsWith("." + Config.getStringProperty("VELOCITY_PAGE_EXTENSION"))) {
        // The query string parameters should be preserved as well
        String queryString = request.getQueryString();
        response.sendRedirect(
            forwardFor + "/" + (UtilMethods.isSet(queryString) ? "?" + queryString : ""));
        return;
      }

      HttpSession session = request.getSession(false);
      boolean ADMIN_MODE =
          session != null
              && (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null);
      boolean PREVIEW_MODE =
          ADMIN_MODE
              && (session.getAttribute(com.dotmarketing.util.WebKeys.PREVIEW_MODE_SESSION) != null);
      boolean EDIT_MODE =
          ADMIN_MODE
              && (session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null);

      String value = request.getHeader("X-Requested-With");
      if ((value != null) && value.equals("XMLHttpRequest") && EDIT_MODE && ADMIN_MODE) {
        ADMIN_MODE = false;
      }

      // ### VALIDATE ARCHIVE ###
      if ((EDIT_MODE || PREVIEW_MODE) && isArchive(request)) {
        PREVIEW_MODE = true;
        EDIT_MODE = false;
        request.setAttribute("archive", true);
      }
      // ### END VALIDATE ARCHIVE ###

      LanguageWebAPI langWebAPI = WebAPILocator.getLanguageWebAPI();
      langWebAPI.checkSessionLocale(request);

      if (PREVIEW_MODE && ADMIN_MODE) {
        // preview mode has the left hand menu and edit buttons on the
        // working page

        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON PREVIEW MODE!!!");

        doPreviewMode(request, response);
      } else if (EDIT_MODE && ADMIN_MODE) {
        // edit mode has the left hand menu and edit buttons on the
        // working page

        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON EDIT MODE!!!");

        doEditMode(request, response);
      } else if (ADMIN_MODE) {
        // admin mode has the left hand menu and shows the live page in
        // the frame
        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON ADMIN MODE!!!");

        doAdminMode(request, response);
      } else {
        // live mode has no frame and shows the live page
        Logger.debug(VelocityServlet.class, "VELOCITY SERVLET I'M ON LIVE MODE!!!");

        doLiveMode(request, response);
      }

    } catch (ResourceNotFoundException rnfe) {

      // response.sendError(404);
      request.setAttribute(Constants.SERVE_URL, request.getRequestURI());
      request.getRequestDispatcher("/localResourceServlet").forward(request, response);

    } catch (ParseErrorException pee) {
      Logger.error(this, "Template Parse Exception : " + pee.toString(), pee);
      try {
        response.sendError(500, "Template Parse Exception");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println("Template Parse Exception");
        out.println("On template:" + request.getRequestURI() + request.getQueryString());
      }

    } catch (MethodInvocationException mie) {
      Logger.error(this, "MethodInvocationException" + mie.toString(), mie);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println(
            "MethodInvocationException Error on template:"
                + request.getRequestURI()
                + request.getQueryString());
      }
    } catch (Exception e) {
      Logger.error(this, e.toString(), e);
      try {
        response.sendError(500, "MethodInvocationException Error on template");
      } catch (Throwable t) {
        Logger.error(this, t.getMessage(), t);
        PrintWriter out = response.getWriter();
        out.println("Error on template:" + request.getRequestURI() + request.getQueryString());
      }
    } finally {
      // catchall
      // added finally because of
      // http://jira.dotmarketing.net/browse/DOTCMS-1334
      try {
        HibernateUtil.commitTransaction();
      } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
      }
      DbConnectionFactory.closeConnection();
    }
    if (profileTime != null) {
      profileTime = Calendar.getInstance().getTimeInMillis() - profileTime;
      VelocityProfiler.log(
          VelocityServlet.class,
          "VelocityPage time: " + request.getRequestURL() + " " + profileTime + " millis");
    }
  }