Package com.dotmarketing.portlets.contentlet.model

Examples of com.dotmarketing.portlets.contentlet.model.Contentlet


        tmp.delete();
        tmp.mkdirs();
        tmp = new java.io.File(tmp,filename);
        FileUtils.writeStringToFile(tmp, "this is a test text");
       
        Contentlet file = new Contentlet();
        file.setStringProperty(FileAssetAPI.FILE_NAME_FIELD, filename);
        file.setStringProperty(FileAssetAPI.TITLE_FIELD, filename);
        file.setStringProperty(FileAssetAPI.HOST_FOLDER_FIELD,hostid);
        file.setBinary(FileAssetAPI.BINARY_FIELD, tmp);
        file.setStructureInode(StructureCache.getStructureByVelocityVarName("fileAsset").getInode());
        file.setLanguageId(1);
        file.setHost(hostid);
        file.setFolder("SYSTEM_FOLDER");
        file = APILocator.getContentletAPI().checkin(file, user, false);
        APILocator.getContentletAPI().isInodeIndexed(file.getInode());
       
       
        final HttpServletRequest req=ServletTestRunner.localRequest.get();
        Host hh=new Host(req.getServerName(),"/webdav/autopub",req.getServerPort(),"admin@dotcms.com","admin",null,null);
       
        Folder demo=(Folder)hh.child("demo.dotcms.com");
        File f1=(File)demo.child(filename);
        f1.delete();
       
        for(Resource rr: demo.children()) {
            if(rr instanceof File) {
                Assert.assertNotSame(filename, ((File)rr).name);
            }
        }
       
        ContentletVersionInfo vi = APILocator.getVersionableAPI().getContentletVersionInfo(file.getIdentifier(), 1);
        Assert.assertTrue(vi.isDeleted());
  }
View Full Code Here


        tmp.delete();
        tmp.mkdirs();
        tmp = new java.io.File(tmp,filename);
        FileUtils.writeStringToFile(tmp, "this is a test text");
       
        Contentlet file = new Contentlet();
        file.setStringProperty(FileAssetAPI.FILE_NAME_FIELD, filename);
        file.setStringProperty(FileAssetAPI.TITLE_FIELD, filename);
        file.setStringProperty(FileAssetAPI.HOST_FOLDER_FIELD,hostid);
        file.setBinary(FileAssetAPI.BINARY_FIELD, tmp);
        file.setStructureInode(StructureCache.getStructureByVelocityVarName("fileAsset").getInode());
        file.setLanguageId(1);
        file.setHost(hostid);
        file.setFolder("SYSTEM_FOLDER");
        file = APILocator.getContentletAPI().checkin(file, user, false);
        APILocator.getContentletAPI().isInodeIndexed(file.getInode());
       
       
        final HttpServletRequest req=ServletTestRunner.localRequest.get();
        Host hh=new Host(req.getServerName(),"/webdav/autopub",req.getServerPort(),"admin@dotcms.com","admin",null,null);
       
