Example #1
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;
  }
Example #2
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;
  }
Example #3
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;
  }
Example #4
0
 public void deleteFromCache(File file)
     throws DotDataException, DotStateException, DotSecurityException {
   fileCache.remove(file);
   WorkingCache.removeAssetFromCache(file);
   if (file.isLive()) {
     LiveCache.removeAssetFromCache(file);
   }
   CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);
 }
Example #5
0
  /**
   * Moves a file into the given directory OR host
   *
   * @param file File to be moved
   * @param parent Destination Folder
   * @param host Destination Host
   * @return true if move success, false otherwise
   * @throws DotDataException
   * @throws DotStateException
   * @throws DotSecurityException
   */
  private Boolean moveFile(File file, Folder parent, Host host)
      throws DotStateException, DotDataException, DotSecurityException {

    HostAPI hostAPI = APILocator.getHostAPI();

    // Find file identifier
    Identifier identifier = com.dotmarketing.business.APILocator.getIdentifierAPI().find(file);

    // gets working container
    File workingWebAsset =
        (File)
            APILocator.getVersionableAPI()
                .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);
    // gets live container
    File liveWebAsset =
        (File)
            APILocator.getVersionableAPI()
                .findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false);

    // checks if another identifer with the same name exists in the same
    Boolean fileNameExists;
    if (parent != null) {
      fileNameExists = fileNameExists(parent, file.getFileName());
    } else {
      fileNameExists =
          fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName());
    }
    if (fileNameExists) {
      return false;
    }

    // assets cache
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
      LiveCache.removeAssetFromCache(liveWebAsset);
    }
    WorkingCache.removeAssetFromCache(workingWebAsset);

    // gets old parent
    Folder oldParent =
        APILocator.getFolderAPI()
            .findParentFolder(workingWebAsset, APILocator.getUserAPI().getSystemUser(), false);

    /*oldParent.deleteChild(workingWebAsset);
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
        oldParent.deleteChild(liveWebAsset);
    }
    //add new Parent
    parent.addChild(workingWebAsset);
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
        parent.addChild(liveWebAsset);
    }*/

    // gets identifier for this webasset and changes the uri and persists it
    User systemUser;
    try {
      systemUser = APILocator.getUserAPI().getSystemUser();
      if (host == null) {
        host = hostAPI.findParentHost(parent, systemUser, false);
      }
    } catch (DotDataException e) {
      Logger.error(FileFactory.class, e.getMessage(), e);
      throw new DotRuntimeException(e.getMessage(), e);

    } catch (DotSecurityException e) {
      Logger.error(FileFactory.class, e.getMessage(), e);
      throw new DotRuntimeException(e.getMessage(), e);
    }
    identifier.setHostId(host.getIdentifier());
    identifier.setURI(parent != null ? workingWebAsset.getURI(parent) : workingWebAsset.getURI());
    // HibernateUtil.saveOrUpdate(identifier);
    APILocator.getIdentifierAPI().save(identifier);

    if (UtilMethods.isSet(liveWebAsset))
      CacheLocator.getIdentifierCache().removeFromCacheByVersionable(liveWebAsset);
    //		IdentifierCache.addAssetToIdentifierCache(liveWebAsset);

    // Add to Preview and Live Cache
    if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) {
      LiveCache.removeAssetFromCache(liveWebAsset);
      LiveCache.addToLiveAssetToCache(liveWebAsset);
    }
    WorkingCache.removeAssetFromCache(workingWebAsset);
    WorkingCache.addToWorkingAssetToCache(workingWebAsset);

    if (file.isShowOnMenu()) {
      // existing folder with different show on menu ... need to regenerate menu
      if (parent != null) {
        RefreshMenus.deleteMenu(oldParent, parent);
        CacheLocator.getNavToolCache().removeNav(parent.getHostId(), parent.getInode());
      } else {
        RefreshMenus.deleteMenu(oldParent);
      }
      CacheLocator.getNavToolCache().removeNav(oldParent.getHostId(), oldParent.getInode());
    }

    return true;
  }
