Package com.dotmarketing.portlets.contentlet.business

Examples of com.dotmarketing.portlets.contentlet.business.ContentletAPI


   * @param contentlets
   * @throws DotSecurityException
   * @throws DotDataException
   */
  public static void removeContentletMapFile(Structure structure) throws DotDataException, DotSecurityException{
    ContentletAPI conAPI=APILocator.getContentletAPI();
    int limit=500;
    int offset=0;
    List<Contentlet> contentlets=conAPI.findByStructure(structure, APILocator.getUserAPI().getSystemUser(), false, limit, offset);
    int size=contentlets.size();
    while(size > 0){
      for (Contentlet contentlet : contentlets) {
        removeContentletMapFile(contentlet);
      }
      offset += limit;
      contentlets=conAPI.findByStructure(structure, APILocator.getUserAPI().getSystemUser(), false, limit, offset);
      size=contentlets.size();
    }
  }
View Full Code Here


      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    UserWebAPI userWebAPI = WebAPILocator.getUserWebAPI();
    ContentletAPI contentAPI = APILocator.getContentletAPI();
    BinaryContentExporter.BinaryContentExporterData data = null;
    File inputFile = null;
    HttpSession session = req.getSession(false);
    List<String> tempBinaryImageInodes = null;
        if ( session != null && session.getAttribute( Contentlet.TEMP_BINARY_IMAGE_INODES_LIST ) != null ) {
            tempBinaryImageInodes = (List<String>) session.getAttribute( Contentlet.TEMP_BINARY_IMAGE_INODES_LIST );
        } else {
            tempBinaryImageInodes = new ArrayList<String>();
        }

        boolean isTempBinaryImage = tempBinaryImageInodes.contains(assetInode);
    try {
      User user = userWebAPI.getLoggedInUser(req);
      boolean respectFrontendRoles = !userWebAPI.isLoggedToBackend(req);
      String downloadName = "file_asset";
      long lang = APILocator.getLanguageAPI().getDefaultLanguage().getId();
      try {
        String x = null;
        if (session != null) {
          x = (String) session.getAttribute(WebKeys.HTMLPAGE_LANGUAGE);
        } else {
          x = (String) req.getAttribute(WebKeys.HTMLPAGE_LANGUAGE);
        }
        lang = Long.parseLong(x);
      } catch(Exception e){
        // Number parsing exception
      }

      boolean isContent = false;
      try {
        isContent = isContent(uuid, byInode, lang, respectFrontendRoles);
      }catch (DotStateException e) {
        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;
        }
View Full Code Here

    Field field = FieldFactory.getFieldByInode(fieldInode);
    if(!UtilMethods.isSet(field)){
      Logger.warn(FieldServices.class,"Field not found.  Unable to load velocity code");
      return new ByteArrayInputStream("".toString().getBytes());
    }
    ContentletAPI conAPI = APILocator.getContentletAPI();
    FieldAPI fAPI = APILocator.getFieldAPI();
    Contentlet content = conAPI.find(contentInode, APILocator.getUserAPI().getSystemUser(), true);
    if(!UtilMethods.isSet(content)){
      Logger.warn(FieldServices.class,"Content not found.  Unable to load velocity code");
      return new ByteArrayInputStream("".toString().getBytes());
    }
    Object contFieldValueObject = conAPI.getFieldValue(content, field);
    String contFieldValue = "";
   
    if(fAPI.isElementConstant(field)){
      contFieldValue = field.getValues() == null ? "" : field.getValues();
    }else{
View Full Code Here

    removeContentletFile(content, identifier, EDIT_MODE);
  }

  public static InputStream buildVelocity(Contentlet content, Identifier identifier, boolean EDIT_MODE) throws DotDataException, DotSecurityException {
    InputStream result;
    ContentletAPI conAPI= APILocator.getContentletAPI();
    FieldAPI fAPI= APILocator.getFieldAPI();
    User systemUser= APILocator.getUserAPI().getSystemUser();


    // let's write this puppy out to our file
    StringBuilder sb= new StringBuilder();

    // CONTENTLET CONTROLS BEGIN
    sb.append("#if($EDIT_MODE)");
    sb.append("#set( $EDIT_CONTENT_PERMISSION=$EDIT_CONTENT_PERMISSION" ).append( identifier.getInode() ).append( ")");
    sb.append("#end");

    sb.append("#set($CONTENT_INODE='" ).append( content.getInode() ).append( "' )");
    sb.append("#set($IDENTIFIER_INODE='" ).append( identifier.getInode() ).append( "' )");

    // set all properties from the contentlet
    sb.append("#set($ContentInode='" ).append( content.getInode() ).append( "' )");
    sb.append("#set($ContentIdentifier='" ).append( identifier.getInode() ).append( "' )");
    sb.append("#set($ContentletTitle=\"" ).append( UtilMethods.espaceForVelocity(conAPI.getName(content, APILocator.getUserAPI().getSystemUser(), true)) ).append( "\" )");
    String modDateStr= UtilMethods.dateToHTMLDate((Date) content.getModDate(), "yyyy-MM-dd H:mm:ss");
    sb.append("#set($ContentLastModDate= $date.toDate(\"yyyy-MM-dd H:mm:ss\", \"" ).append( modDateStr ).append( "\"))");
    sb.append("#set($ContentLastModUserId= \"" ).append( content.getModUser() ).append( "\")");
    if (content.getOwner() != null)
      sb.append("#set($ContentOwnerId= \"" ).append( content.getOwner() ).append( "\")");

    // Structure fields

    Structure structure= content.getStructure();

    List<Field> fields= FieldsCache.getFieldsByStructureInode(structure.getInode());
    Iterator<Field> fieldsIt= fields.iterator();

    String widgetCode= "";

    while (fieldsIt.hasNext()) {
      Field field= (Field) fieldsIt.next();
      String contField= field.getFieldContentlet();
      String contFieldValue= null;
      Object contFieldValueObject= null;
      String velPath= (!EDIT_MODE) ? "live/" : "working/";
      if(fAPI.isElementConstant(field)){
          if(field.getVelocityVarName().equals("widgetPreexecute")){
          continue;
        }
        if(field.getVelocityVarName().equals("widgetCode")){
          widgetCode= "#set($" + field.getVelocityVarName() + "=$velutil.mergeTemplate(\"" + velPath +  content.getInode() + "_" + field.getInode() + "." + Config.getStringProperty("VELOCITY_FIELD_EXTENSION") + "\"))";
          continue;
        }else{
          String fieldValues=field.getValues()==null?"":field.getValues();
          if(fieldValues.contains("$") || fieldValues.contains("#")){
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "= $velutil.mergeTemplate(\"" ).append( velPath ).appendcontent.getInode() ).append( "_" ).append( field.getInode() ).append( "." ).append( Config.getStringProperty("VELOCITY_FIELD_EXTENSION") ).append( "\"))");
          }else{
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "= \"" ).append( UtilMethods.espaceForVelocity(fieldValues).trim() ).append( "\")");
          }
          continue;
        }
      }
      if (UtilMethods.isSet(contField)) {
        try {
          contFieldValueObject= conAPI.getFieldValue(content, field);
          contFieldValue= contFieldValueObject== null ? "" : contFieldValueObject.toString();
        } catch (Exception e) {
          Logger.error(ContentletServices.class, "writeContentletToFile: " + e.getMessage());
        }
        if (!field.getFieldType().equals(Field.FieldType.DATE_TIME.toString()) && !field.getFieldType().equals(Field.FieldType.DATE.toString())
            && !field.getFieldType().equals(Field.FieldType.TIME.toString())){
          if(contFieldValue.contains("$") || contFieldValue.contains("#")){
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "=$velutil.mergeTemplate(\"" ).append( velPath ).appendcontent.getInode() ).append( "_" ).append( field.getInode() ).append( "." ).append( Config.getStringProperty("VELOCITY_FIELD_EXTENSION") ).append( "\"))");
          }else{
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "=\"" ).append( UtilMethods.espaceForVelocity(contFieldValue).trim() ).append( "\")");
          }
        }

      }

      if (field.getFieldType().equals(Field.FieldType.IMAGE.toString())) {
        String identifierValue= content.getStringProperty(field.getVelocityVarName());
        if( InodeUtils.isSet(identifierValue) ) {
          if (EDIT_MODE){
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getFile('" ).append( identifierValue ).append( "',false))");
          }else{
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getFile('" ).append( identifierValue ).append( "',true))");
          }
        }else{
          sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getNewFile())");
        }

        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageInode=$" ).append( field.getVelocityVarName() ).append( "Object.getInode() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageIdentifier=$" ).append( field.getVelocityVarName() ).append( "Object.getIdentifier() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageWidth=$" ).append( field.getVelocityVarName() ).append( "Object.getWidth() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageHeight=$" ).append( field.getVelocityVarName() ).append( "Object.getHeight() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageExtension=$" ).append( field.getVelocityVarName() ).append( "Object.getExtension() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageURI=$filetool.getURI($" ).append( field.getVelocityVarName() ).append( "Object))");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageTitle=$UtilMethods.espaceForVelocity($" ).append( field.getVelocityVarName() ).append( "Object.getTitle()) )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageFriendlyName=$UtilMethods.espaceForVelocity($" ).append( field.getVelocityVarName() ).append( "Object.getFriendlyName()) )");

        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImagePath=$" ).append( field.getVelocityVarName() ).append( "Object.getPath())");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ImageName=$" ).append( field.getVelocityVarName() ).append( "Object.getFileName())");

      }//  http://jira.dotmarketing.net/browse/DOTCMS-2178
      else if (field.getFieldType().equals(Field.FieldType.BINARY.toString())){
        java.io.File binFile;
        String fileName= "";
        String filesize= "";
        try {
          binFile= content.getBinary(field.getVelocityVarName());
          if(binFile != null) {
            fileName= binFile.getName();
            filesize= FileUtil.getsize(binFile);
          }
        } catch (IOException e) {
          Logger.error(ContentletServices.class, "Unable to retrive binary file for content id " + content.getIdentifier() + " field " + field.getVelocityVarName(), e);
          continue;
        }
           sb.append("#set($" ).append( field.getVelocityVarName() ).append( "BinaryFileTitle=\"" ).append( UtilMethods.espaceForVelocity(fileName) ).append( "\" )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "BinaryFileSize=\"" ).append( UtilMethods.espaceForVelocity(filesize) ).append( "\" )");
        String binaryFileURI= fileName.length()>0? UtilMethods.espaceForVelocity("/contentAsset/raw-data/"+content.getIdentifier()+"/"+ field.getVelocityVarName() + "/" + content.getInode()):"";
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "BinaryFileURI=\"" ).append( binaryFileURI).append("\" )");
      }else if (field.getFieldType().equals(Field.FieldType.FILE.toString())) {
        String identifierValue= content.getStringProperty(field.getVelocityVarName());
        if( InodeUtils.isSet(identifierValue) ) {
          if (EDIT_MODE){
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getFile('" ).append( identifierValue ).append( "',false))");
          }else{
            sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getFile('" ).append( identifierValue ).append( "',true))");
          }
        }else{
          sb.append("#set($" ).append( field.getVelocityVarName() ).append( "Object= $filetool.getNewFile())");
        }

        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileInode=$" ).append( field.getVelocityVarName() ).append( "Object.getInode() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileIdentifier=$" ).append( field.getVelocityVarName() ).append( "Object.getIdentifier() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileExtension=$" ).append( field.getVelocityVarName() ).append( "Object.getExtension() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileURI=$filetool.getURI($" ).append( field.getVelocityVarName() ).append( "Object))");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileTitle=$" ).append( field.getVelocityVarName() ).append( "Object.getTitle() )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileFriendlyName=$UtilMethods.espaceForVelocity($" ).append( field.getVelocityVarName() ).append( "Object.getFriendlyName() ))");

        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FilePath=$UtilMethods.espaceForVelocity($" ).append( field.getVelocityVarName() ).append( "Object.getPath()) )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "FileName=$UtilMethods.espaceForVelocity($" ).append( field.getVelocityVarName() ).append( "Object.getFileName()) )");


      } else if (field.getFieldType().equals(Field.FieldType.SELECT.toString())) {
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "SelectLabelsValues=\"" ).append( field.getValues().replaceAll("\\r\\n", " ").replaceAll("\\n", " ") ).append( "\")");
      } else if (field.getFieldType().equals(Field.FieldType.RADIO.toString())) {
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "RadioLabelsValues=\"" ).append( field.getValues().replaceAll("\\r\\n", " ").replaceAll("\\n", " ") ).append( "\" )");
      } else if (field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())) {
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "CheckboxLabelsValues=\"" ).append( field.getValues().replaceAll("\\r\\n", " ").replaceAll("\\n", " ") ).append( "\" )");
      } else if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
        String shortFormat= "";
        String dbFormat= "";
        if (contFieldValueObject != null && contFieldValueObject instanceof Date) {
          shortFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy");
          dbFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "yyyy-MM-dd");
        }
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "=$date.toDate(\"yyyy-MM-dd\", \"" ).append( dbFormat ).append( "\"))");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "ShortFormat=\"" ).append( shortFormat ).append( "\" )");
        sb.append("#set($" ).append( field.getVelocityVarName() ).append( "DBFormat=\"" ).append( dbFormat ).append( "\" )");
      } else if (field.getFieldType().equals(Field.FieldType.TIME.toString())) {
        String shortFormat= "";
        if (contFieldValueObject != null && contFieldValueObject instanceof Date) {
          shortFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "H:mm:ss");
        }
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "ShortFormat=\"" ).append( shortFormat ).append( "\" )");
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "= $date.toDate(\"H:mm:ss\", \"" ).append( shortFormat ).append( "\"))");
      } else if (field.getFieldType().equals(Field.FieldType.DATE_TIME.toString())) {
        String shortFormat= "";
        String longFormat= "";
        String dbFormat= "";
        if (contFieldValueObject != null && contFieldValueObject instanceof Date) {
          shortFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy");
          longFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "MM/dd/yyyy H:mm:ss");
          dbFormat= UtilMethods.dateToHTMLDate((Date) contFieldValueObject, "yyyy-MM-dd H:mm:ss");
        }
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "= $date.toDate(\"yyyy-MM-dd H:mm:ss\", \"" ).append( dbFormat ).append( "\"))");
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "ShortFormat=\"" ).append( shortFormat ).append( "\" )");
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "LongFormat=\"" ).append( longFormat ).append( "\" )");
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "DBFormat=\"" ).append( dbFormat ).append( "\" )");
      } else if (field.getFieldType().equals(Field.FieldType.BUTTON.toString())) {
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "ButtonValue=\"" ).append( (field.getFieldName()== null ? "" : field.getFieldName()) ).append( "\" )");
        sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "ButtonCode=\"" ).append( (field.getValues()== null ? "" : field.getValues()) ).append( "\" )");
      }//http://jira.dotmarketing.net/browse/DOTCMS-2869