View Full Code Here

    }
        p = p.substring(5, p.lastIndexOf("."));
        IFileAsset file = null;
    try {
      if(id!=null && InodeUtils.isSet(id.getId()) && id.getAssetType().equals("contentlet")){
        Contentlet cont = APILocator.getContentletAPI().findContentletByIdentifier(id.getId(), true, APILocator.getLanguageAPI().getDefaultLanguage().getId(), APILocator.getUserAPI().getSystemUser(), false);
        if(cont!=null && InodeUtils.isSet(cont.getInode())){
          file = APILocator.getFileAssetAPI().fromContentlet(cont);
        }
      }else{
        file = fileAPI.find(p, userAPI.getSystemUser(), false);
      }
View Full Code Here

      if (request.getSession().getAttribute(WebKeys.CMS_USER) != null) {
        user = (User) request.getSession().getAttribute(WebKeys.CMS_USER);
      }
      String userId = user.getUserId();
      // Contentlet Data
      Contentlet contentlet = new Contentlet();
      try{
        contentlet = conAPI.find(commentsOptions.get("contentInode"), user, true);
      }catch(DotDataException e){
        Logger.error(this, "Unable to look up comment with inode " + commentsOptions.get("contentInode"), e);
      }

      Structure contentletStructure = StructureCache.getStructureByInode(contentlet.getStructureInode());
      Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

      /*make sure we have a structure in place before saving */
      CommentsWebAPI cAPI = new CommentsWebAPI();
      cAPI.validateComments(contentlet.getInode());

      Structure commentsStructure = StructureCache.getStructureByVelocityVarName(CommentsWebAPI.commentsVelocityStructureName);

      Contentlet contentletComment = new Contentlet();

      // set the default language
      com.dotmarketing.portlets.contentlet.business.Contentlet beanContentlet = (com.dotmarketing.portlets.contentlet.business.Contentlet) InodeFactory.getInode(contentlet.getInode(), com.dotmarketing.portlets.contentlet.business.Contentlet.class);

      contentletComment.setLanguageId(beanContentlet.getLanguageId());

      // Add the default fields
      contentletComment.setStructureInode(commentsStructure.getInode());

      Field field;

      /* Set the title if we have one*/
      if(UtilMethods.isSet(commentsOptions.get("commentTitle"))){

        field = commentsStructure.getFieldVar("title");

        conAPI.setContentletProperty(contentletComment, field, commentsOptions.get("commentTitle"));
      }

      /* Validate if a CommentsCount field exists in the contentlet structure
         if not, then create it and populate it.*/

      field = contentletStructure.getFieldVar("commentscount");
      if (field==null || !InodeUtils.isSet(field.getInode())) {
        List<Field> fields = new ArrayList<Field>();
          field = new Field("CommentsCount", Field.FieldType.TEXT, Field.DataType.INTEGER, contentletStructure,
                      false, false, true, Integer.MAX_VALUE, "0", "0", "",true, true, true);
        FieldFactory.saveField(field);
        for(Field structureField: contentletStructure.getFields()){
          fields.add(structureField);
        }
        fields.add(field);
        FieldsCache.removeFields(contentletStructure);
        FieldsCache.addFields(contentletStructure,fields);
      }

      /* Get the  value from the CommentsCount field for this contentlet, if the value
       * is null, then the contentlet has no comments, otherwise increment its value by one
       * and set it to the contentlet.
       */
     
      String velVar = field.getVelocityVarName();

      int comentsCount = -1;
      try {
        Long countValue = contentlet.getLongProperty(velVar);
        comentsCount  = countValue.intValue();
      } catch (Exception e) {
        Logger.debug(this, e.toString());
      }

      if (comentsCount == -1) {
        try {
          String countValue = (contentlet.getStringProperty(velVar) ==  null) ? field.getDefaultValue() : contentlet.getStringProperty(velVar);
          comentsCount  = countValue.equals("") ? 0 : new Integer(countValue).intValue();
        } catch (Exception e) {
          Logger.debug(this, e.toString());
        }
      }

      ++comentsCount;
      conAPI.setContentletProperty(contentlet, field, comentsCount);
      //Update the contentlet with the new comment count
      /*List<Category> cats = catAPI.getParents(contentlet, user, true);
      Map<Relationship, List<Contentlet>> contentRelationships = new HashMap<Relationship, List<Contentlet>>();

      List<Relationship> rels = RelationshipFactory.getAllRelationshipsByStructure(contentlet.getStructure());
      for (Relationship r : rels) {
        if(!contentRelationships.containsKey(r)){
          contentRelationships.put(r, new ArrayList<Contentlet>());
        }
        List<Contentlet> cons = conAPI.getRelatedContent(contentlet, r, user, true);
        for (Contentlet co : cons) {
          List<Contentlet> l2 = contentRelationships.get(r);
          l2.add(co);
        }
      }
      conAPI.checkinWithoutVersioning(contentlet, contentRelationships, cats, APILocator.getPermissionAPI().getPermissions(contentlet), user, true);
            */
      // Date
      field = commentsStructure.getFieldVar("datePublished");
      conAPI.setContentletProperty(contentletComment, field, new Date());

      // User Id
      field = commentsStructure.getFieldVar("userid");
      conAPI.setContentletProperty(contentletComment, field, userId);

      // Author
      field = commentsStructure.getFieldVar("author");
      conAPI.setContentletProperty(contentletComment, field, VelocityUtil.cleanVelocity(commentsForm.getName()));

      // Email
      field = commentsStructure.getFieldVar("email");
      conAPI.setContentletProperty(contentletComment, field, VelocityUtil.cleanVelocity(commentsForm.getEmail()));

      // WebSite
      field = commentsStructure.getFieldVar("website");
      conAPI.setContentletProperty(contentletComment, field, VelocityUtil.cleanVelocity(commentsForm.getWebsite()));

      // EmailResponse
      field = commentsStructure.getFieldVar("emailResponse");
      conAPI.setContentletProperty(contentletComment, field, (commentsForm.isNotify()?"yes":"no"));

      // IP Address
      field = commentsStructure.getFieldVar("ipAddress");
      conAPI.setContentletProperty(contentletComment, field, request.getRemoteAddr());

      // Comment
      field = commentsStructure.getFieldVar("comment");
      String comment = commentsForm.getComment();
      comment=VelocityUtil.cleanVelocity(comment);


      if (UtilMethods.isSet(commentsOptions.get("commentStripHtml")) && commentsOptions.get("commentStripHtml").equalsIgnoreCase("true")) {
        comment = Html.stripHtml(comment);
      }

      conAPI.setContentletProperty(contentletComment, field, comment);

      // Add the permission
      PermissionAPI perAPI = APILocator.getPermissionAPI();
      List<Permission> pers = perAPI.getPermissions(commentsStructure);




      // new workflows
      if(UtilMethods.isSet(commentsOptions.get("commentsModeration"))){
        if(!UtilMethods.isSet(contentletComment.getStringProperty(Contentlet.WORKFLOW_ACTION_KEY)))
            contentletComment.setStringProperty(Contentlet.WORKFLOW_ACTION_KEY, APILocator.getWorkflowAPI().findEntryAction(contentletComment, user).getId());
        contentletComment.setStringProperty(Contentlet.WORKFLOW_COMMENTS_KEY, commentsForm.getComment());
      }






      // Save the comment
      contentletComment = conAPI.checkin(contentletComment, new HashMap<Relationship, List<Contentlet>>(), new ArrayList<Category>(), pers, user, true);

            // If live I have to publish the asset
            if (UtilMethods.isSet(commentsOptions.get("commentAutoPublish")) && commentsOptions.get("commentAutoPublish").equalsIgnoreCase("true")) {
                APILocator.getVersionableAPI().setLive(contentletComment);
            }

      // Set the relation between the content and the comments
      Identifier contentletCommentIdentifier = APILocator.getIdentifierAPI().find(contentletComment);
      String commentRelationStructureName = commentsStructure.getName().replaceAll("\\s", "_").replaceAll("[^a-zA-Z0-9\\_]", "");
      String contentletRelationStructureName = contentletStructure.getName().replaceAll("\\s", "_").replaceAll("[^a-zA-Z0-9\\_]", "");
      String relationName = contentletRelationStructureName + "-" + commentRelationStructureName;


      /* get the next in the order */
      int order  = RelationshipFactory.getMaxInSortOrder(contentletIdentifier.getInode(), relationName);


      contentletIdentifier.addChild(contentletCommentIdentifier, relationName, ++order);

      ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.comment.success"));

      /* If the comment has been sennt successfully, activeDiv is set to its initial value*/
      commentsForm.setActiveDiv("");









      beanContentlet = (com.dotmarketing.portlets.contentlet.business.Contentlet) InodeFactory.getInode(contentletComment.getInode(), com.dotmarketing.portlets.contentlet.business.Contentlet.class);
      beanContentlet = conAPI.convertContentletToFatContentlet(contentletComment, beanContentlet);
      HibernateUtil.saveOrUpdate(beanContentlet);

      if (UtilMethods.isSet(commentsOptions.get("commentAutoPublish")) && commentsOptions.get("commentAutoPublish").equalsIgnoreCase("true"))
      {
        conAPI.publish(contentletComment, user, true);
      }


      saveMessages(request, ae);
      saveMessages(request.getSession(), ae);
      String referrer = UtilMethods.isSet(commentsOptions.get("referrer"))?commentsOptions.get("referrer"):"";
      referrer = (referrer.indexOf("#comments") == -1 ? referrer + "#comments" : referrer);

      String commentQuestion = commentsOptions.get("commentTitle");

      //The send comment emails should be send when there is a new comment (ALWAYS)
      String userName = commentsForm.getName();
      String userEmail = commentsForm.getEmail();
      String userComment = commentsForm.getComment();
      HibernateUtil.commitTransaction();
      if(!conAPI.isInodeIndexed(contentletComment.getInode())){
        Logger.error(this, "Problem indexing comment content");
      }
      sendCommentEmails(contentletIdentifier, relationName, request, referrer,userName,userEmail,userComment,commentQuestion, commentsOptions);

      ActionForward forward = new ActionForward(referrer);
View Full Code Here

        try{
            ica = new InternalContextAdapterImpl(ctx);
            String fieldResourceName = ica.getCurrentTemplateName();
            String conInode = fieldResourceName.substring(fieldResourceName.indexOf("/") + 1, fieldResourceName.indexOf("_"));

            Contentlet con = APILocator.getContentletAPI().find(conInode, APILocator.getUserAPI().getSystemUser(), true);

            User mu = userAPI.loadUserById(con.getModUser(), APILocator.getUserAPI().getSystemUser(), true);
            Role scripting =APILocator.getRoleAPI().loadRoleByKey("Scripting Developer");
            return APILocator.getRoleAPI().doesUserHaveRole(mu, scripting);
    }
    catch(Exception e){
      Logger.warn(this.getClass(), "Scripting called with error" + e);
View Full Code Here

          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet = permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user, true);

            context.put("EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(), new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
View Full Code Here

                    int count = 0;

                    while ( iter.hasNext() && (count < c.getMaxContentlets()) ) {
                        count++;

                        Contentlet contentlet = (Contentlet) iter.next();
                        Identifier contentletIdentifier = APILocator.getIdentifierAPI().find( contentlet );

                        boolean hasWritePermOverContentlet = permissionAPI.doesUserHavePermission( contentlet, PERMISSION_WRITE, backendUser );

                        context.put( "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(), new Boolean( hasWritePermOverContentlet ) );

                        contentletList.add( String.valueOf( contentletIdentifier.getInode() ) );
                        Logger.debug( this, "Adding contentlet=" + contentletIdentifier.getInode() );
                        Structure contStructure = contentlet.getStructure();
                        if ( contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET ) {
                            Field field = contStructure.getFieldVar( "widgetPreexecute" );
                            if ( field != null && UtilMethods.isSet( field.getValues() ) ) {
                                preExecuteCode.append( field.getValues().trim() + "\n" );
                                widgetPreExecute = true;
View Full Code Here

        resp.sendError(404);
        return;
      }

      if (isContent){
        Contentlet content = null;
        if(byInode) {
          if(isTempBinaryImage)
            content = contentAPI.find(assetInode, APILocator.getUserAPI().getSystemUser(), respectFrontendRoles);
          else
            content = contentAPI.find(assetInode, user, respectFrontendRoles);
          assetIdentifier = content.getIdentifier();
        } else {
            boolean live=userWebAPI.isLoggedToFrontend(req);
            if (req.getSession(false) != null && req.getSession().getAttribute("tm_date")!=null) {
                live=true;
                Identifier ident=APILocator.getIdentifierAPI().find(assetIdentifier);
                if(UtilMethods.isSet(ident.getSysPublishDate()) || UtilMethods.isSet(ident.getSysExpireDate())) {
                    Date fdate=new Date(Long.parseLong((String)req.getSession().getAttribute("tm_date")));
                    if(UtilMethods.isSet(ident.getSysPublishDate()) && ident.getSysPublishDate().before(fdate))
                        live=false;
                    if(UtilMethods.isSet(ident.getSysExpireDate()) && ident.getSysExpireDate().before(fdate))
                        return; // expired!
                }
            }
          content = contentAPI.findContentletByIdentifier(assetIdentifier, live, lang, user, respectFrontendRoles);
          assetInode = content.getInode();
        }
        Field field = content.getStructure().getFieldVar(fieldVarName);
        if(field == null){
          Logger.debug(this,"Field " + fieldVarName + " does not exists within structure " + content.getStructure().getVelocityVarName());
          resp.sendError(404);
          return;
        }

        if(isTempBinaryImage)
          inputFile = contentAPI.getBinaryFile(content.getInode(), field.getVelocityVarName(), APILocator.getUserAPI().getSystemUser());
        else
          inputFile = contentAPI.getBinaryFile(content.getInode(), field.getVelocityVarName(), user);
        if(inputFile == null){
          Logger.debug(this,"binary file '" + fieldVarName + "' does not exist for inode " + content.getInode());
          resp.sendError(404);
          return;
        }
        downloadName = inputFile.getName();
      }
View Full Code Here

    }


    if(byInode){
      try {
        Contentlet c =APILocator.getContentletAPI().find(id, userAPI.getSystemUser(), true);
        if(c != null && c.getInode() != null)
          return true;
      } catch (Exception e) {
        Logger.debug(this.getClass(), "Unable to find contentlet " + id);
      }
      try {
        if(fileAPI.find(id,userAPI.getSystemUser(),false) != null){
          return false;
        }
      } catch (DotHibernateException e) {
        Logger.debug(this.getClass(), "cant find file with inode " + id);
      }
    }

    else{
      try {

        Identifier identifier = APILocator.getIdentifierAPI().loadFromCache(id);
        if(identifier != null){
          return "contentlet".equals(identifier.getAssetType());
        }

        //second check content check from lucene
        String luceneQuery = "+identifier:" + id;
        Contentlet c = APILocator.getContentletAPI().findContentletByIdentifier(id, false,langId, userAPI.getSystemUser(), false);
        if(c != null && UtilMethods.isSet(c.getInode())){
          return true;
        }

      } catch (Exception e) {
        Logger.debug(this.getClass(), "cant find identifier " + id);
View Full Code Here

            }
            try {
                //Integer.parseInt(x);
                //Identifier identifier = (Identifier) InodeFactory.getInode(x, Identifier.class);
              Identifier identifier = APILocator.getIdentifierAPI().find(x);
                Contentlet contentlet = null;
                if(CacheLocator.getVeloctyResourceCache().isMiss(arg0)){
                  if(LanguageWebAPI.canDefaultContentToDefaultLanguage()) {
                     LanguageAPI langAPI = APILocator.getLanguageAPI();
                     language = Long.toString(langAPI.getDefaultLanguage().getId());
                  } else {
                    throw new ResourceNotFoundException("Contentlet is a miss in the cache");
                  }
              }
               
                try {
                  contentlet = conAPI.findContentletByIdentifier(identifier.getInode(), !preview,new Long(language) , APILocator.getUserAPI().getSystemUser(), true);
                } catch (DotContentletStateException e) {
                    contentlet = null;
                }
               
                if(contentlet == null || !InodeUtils.isSet(contentlet.getInode()) || contentlet.isArchived()){
                   
                    LanguageAPI langAPI = APILocator.getLanguageAPI();
                    long lid = langAPI.getDefaultLanguage().getId();
                    if(lid!=Long.parseLong(language)) {
                        Contentlet cc = conAPI.findContentletByIdentifier(identifier.getInode(), !preview,lid , APILocator.getUserAPI().getSystemUser(), true);
                        if(cc!=null && UtilMethods.isSet(cc.getInode())
                                 && !cc.isArchived() && LanguageWebAPI.canApplyToAllLanguages(cc)) {
                            contentlet = cc;
                        } else {
                            CacheLocator.getVeloctyResourceCache().addMiss(arg0);
                            throw new ResourceNotFoundException("Contentlet is a miss in the cache");
                        }
                    }
                }

                Logger.debug(this,"DotResourceLoader:\tWriting out contentlet inode = " + contentlet.getInode());

                result = ContentletServices.buildVelocity(contentlet, identifier, preview);
            } catch (NumberFormatException e) {
                Logger.warn(this,"getResourceStream: Invalid resource path provided = " + arg0 + ", request discarded.");
                try {
            return new ByteArrayInputStream("".getBytes("UTF-8"));
          } catch (UnsupportedEncodingException e1) {
            Logger.error(DotResourceLoader.class,e1.getMessage(),e1);
          }
            } catch (DotContentletStateException e) {
              CacheLocator.getVeloctyResourceCache().addMiss(arg0);
                Logger.debug(this,"getResourceStream: Invalid resource path provided = " + arg0 + ", request discarded.");
                try {
            return new ByteArrayInputStream("".getBytes("UTF-8"));
          } catch (UnsupportedEncodingException e1) {
            Logger.error(DotResourceLoader.class,e1.getMessage(),e1);
          }
            }
        }else if (arg0.endsWith(VELOCITY_FIELD_EXTENSION)) {
          //long contentletInode;
          //long fieldInode;
          if (x.indexOf("_") > -1) {
            String fieldID = x.substring(x.indexOf("_") + 1, x.length());
            String conInode = x.substring(0,x.indexOf("_"));
            //contentletInode = Integer.parseInt(conInode);
            //fieldInode = Integer.parseInt(fieldID);
            result = FieldServices.buildVelocity(fieldID, conInode, preview);
          }

        }else if (arg0.endsWith(VELOCITY_CONTENT_MAP_EXTENSION)) {
            try {
              String language = "";
              if (x.indexOf("_") > -1) {
                  Logger.debug(this,"x=" + x);
                  language = x.substring(x.indexOf("_") + 1, x.length());
                  Logger.debug(this,"language=" + language);
                  x = x.substring(0, x.indexOf("_"));
                  Logger.debug(this,"x=" + x);
              }

              Contentlet contentlet = null;
              if(CacheLocator.getVeloctyResourceCache().isMiss(arg0)){
                throw new ResourceNotFoundException("Contentlet is a miss in the cache");
              }
             
              try {
                  contentlet = conAPI.findContentletByIdentifier(new String(x), !preview,new Long(language) , APILocator.getUserAPI().getSystemUser(), true);
              }
              catch(Exception ex) {
                  contentlet = null;
              }
             
              if(contentlet == null || !InodeUtils.isSet(contentlet.getInode())){
                  CacheLocator.getVeloctyResourceCache().addMiss(arg0);
                  throw new ResourceNotFoundException("Contentlet is a miss in the cache");
                }

              Logger.debug(this,"DotResourceLoader:\tWriting out contentlet inode = " + contentlet.getInode());

              result = ContentletMapServices.buildVelocity(contentlet, preview);
            } catch (DotContentletStateException e) {
              CacheLocator.getVeloctyResourceCache().addMiss(arg0);
                Logger.debug(this,"getResourceStream: Invalid resource path provided = " + arg0 + ", request discarded.");
View Full Code Here

TOP

Related Classes of com.dotmarketing.portlets.contentlet.model.Contentlet

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.