Example #6
0
  public void doLiveMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration());
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    // Map with all identifier inodes for a given uri.
    String idInode = APILocator.getIdentifierAPI().find(host, uri).getInode();

    // Checking the path is really live using the livecache
    String cachedUri = LiveCache.getPathFromCache(uri, host);

    // if we still have nothing.
    if (!InodeUtils.isSet(idInode) || cachedUri == null) {
      throw new ResourceNotFoundException(
          String.format("Resource %s not found in Live mode!", uri));
    }

    response.setContentType(CHARSET);

    request.setAttribute("idInode", String.valueOf(idInode));
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + idInode);

    /*
     * JIRA http://jira.dotmarketing.net/browse/DOTCMS-4659
    //Set long lived cookie regardless of who this is */
    String _dotCMSID =
        UtilMethods.getCookieValue(
            request.getCookies(), com.dotmarketing.util.WebKeys.LONG_LIVED_DOTCMS_ID_COOKIE);

    if (!UtilMethods.isSet(_dotCMSID)) {
      // create unique generator engine
      Cookie idCookie = CookieUtil.createCookie();
      response.addCookie(idCookie);
    }

    com.liferay.portal.model.User user = null;
    HttpSession session = request.getSession(false);
    try {
      if (session != null)
        user =
            (com.liferay.portal.model.User)
                session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying to getUser: "******"Page Permissions for URI=" + uri);

    HTMLPage page = null;
    try {
      // we get the page and check permissions below
      page =
          APILocator.getHTMLPageAPI()
              .loadLivePageById(idInode, APILocator.getUserAPI().getSystemUser(), false);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return;
    }

    // Check if the page is visible by a CMS Anonymous role
    if (!permissionAPI.doesUserHavePermission(page, PERMISSION_READ, user, true)) {
      // this page is protected. not anonymous access

      /**
       * ***************************************************************** If we need to redirect
       * someone somewhere to login before seeing a page, we need to edit the /portal/401.jsp page
       * to sendRedirect the user to the proper login page. We are not using the REDIRECT_TO_LOGIN
       * variable in the config any longer.
       * ****************************************************************
       */
      if (!signedIn) {
        // No need for the below LAST_PATH attribute on the front end
        // http://jira.dotmarketing.net/browse/DOTCMS-2675
        // request.getSession().setAttribute(WebKeys.LAST_PATH,
        // new ObjectValuePair(uri, request.getParameterMap()));
        request.getSession().setAttribute(com.dotmarketing.util.WebKeys.REDIRECT_AFTER_LOGIN, uri);

        Logger.debug(
            VelocityServlet.class,
            "VELOCITY CHECKING PERMISSION: Page doesn't have anonymous access" + uri);

        Logger.debug(VelocityServlet.class, "401 URI = " + uri);

        Logger.debug(VelocityServlet.class, "Unauthorized URI = " + uri);
        response.sendError(401, "The requested page/file is unauthorized");
        return;

      } else if (!permissionAPI
          .getReadRoles(ident)
          .contains(APILocator.getRoleAPI().loadLoggedinSiteRole())) {
        // user is logged in need to check user permissions
        Logger.debug(VelocityServlet.class, "VELOCITY CHECKING PERMISSION: User signed in");

        // check user permissions on this asset
        if (!permissionAPI.doesUserHavePermission(ident, PERMISSION_READ, user, true)) {
          // the user doesn't have permissions to see this page
          // go to unauthorized page
          Logger.warn(
              VelocityServlet.class,
              "VELOCITY CHECKING PERMISSION: Page doesn't have any access for this user");
          response.sendError(403, "The requested page/file is forbidden");
          return;
        }
      }
    }

    Logger.debug(VelocityServlet.class, "Recording the ClickStream");
    if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) {
      if (user != null) {
        UserProxy userProxy =
            com.dotmarketing.business.APILocator.getUserProxyAPI()
                .getUserProxy(user, APILocator.getUserAPI().getSystemUser(), false);
        if (!userProxy.isNoclicktracking()) {
          ClickstreamFactory.addRequest(
              (HttpServletRequest) request, ((HttpServletResponse) response), host);
        }
      } else {
        ClickstreamFactory.addRequest(
            (HttpServletRequest) request, ((HttpServletResponse) response), host);
      }
    }

    // Begin Page Caching
    boolean buildCache = false;
    String key = getPageCacheKey(request);
    if (key != null) {

      String cachedPage = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL());

      if (cachedPage == null
          || "refresh".equals(request.getParameter("dotcache"))
          || "refresh".equals(request.getAttribute("dotcache"))
          || "refresh".equals(request.getSession().getAttribute("dotcache"))) {
        // build cached response
        buildCache = true;
      } else {
        // have cached response and are not refreshing, send it
        response.getWriter().write(cachedPage);
        return;
      }
    }

    Writer out =
        (buildCache) ? new StringWriter(4096) : new VelocityFilterWriter(response.getWriter());

    // get the context from the requst if possible
    Context context = VelocityUtil.getWebContext(request, response);

    request.setAttribute("velocityContext", context);
    Logger.debug(VelocityServlet.class, "HTMLPage Identifier:" + idInode);

    try {

      VelocityUtil.getEngine()
          .getTemplate("/live/" + idInode + "." + VELOCITY_HTMLPAGE_EXTENSION)
          .merge(context, out);

    } catch (ParseErrorException e) {
      // out.append(e.getMessage());
    }

    context = null;
    if (buildCache) {
      String trimmedPage = out.toString().trim();
      response.getWriter().write(trimmedPage);
      response.getWriter().close();
      synchronized (key) {
        String x = CacheLocator.getBlockDirectiveCache().get(key, (int) page.getCacheTTL());
        if (x != null) {
          return;
        }
        CacheLocator.getBlockDirectiveCache()
            .add(getPageCacheKey(request), trimmedPage, (int) page.getCacheTTL());
      }
    } else {
      out.close();
    }
  }