//      else if (field.getFieldType().equals(Field.FieldType.CUSTOM_FIELD.toString())){
//         sb.append("#set( $" + field.getVelocityVarName() + "Code=\"" + UtilMethods.espaceForVelocity(field.getValues()) + "\" )");
//      }//http://jira.dotmarketing.net/browse/DOTCMS-3232
      else if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())){
        if(InodeUtils.isSet(content.getFolder())){
          sb.append("#set( $ConHostFolder='" ).append( content.getFolder() ).append( "' )");
        }else{
          sb.append("#set( $ConHostFolder='" ).append( content.getHost() ).append( "' )");
        }
      }

      else if (field.getFieldType().equals(Field.FieldType.CATEGORY.toString())) {

        // Get the Category Field
        Category category= categoryAPI.find(field.getValues(), systemUser, false);
        // Get all the Contentlets Categories
        List<Category> selectedCategories= categoryAPI.getParents(content, systemUser, false);

            //Initialize variables
            String catInodes= "";
            Set<Category> categoryList= new HashSet<Category>();
        List<Category> categoryTree= categoryAPI.getAllChildren(category, systemUser, false);

        if (selectedCategories.size() > 0 && categoryTree != null) {
          for (int k= 0; k < categoryTree.size(); k++) {
            Category cat= (Category) categoryTree.get(k);
            for (Category categ : selectedCategories) {
              if (categ.getInode().equalsIgnoreCase(cat.getInode())) {
                categoryList.add(cat);
              }
            }
          }
        }

        if (categoryList.size() > 0) {
            StringBuilder catbuilder=new StringBuilder();
          Iterator<Category> it= categoryList.iterator();
          while (it.hasNext()) {
            Category cat= (Category) it.next();
            catbuilder.append("\"").append(cat.getInode()).append("\"");
            if (it.hasNext()) {
              catbuilder.append(",");
            }
          }
          catInodes=catbuilder.toString();

          sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "FilteredCategories=$categories.filterCategoriesByUserPermissions([" ).append( catInodes ).append( "] ))");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "Categories=$categories.fetchCategoriesInodes($").append(field.getVelocityVarName()).append("FilteredCategories))");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "CategoriesNames=$categories.fetchCategoriesNames($").append(field.getVelocityVarName()).append("FilteredCategories))");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "=$").append(field.getVelocityVarName()).append("Categories)");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "CategoriesKeys=$categories.fetchCategoriesKeys($").append(field.getVelocityVarName()).append("FilteredCategories))");
        }
        else {
            sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "FilteredCategories=$contents.getEmptyList())");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "Categories=$contents.getEmptyList())");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "CategoriesNames=$contents.getEmptyList())");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "=$contents.getEmptyList())");
                  sb.append("#set( $" ).append( field.getVelocityVarName() ).append( "CategoriesKeys=$contents.getEmptyList())");
        }
      }
    }


        // get the contentlet categories to make a list
        String categories= "";
        Set<Category> categoryList= new HashSet<Category>(categoryAPI.getParents(content, systemUser, false));
        if (categoryList!=null && categoryList.size()>0) {
            StringBuilder catbuilder=new StringBuilder();
      Iterator<Category> it= categoryList.iterator();
      while (it.hasNext()) {
        Category category= (Category) it.next();
            catbuilder.append("\"").append(category.getInode()).append("\"") ;
        if (it.hasNext()) {
              catbuilder.append(",");
            }
          }
      categories=catbuilder.toString();

      sb.append("#set($ContentletFilteredCategories=$categories.filterCategoriesByUserPermissions([" ).append( categories ).append( "] ))");
          sb.append("#set($ContentletCategories=$categories.fetchCategoriesInodes($ContentletFilteredCategories))");
          sb.append("#set($ContentletCategoryNames=$categories.fetchCategoriesNames($ContentletFilteredCategories))");
          sb.append("#set($ContentletCategoryKeys=$categories.fetchCategoriesKeys($ContentletFilteredCategories))");
        }
        else {
            sb.append("#set($ContentletFilteredCategories=$contents.getEmptyList())");
            sb.append("#set($ContentletCategories=$contents.getEmptyList())");
            sb.append("#set($ContentletCategoryNames=$contents.getEmptyList())");
            sb.append("#set($ContentletCategoryKeys=$contents.getEmptyList())");
        }

    //This needs to be here because the all fields like cats etc.. need to be parsed first and it needs to be before
    // the $CONTENT_INODE is reset sb.append("#set( $CONTENT_INODE=\"" + content.getInode() + "\" )");
    //http://jira.dotmarketing.net/browse/DOTCMS-2808
    sb.append(widgetCode);

    // This is code is repeated because the bug GETTYS-268, the content
    // variables were been overwritten
    // by the parse inside the some of the content fields
    // To edit the look, see
    // WEB-INF/velocity/static/preview/content_controls.vtl

    if(EDIT_MODE) {
      sb.append("#set( $EDIT_CONTENT_PERMISSION=$EDIT_CONTENT_PERMISSION" ).append( identifier.getInode() ).append( " )");
    }

    sb.append("#set( $CONTENT_INODE=\"" ).append( content.getInode() ).append( "\" )");
    sb.append("#set( $IDENTIFIER_INODE=\"" ).append( identifier.getInode() ).append( "\" )");

    sb.append("#set( $ContentInode=\"" ).append( content.getInode() ).append( "\" )");
    sb.append("#set( $ContentIdentifier=\"" ).append( identifier.getInode() ).append( "\" )");
    sb.append("#set( $ContentletTitle=\"" ).append( UtilMethods.espaceForVelocity(conAPI.getName(content, APILocator.getUserAPI().getSystemUser(), true)) ).append( "\" )");
    sb.append("#set( $ContentletStructure=\"" ).append( content.getStructureInode() ).append( "\" )");

    if(structure.getStructureType()== Structure.STRUCTURE_TYPE_WIDGET){
      sb.append("#set( $isWidget= \"" ).append( true ).append( "\")");
      if(structure.getName().equals(FormAPI.FORM_WIDGET_STRUCTURE_NAME_FIELD_NAME)){
View Full Code Here

   * @param contentlets
   * @throws DotSecurityException
   * @throws DotDataException
   */
  public static void removeContentletFile(Structure structure) throws DotDataException, DotSecurityException{
    ContentletAPI conAPI= APILocator.getContentletAPI();
    int limit= 500;
    int offset= 0;
    List<Contentlet> contentlets= conAPI.findByStructure(structure, APILocator.getUserAPI().getSystemUser(), false, limit, offset);
    int size= contentlets.size();
    while(size > 0){
      for (Contentlet contentlet : contentlets) {
        removeContentletFile(contentlet);
      }
      offset += limit;
      contentlets= conAPI.findByStructure(structure, APILocator.getUserAPI().getSystemUser(), false, limit, offset);
      size= contentlets.size();
    }
  }
View Full Code Here

   * @throws DotDataException
   */
  @SuppressWarnings("unchecked")
  public static boolean publishAsset(Inode webAsset, User user, boolean respectFrontendRoles, boolean isNewVersion) throws WebAssetException, DotSecurityException, DotDataException
  {
    ContentletAPI conAPI = APILocator.getContentletAPI();
    HostAPI hostAPI = APILocator.getHostAPI();
   
    //http://jira.dotmarketing.net/browse/DOTCMS-6325
    if (user != null &&
        ((webAsset instanceof Folder)?
        !permissionAPI.doesUserHavePermission(webAsset, PermissionAPI.PERMISSION_EDIT, user):
        !permissionAPI.doesUserHavePermission(webAsset, PERMISSION_PUBLISH, user))) {
      Logger.debug(PublishFactory.class, "publishAsset: user = " + user.getEmailAddress() + ", don't have permissions to publish: " + webAsset);
      return false;
    }
   
    if (webAsset instanceof WebAsset)
    {
      try {
        WebAssetFactory.publishAsset((WebAsset) webAsset, user, isNewVersion);
      } catch (Exception e) {
        Logger.error(PublishFactory.class, "publishAsset: Failed to publish the asset.", e);
      }
    }

    if (webAsset instanceof com.dotmarketing.portlets.files.model.File)
    {
      // publishing a file
      LiveCache.removeAssetFromCache((WebAsset)webAsset);
      LiveCache.addToLiveAssetToCache((WebAsset) webAsset);
      WorkingCache.removeAssetFromCache((WebAsset)webAsset);
      WorkingCache.addToWorkingAssetToCache((WebAsset) webAsset);
      if(RefreshMenus.shouldRefreshMenus((com.dotmarketing.portlets.files.model.File)webAsset)){
        com.dotmarketing.menubuilders.RefreshMenus.deleteMenu((WebAsset)webAsset);
        Identifier ident=APILocator.getIdentifierAPI().find(webAsset);
        CacheLocator.getNavToolCache().removeNavByPath(ident.getHostId(), ident.getParentPath());
      }

    }

    if (webAsset instanceof Container) {

      //saves to live folder under velocity
      ContainerServices.invalidate((Container)webAsset);
    }


    if (webAsset instanceof Template) {

        Logger.debug(PublishFactory.class, "*****I'm a Template -- Publishing");

      //gets all identifier children
      java.util.List<Container> identifiers = APILocator.getTemplateAPI().getContainersInTemplate((Template)webAsset, APILocator.getUserAPI().getSystemUser(), false);
      java.util.Iterator<Container> identifiersIter = identifiers.iterator();
      while (identifiersIter.hasNext()) {

        Container container =(Container) identifiersIter.next();

          Logger.debug(PublishFactory.class, "*****I'm a Template -- Publishing my Container Child=" + container.getInode());
          if(!container.isLive()){
            publishAsset(container,user, respectFrontendRoles, isNewVersion);
          }
       
       
      }

            //Clean-up the cache for this template
            CacheLocator.getTemplateCache().remove( webAsset.getInode() );
            //writes the template to a live directory under velocity folder
      TemplateServices.invalidate((Template)webAsset);

    }

    if (webAsset instanceof HTMLPage)
    {

        Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- Publishing");

        List relatedNotPublished = new ArrayList();
        relatedNotPublished = getUnpublishedRelatedAssets(webAsset, relatedNotPublished, user, respectFrontendRoles);
       
        //Publishing related pieces of content
        for(Object asset : relatedNotPublished) {
          if(asset instanceof Contentlet) {
          Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- Publishing my Contentlet Child=" + ((Contentlet)asset).getInode());
          try {
            Contentlet c = (Contentlet)asset;
            if(!APILocator.getWorkflowAPI().findSchemeForStruct(c.getStructure()).isMandatory()){
              conAPI.publish((Contentlet)asset, user, false);
            }
          } catch (DotSecurityException e) {
            //User has no permission to publish the content in the page so we just skip it
            Logger.debug(PublishFactory.class, "publish html page: User has no permission to publish the content inode = " + ((Contentlet)asset).getInode() + " in the page, skipping it.");
          }           
          }else if(asset instanceof Template){
            Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- Publishing Template =" + ((Template)asset).getInode());
            publishAsset((Template)asset,user, respectFrontendRoles,false);
          }
        }

        LiveCache.removeAssetFromCache((WebAsset) webAsset);
      LiveCache.addToLiveAssetToCache((WebAsset) webAsset);
      WorkingCache.removeAssetFromCache((WebAsset) webAsset);
      WorkingCache.addToWorkingAssetToCache((WebAsset) webAsset);
      //writes the htmlpage to a live directory under velocity folder
      PageServices.invalidate((HTMLPage)webAsset);

            //Refreshing the menues
     
     
      if(RefreshMenus.shouldRefreshMenus((HTMLPage)webAsset)){
        Folder folder = (Folder) APILocator.getFolderAPI().findParentFolder((Treeable)webAsset,user,false);
        if(folder != null){
          RefreshMenus.deleteMenu(folder);
          CacheLocator.getNavToolCache().removeNav(folder.getHostId(),folder.getInode());
        }
      }
            CacheLocator.getHTMLPageCache().remove((HTMLPage) webAsset);

    }

    if (webAsset instanceof Folder) {

      Folder parentFolder = (Folder) webAsset;

        Logger.debug(PublishFactory.class, "*****I'm a Folder -- Publishing" + parentFolder.getName());

      //gets all links for this folder
      java.util.List foldersListSubChildren = APILocator.getFolderAPI().findSubFolders(parentFolder,APILocator.getUserAPI().getSystemUser(),false);
      //gets all links for this folder
      java.util.List linksListSubChildren = APILocator.getFolderAPI().getWorkingLinks(parentFolder, user, false);
      //gets all html pages for this folder
      java.util.List htmlPagesSubListChildren = APILocator.getFolderAPI().getWorkingHTMLPages(parentFolder,user,false);
      //gets all files for this folder
      java.util.List filesListSubChildren = APILocator.getFolderAPI().getWorkingFiles(parentFolder,user,false);
      //gets all templates for this folder
      //java.util.List templatesListSubChildren = APILocator.getFolderAPI().getWorkingChildren(parentFolder,Template.class);
      //gets all containers for this folder
      //java.util.List containersListSubChildren = APILocator.getFolderAPI().getWorkingChildren(parentFolder,Container.class);

      //gets all subitems
      java.util.List elements = new java.util.ArrayList();
      elements.addAll(foldersListSubChildren);
      elements.addAll(linksListSubChildren);
      elements.addAll(htmlPagesSubListChildren);
      elements.addAll(filesListSubChildren);
      //elements.addAll(templatesListSubChildren);
      //elements.addAll(containersListSubChildren);

      java.util.Iterator elementsIter = elements.iterator();
      while (elementsIter.hasNext()) {
        Inode inode = (Inode) elementsIter.next();
          Logger.debug(PublishFactory.class, "*****I'm a Folder -- Publishing my Inode Child=" + inode.getInode());
        publishAsset(inode,user, respectFrontendRoles, isNewVersion);
      }
     
      java.util.List<Contentlet> contentlets = conAPI.findContentletsByFolder(parentFolder, user, false);
      java.util.Iterator<Contentlet> contentletsIter = contentlets.iterator();
      while (contentletsIter.hasNext()) {
        //publishes each one
        Contentlet contentlet = (Contentlet)contentletsIter.next();
        Logger.debug(PublishFactory.class, "*****I'm a Folder -- Publishing my Inode Child=" + contentlet.getInode());
        if(!contentlet.isLive() && !contentlet.isArchived() && (permissionAPI.doesUserHavePermission(contentlet, PERMISSION_PUBLISH, user, respectFrontendRoles))) {
          APILocator.getContentletAPI().publish(contentlet, user, false);
        }
      }
    }

    if (webAsset instanceof Link) {
      List contentlets = InodeFactory.getParentsOfClass(webAsset, com.dotmarketing.portlets.contentlet.business.Contentlet.class);
      Iterator it = contentlets.iterator();
      while (it.hasNext()) {
        com.dotmarketing.portlets.contentlet.business.Contentlet cont = (com.dotmarketing.portlets.contentlet.business.Contentlet) it.next();
          if (cont.isLive()) {
            try {
              com.dotmarketing.portlets.contentlet.model.Contentlet newFormatContentlet =
              conAPI.convertFatContentletToContentlet(cont);
            ContentletServices.invalidate(newFormatContentlet,  false);
              ContentletMapServices.invalidate(newFormatContentlet, false);
          } catch (DotDataException e) {
            throw new WebAssetException(e.getMessage(), e);
          }
View Full Code Here

   * @throws DotSecurityException
   */
  @SuppressWarnings("unchecked")
  public static List getUnpublishedRelatedAssets(Inode webAsset, List relatedAssets, boolean returnOnlyWebAssets, boolean checkPublishPermissions, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException {

    ContentletAPI conAPI = APILocator.getContentletAPI();

    if (webAsset instanceof Template) {

        Logger.debug(PublishFactory.class, "*****I'm a Template -- PrePublishing");

      //gets all identifier children

      java.util.List<Container> identifiers = APILocator.getTemplateAPI().getContainersInTemplate((Template)webAsset, APILocator.getUserAPI().getSystemUser(), false);
      Iterator<Container> identifiersIter = identifiers.iterator();
      while (identifiersIter.hasNext()) {

        Container container = (Container)identifiersIter.next();
        if(!container.isLive() && (permissionAPI.doesUserHavePermission(container, PERMISSION_PUBLISH, user, respectFrontendRoles) || !checkPublishPermissions)) {
          relatedAssets.add(container);
        }
      }

    }

    if (webAsset instanceof HTMLPage) {

        Logger.debug(PublishFactory.class, "*****I'm an HTML Page -- PrePublishing");

      //gets working (not published) template parent for this html page
      Template templateParent = HTMLPageFactory.getHTMLPageTemplate((HTMLPage)webAsset,true);

      if (InodeUtils.isSet(templateParent.getInode())) {
       
        if(!templateParent.isLive() && (permissionAPI.doesUserHavePermission(templateParent, PERMISSION_PUBLISH, user, respectFrontendRoles) || !checkPublishPermissions)) {
          relatedAssets.add(templateParent);
        }


        //gets all live container children       
        java.util.List<Container> identifiers = APILocator.getTemplateAPI().getContainersInTemplate(templateParent, APILocator.getUserAPI().getSystemUser(), false);
        java.util.Iterator<Container> identifiersIter = identifiers.iterator();
        while (identifiersIter.hasNext()) {

          Container container = (Container)identifiersIter.next();

                    List categories = InodeFactory.getParentsOfClass(container, Category.class);
          List contentlets = null;

          if (categories.size() == 0) {
              Logger.debug(PublishFactory.class, "*******HTML Page PrePublishing Static Container");
              Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(webAsset);
              Identifier idenContainer = APILocator.getIdentifierAPI().find(container);
              try{
                contentlets = conAPI.findPageContentlets(idenHtmlPage.getInode(),idenContainer.getInode(),null, true, -1, APILocator.getUserAPI().getSystemUser(), false);
              }catch (Exception e) {
               Logger.error(PublishFactory.class,"Unable to get contentlets on page",e);
               contentlets = new ArrayList<Contentlet>();
            }
                    }
                    else {

                    Logger.debug(PublishFactory.class, "*******HTML Page PrePublishing Dynamic Container");
                        Iterator catsIter = categories.iterator();
                        Set contentletSet = new HashSet();

                        String condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted=" + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
                        String sort = (container.getSortContentletsBy() == null) ? "sort_order" : container.getSortContentletsBy();

                        while (catsIter.hasNext()) {
                            Category category = (Category) catsIter.next();
                            List contentletsChildren = InodeFactory.getChildrenClassByConditionAndOrderBy(category,
                                    Contentlet.class, condition, sort);
                            if (contentletsChildren != null && contentletsChildren.size() > 0) {
                                contentletSet.addAll(contentletsChildren);
                            }
                        }
                        contentlets = new ArrayList();
                        contentlets.addAll(contentletSet);
                    }
          java.util.Iterator contentletsIter = contentlets.iterator();
          while (contentletsIter.hasNext()) {
            //publishes each one
            Contentlet contentlet = (Contentlet)contentletsIter.next();
            if(!contentlet.isLive() && (permissionAPI.doesUserHavePermission(contentlet, PERMISSION_PUBLISH, user, respectFrontendRoles) || !checkPublishPermissions)) {
              relatedAssets.add(contentlet);
            }
          }
        }

      }

    }

    if (webAsset instanceof Folder) {

      Folder parentFolder = (Folder) webAsset;

        Logger.debug(PublishFactory.class, "*****I'm a Folder -- PrePublishing" + parentFolder.getName());
       
      //gets all links for this folder
      java.util.List foldersListSubChildren = APILocator.getFolderAPI().findSubFolders(parentFolder,APILocator.getUserAPI().getSystemUser(),false);
      //gets all links for this folder
      java.util.List linksListSubChildren = APILocator.getFolderAPI().getWorkingLinks(parentFolder,user,false);
      //gets all html pages for this folder
      java.util.List htmlPagesSubListChildren = APILocator.getFolderAPI().getWorkingHTMLPages(parentFolder,user,false);
      //gets all files for this folder
      java.util.List filesListSubChildren = APILocator.getFolderAPI().getWorkingFiles(parentFolder,user,false);
      //gets all templates for this folder
      //java.util.List templatesListSubChildren = APILocator.getFolderAPI().getWorkingChildren(parentFolder,Template.class);
      //gets all containers for this folder
      //java.util.List containersListSubChildren = APILocator.getFolderAPI().getWorkingChildren(parentFolder,Container.class);

      //gets all subitems
      java.util.List elements = new java.util.ArrayList();
      elements.addAll(foldersListSubChildren);
      elements.addAll(linksListSubChildren);
      elements.addAll(htmlPagesSubListChildren);
      elements.addAll(filesListSubChildren);
      //elements.addAll(templatesListSubChildren);
      //elements.addAll(containersListSubChildren);



      java.util.Iterator elementsIter = elements.iterator();
      while (elementsIter.hasNext()) {
        Inode asset = (Inode) elementsIter.next();
        if (asset instanceof WebAsset) {
          if(!((WebAsset)asset).isLive() && (permissionAPI.doesUserHavePermission(((WebAsset)asset), PERMISSION_PUBLISH, user, respectFrontendRoles) || !checkPublishPermissions)) {
            relatedAssets.add(asset);
          }
        }else if(!returnOnlyWebAssets){
          relatedAssets.add(asset);
        }
        //if it exists it prepublishes it
        relatedAssets = getUnpublishedRelatedAssets(asset,relatedAssets, returnOnlyWebAssets, checkPublishPermissions, user, respectFrontendRoles);
      }
     
      java.util.List<Contentlet> contentlets = conAPI.findContentletsByFolder(parentFolder, user, false);
      java.util.Iterator<Contentlet> contentletsIter = contentlets.iterator();
      while (contentletsIter.hasNext()) {
        Contentlet contentlet = (Contentlet)contentletsIter.next();
        if(!contentlet.isLive() && (permissionAPI.doesUserHavePermission(contentlet, PERMISSION_PUBLISH, user, respectFrontendRoles) || !checkPublishPermissions)) {
          relatedAssets.add(contentlet);
View Full Code Here

        //create the relationship
        relationship = new Relationship (slideShowSt, slideSt, "Slide Show", "Slide Image", com.dotmarketing.util.WebKeys.Relationship.RELATIONSHIP_CARDINALITY.ONE_TO_MANY.ordinal(), false, false);
        RelationshipFactory.saveRelationship(relationship);
      }
     
      ContentletAPI conAPI = APILocator.getContentletAPI();
      StringBuffer lqBuffy = new StringBuffer();
      lqBuffy.append("+structureInode:" + slideShowSt.getInode() + " +type:content +live:true +deleted:false +" + slideShowTitleF.getFieldContentlet().trim() + ":\"" + title.toLowerCase() + "\"");
      User user = (User)request.getSession().getAttribute(WebKeys.CMS_USER);
      List<Contentlet> results = conAPI.search(lqBuffy.toString(), 0, -1, "inode",user , true);
     
//      List<Contentlet> results = ContentletFactory.getContentletByCondition("live = " + DbConnectionFactory.getDBTrue() +
//          " and deleted = " + DbConnectionFactory.getDBFalse() + " and " +
//          slideShowTitleF.getFieldContentlet() + " = '" + UtilMethods.sqlify(title) + "'");
 
      if (results.size() == 0) {
        return;
      }
     
      Contentlet slideShow = results.get(0);
      String slideShowTitle = (String)conAPI.getFieldValue(slideShow, slideShowTitleF);
      String slideShowCredits = (String)conAPI.getFieldValue(slideShow, slideShowCreditsF);
      String slideShowAudioTitle = (String)conAPI.getFieldValue(slideShow, slideShowAudioTitleF);
      String slideShowAudioFileInode = (String)conAPI.getFieldValue(slideShow, slideShowAudioFileF);
      File slideShowFile = (File) InodeFactory.getInode(slideShowAudioFileInode, File.class);
     
      List<Contentlet> slideImages = RelationshipFactory.getAllRelationshipRecords(relationship, slideShow, true, true);
     
      sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

      sw.write("<slidesInfo>\n");
      sw.write("  <baseInfo>\n");
      sw.write("    <intTotalImg>" + slideImages.size() + "</intTotalImg>\n");
      sw.write("    <strTitle>" + XMLUtils.xmlEscape(slideShowTitle) + "</strTitle>\n");
      sw.write("    <strCredits>" + XMLUtils.xmlEscape(slideShowCredits) + "</strCredits>\n");
      sw.write("    <strAudio>" + XMLUtils.xmlEscape(slideShowAudioTitle) + "</strAudio>\n");
      sw.write("  </baseInfo>\n");
      sw.write("  <strSound>\n");
      sw.write("    <strPathSound>" + (slideShowFile.getURI() == null || slideShowFile.getURI().equals("")?"":slideShowFile.getURI()) + "</strPathSound>\n");
      sw.write("  </strSound>\n");

      StringBuffer imagesPathsXML = new StringBuffer ();
      StringBuffer imagesTimingXML = new StringBuffer ();
      StringBuffer imagesTextXML = new StringBuffer ();
      for (Contentlet slide : slideImages) {
        // only show live slides
        if (!slide.isLive()) {
          continue;
        }

        //String slideTitle = (String)ContentletFactory.getFieldValue(slide, slideTitleF);
        String slideTextBody = (String)conAPI.getFieldValue(slide, slideTextBodyF);
        long slideTiming = (Long)conAPI.getFieldValue(slide, slideTimingF);
        String slideImageInode = (String)conAPI.getFieldValue(slide, slideImageF);
        //File slideImage = (File) InodeFactory.getInode(slideImageInode, File.class);
        //Identifier slideImageIdentifier = (Identifier) InodeFactory.getInode(slideImageInode, Identifier.class);
        Identifier slideImageIdentifier = APILocator.getIdentifierAPI().find(slideImageInode);
        File slideImage = (File)APILocator.getVersionableAPI().findWorkingVersion(slideImageIdentifier, user, true);
View Full Code Here

   */
  @Test
  public void retry_issue5097 () throws DotSecurityException, DotDataException, IOException, JSONException, DotPublisherException, InterruptedException {

    EnvironmentAPI environmentAPI = APILocator.getEnvironmentAPI();
    ContentletAPI contentletAPI = APILocator.getContentletAPI();
    PublishingEndPointAPI publisherEndPointAPI = APILocator.getPublisherEndPointAPI();
    PublisherAPI publisherAPI = PublisherAPI.getInstance();

    HttpServletRequest req = ServletTestRunner.localRequest.get();

    Environment environment = new Environment();
    environment.setName( "TestEnvironment_" + String.valueOf( new Date().getTime() ) );
    environment.setPushToAll( false );

    //Find the roles of the admin user
    Role role = APILocator.getRoleAPI().loadRoleByKey( adminUser.getUserId() );

    //Create the permissions for the environment
    List<Permission> permissions = new ArrayList<Permission>();
    Permission p = new Permission( environment.getId(), role.getId(), PermissionAPI.PERMISSION_USE );
    permissions.add( p );

    //Create a environment
    environmentAPI.saveEnvironment( environment, permissions );

    //Now we need to create the end point
    PublishingEndPoint endpoint = new PublishingEndPoint();
    endpoint.setServerName( new StringBuilder( "TestEndPoint" + String.valueOf( new Date().getTime() ) ) );
    endpoint.setAddress( "127.0.0.1" );
    endpoint.setPort( "999" );
    endpoint.setProtocol( "http" );
    endpoint.setAuthKey( new StringBuilder( PublicEncryptionFactory.encryptString( "1111" ) ) );
    endpoint.setEnabled( true );
    endpoint.setSending( false );//TODO: Shouldn't this be true as we are creating this end point to send bundles to another server..?
    endpoint.setGroupId( environment.getId() );
    //Save the endpoint.
    publisherEndPointAPI.saveEndPoint( endpoint );

    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //++++++++++++++++++++++++++++++PUBLISH++++++++++++++++++++++++++++

    //Getting test data
    List<Contentlet> contentlets = contentletAPI.findAllContent( 0, 1 );
    //Validations
    assertNotNull( contentlets );
    assertEquals( contentlets.size(), 1 );

    //Preparing the url in order to push content
View Full Code Here

     */
    @Test
    public void addRemoveContentToIndex () throws Exception {

        ContentletIndexAPI indexAPI = APILocator.getContentletIndexAPI();
        ContentletAPI contentletAPI = APILocator.getContentletAPI();

        //Creating a test structure
        Structure testStructure = loadTestStructure();
        //Creating a test contentlet
        Contentlet testContentlet = loadTestContentlet( testStructure );

        try {

            //And add it to the index
            indexAPI.addContentToIndex( testContentlet );

            //We are just making time in order to let it apply the index
            contentletAPI.isInodeIndexed( testContentlet.getInode(), true );

            //Verify if it was added to the index
            String query = "+structureName:" + testStructure.getVelocityVarName() + " +deleted:false +live:true";
            List<Contentlet> result = contentletAPI.search( query, 0, -1, "modDate desc", user, true );

            //Validations
            assertNotNull( result );
            assertTrue( !result.isEmpty() );

            //Remove the contentlet from the index
            indexAPI.removeContentFromIndex( testContentlet );

            //We are just making time in order to let it apply the index
            wasContentRemoved( query );

            //Verify if it was removed to the index
            result = contentletAPI.search( query, 0, -1, "modDate desc", user, true );

            //Validations
            assertTrue( result == null || result.isEmpty() );
        } finally {
            APILocator.getContentletAPI().delete( testContentlet, user, false );
View Full Code Here

TOP

Related Classes of com.dotmarketing.portlets.contentlet.business.ContentletAPI

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.