Package com.dotmarketing.portlets.structure.model

Examples of com.dotmarketing.portlets.structure.model.Field


        // Save the fields

       
        // Comment Title
        Field field = new Field();
        field.setFieldName("Title");
        field.setVelocityVarName("title");
        field.setFieldContentlet("text1");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setIndexed(true);
        field.setRequired(true);
        field.setListed(true);
        field.setSortOrder(0);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);
             

        // UserId
        field = new Field();
        field.setFieldName("UserId");
        field.setVelocityVarName("userid");
        field.setFieldContentlet("text2");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(2);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

       
        // Author
        field = new Field();
        field.setFieldName("Author");
        field.setVelocityVarName("author");
        field.setFieldContentlet("text3");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(3);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

       
        // Email
        field = new Field();
        field.setFieldName("Email");
        field.setVelocityVarName("email");
        field.setFieldContentlet("text4");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(4);
        field.setIndexed(true);
        field.setRequired(true);
        field.setListed(true);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

       
        // Website
        field = new Field();
        field.setFieldName("Website");
        field.setVelocityVarName("website");
        field.setFieldContentlet("text5");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(5);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

        // Comment
        field = new Field();
        field.setFieldName("Comment");
        field.setVelocityVarName("comment");
        field.setFieldContentlet("text_area1");
        field.setFieldType("wysiwyg");
        field.setStructureInode(commentsStructureInode);
        field.setIndexed(true);
        field.setRequired(true);
        field.setSortOrder(6);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

       
        // Email Responses
        field = new Field();
        field.setFieldName("Email Response");
        field.setVelocityVarName("emailResponse");
        field.setFieldContentlet("text6");
        field.setFieldType("radio");
        field.setValues("Yes|yes\r\nNo|no");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(7);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);

       
        // IP Address
        field = new Field();
        field.setFieldName("IP Address");
        field.setVelocityVarName("ipAddress");
        field.setFieldContentlet("text7");
        field.setFieldType("text");
        field.setStructureInode(commentsStructureInode);
        field.setSortOrder(8);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);
       
       
        // Date
        field = new Field();
        field.setFieldName("DatePublished");
        field.setVelocityVarName("datePublished");
        field.setFieldContentlet("date1");
        field.setFieldType("date_time");
        field.setStructureInode(commentsStructureInode);
        field.setIndexed(true);
        field.setRequired(false);
        field.setListed(false);
        field.setSortOrder(9);
        field.setFixed(true);
        field.setReadOnly(true);
        FieldFactory.saveField(field);
        fields.add(field);
        FieldsCache.removeFields(commentsStructure);
        FieldsCache.addFields(commentsStructure,fields);
      } catch (DotHibernateException e) {
View Full Code Here


        Contentlet contentlet = new Contentlet();
      contentlet = conAPI.find(inode, APILocator.getUserAPI().getSystemUser(), respectFrontendRoles);

      Structure contentletStructure = StructureCache.getStructureByInode(contentlet.getStructureInode());

        Field field =  contentletStructure.getField("CommentsCount");
        if (!InodeUtils.isSet(field.getInode())){
          return 0;
        }
        if(field.getFieldContentlet().startsWith(Field.DataType.TEXT.toString())){
            commentNumber = Integer.parseInt(contentlet.getStringProperty(field.getVelocityVarName())) ;
           
        }else {
          commentNumber = new Long(contentlet.getLongProperty(field.getVelocityVarName())).intValue();
        }
       
        }catch(DotDataException e){
                Logger.error(this, "Unable to look up contentlet with inode " + inode, e);
        }catch (DotSecurityException se) {
View Full Code Here

      if (0 < hits.size()) {
        Contentlet cont = hits.get(0);
        String structInode = (String) cont.getMap().get("stInode");
        List<Field> fields = FieldsCache.getFieldsByStructureInode(structInode);
        Field field = null;
        for(Field f : fields) {
                if("averageRating".equals(f.getVelocityVarName())){
                    field = f;
                    break;
                }
            }
        if(field == null || (!InodeUtils.isSet(field.getInode())) ){
            return 0;
        }
        String avg = cont.getMap().get(field.getVelocityVarName()).toString();

        try {
          average = Float.parseFloat(avg);
        } catch (Exception e) {
          average = 0F;
View Full Code Here

      if (0 < hits.size()) {
        Contentlet cont  = hits.get(0);
        String structInode = (String) cont.getMap().get("stInode");

                List<Field> fields = FieldsCache.getFieldsByStructureVariableName(structInode);
                Field field = null;
                for(Field f : fields) {
                    if("averageRating".equals(f.getVelocityVarName())){
                        field = f;
                        break;
                    }
                }
                if(field == null || (!InodeUtils.isSet(field.getInode()))){
                    return "";
                }

        votesNumber = cont.getMap().get(field.getVelocityVarName()).toString();
      }
    } catch (Exception ex) {
      Logger.error(RatingAPI.class, "getRatingVotesNumber: Error Searching Contentlets - lucene query: " + query, ex);
    }
View Full Code Here

      }

      for (; parameterNames.hasMoreElements();) {
        parameterName = parameterNames.nextElement();
        Field  field = st.getFieldVar(parameterName);
        String fieldTypeStr = field!=null?field.getFieldType():"";
        Field.FieldType fieldType =  Field.FieldType.getFieldType(fieldTypeStr);
        String[] fieldValues = request.getParameterValues(parameterName);
        String value = "";
        if(fieldValues.length>1){
          for(String val:fieldValues){
            value+=","+val;
          }
          parameters.put(parameterName,value.substring(1));
        }else{
          parameters.put(parameterName,fieldValues[0]);
        }

        if(fieldType == null || (fieldType!=null && !fieldType.equals(Field.FieldType.IMAGE) && !fieldType.equals(Field.FieldType.FILE)&& !fieldType.equals(Field.FieldType.BINARY))){
          parametersName.add(parameterName);
          String[] vals = request.getParameterValues(parameterName);
          values.add(vals);
          if(!parameterName.equals("dispatch") && !parameterName.equals("captcha") && !parameterName.equals("options") && !parameterName.equals("structure") && !parameterName.equals("userId") && !parameterName.equals("referrer")){
            if(!SubmitContentUtil.imageOrFileParam(st, parameterName) && !UtilMethods.isImage(parameterName)){
              for(String val : vals){
                if(val.length() < 512) {
                  paramsBuff.append("&").append(parameterName).append("=").append(encoder.encode(val));
                }
              }
            }
          }
        }
        else {
          parametersfileName.add(parameterName);
          String[] vals = request.getParameterValues(parameterName);
          filevalues.add(vals);

          if(!parameterName.equals("dispatch") && !parameterName.equals("captcha") && !parameterName.equals("options") && !parameterName.equals("structure") && !parameterName.equals("userId") && !parameterName.equals("referrer")){
            if(!SubmitContentUtil.imageOrFileParam(st, parameterName)){
              for(String val : vals){
                paramsBuff.append("&").append(parameterName).append("=").append(encoder.encode(val));
              }
            }
          }
        }
      }

      params=paramsBuff.toString();

      /*
       * Checking for captcha
       */
      if(useCaptcha){

        if(!CaptchaUtil.isValidImageCaptcha(request)){
          User user = com.liferay.portal.util.PortalUtil.getUser(request);
          String mes=LanguageUtil.get(user, "org.dotcms.frontend.content.submission.captcha.validation.image");
          mes = mes.replace(":", "");
          errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.contentlet.required", mes));
          saveMessages(session, errors);
          if(errors.size() > 0 && UtilMethods.isSet(params)){
            referrer=referrer+"?"+params.substring(1);
            af = new ActionForward(referrer);
            af.setRedirect(true);
          }
          return af;
        }

      }

      if(useAudioCaptcha){

        if(!CaptchaUtil.isValidAudioCaptcha(request)){
          errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.contentlet.required","Validation Sound"));
          saveMessages(session, errors);
          if(errors.size() > 0 && UtilMethods.isSet(params)){
            referrer=referrer+"?"+params.substring(1);
            af = new ActionForward(referrer);
            af.setRedirect(true);
          }
          return af;
        }
      }

      /**
       * Get Categories
       */
      ArrayList<Category> cats = new ArrayList<Category>();
      String[] arr = request.getParameterValues("categories") == null?new String[0]:request.getParameterValues("categories");
      if (arr != null && arr.length > 0) {
        for (int i = 0; i < arr.length; i++) {
          if(UtilMethods.isSet(arr[i])){
            Category c = catAPI.find(arr[i], SubmitContentUtil.getUserFromId(userId), true);
            if(UtilMethods.isSet(c))
              cats.add(c);
          }
        }
      }

      for (int i = 0; i < parametersName.size(); ++i) {
        Field field = st.getFieldVar(parametersName.get(i));
        String[] fieldValue = values.get(i);
        int size = 0;
                if(fieldValue!= null && !fieldValue[0].equals("") ){
                  size=1;
          if (fieldValue[0].contains(",")) {
            String[] fieldValueaux = fieldValue[0].split(",");
            fieldValue = fieldValueaux;
            size = fieldValue.length;
          }
         }

        for (int j = 0; j < size; j++) {
          if ((field != null)&& (field.getFieldType() != null)&& (field.getFieldType().equals(Field.FieldType.CATEGORY.toString()))){
            Category c = catAPI.find(com.dotmarketing.util.VelocityUtil.cleanVelocity(fieldValue[j].trim()),SubmitContentUtil.getUserFromId(userId), true);
            if(UtilMethods.isSet(c))
              cats.add(c);
          }

        }
      }

      List<Map<String,Object>> fileParameters = new ArrayList<Map<String,Object>>();

      DotContentletValidationException cve = new DotContentletValidationException("Contentlet's fields are not valid");
      boolean hasError = false;

      /**
       * Get image fields
       */
      imageFields = StructureFactory.getImagesFieldsList(st, parametersfileName, filevalues);
      if(imageFields.size() > 0){

        for(Field f : imageFields){
          java.io.File uploadedFile = uploadReq.getFile(f.getVelocityVarName());
          String title = uploadReq.getFileName(f.getVelocityVarName());
          if(f.isRequired() && !UtilMethods.isSet(title)){
            cve.addRequiredField(f);
            hasError = true;
            continue;
          }
          if(uploadedFile!=null && uploadedFile.length()> 0){
            String contentType = uploadReq.getContentType(f.getVelocityVarName());
            if(contentType.equals("image/png") || contentType.equals("image/gif") || contentType.equals("image/jpeg")){
              Map<String,Object> temp = new HashMap<String,Object>();
              temp.put("field", f);
              temp.put("title", title);
              temp.put("file", uploadedFile);
              temp.put("host", host);
              fileParameters.add(temp);
            }else{
              cve.addBadTypeField(f);
              hasError = true;
              imageNames.add(title);
              continue;
            }
          }
        }
      }

      /**
       * Get file fields
       */
      //http://jira.dotmarketing.net/browse/DOTCMS-3463
      Map <String, Object> tempBinaryValues= new HashMap <String, Object>();
      fileFields = StructureFactory.getFilesFieldsList(st, parametersfileName, filevalues);
      List <Field> fields = st.getFields();
      for(Field field:fields){
        Map <String, Object> binaryvalues= new HashMap <String, Object>();
        if (field.getFieldType().equals("binary"))
        {
          tempBinaryValues=processBinaryTempFileUpload( field.getVelocityVarName(), request, field.getFieldContentlet()) ;
          binaryvalues.put("field", field);
          parametersName.add(tempBinaryValues.get("parameterName").toString());
          Object ob = tempBinaryValues.get("parameterValues");
          if(ob != null){
            File f = (File)ob;
            binaryvalues.put("file", f);
            values.add(new String []{f.getAbsolutePath()});
          }else{
            binaryvalues.put(field.getVelocityVarName(), null);
            values.add(new String []{""});
          }
          fileParameters.add(binaryvalues);
        }

View Full Code Here

   * @param value The field value
   * @throws DotDataException
   */
  private static void setField(Structure structure, Contentlet contentlet, String fieldName, String[] values) throws DotDataException{

    Field field = structure.getFieldVar(fieldName);
    String value="";
    if(UtilMethods.isSet(field) && APILocator.getFieldAPI().valueSettable(field)){
      try{
        if(field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())){
          value = VelocityUtil.cleanVelocity(values[0]);
          Host host = APILocator.getHostAPI().find(value, APILocator.getUserAPI().getSystemUser(), false);
          if(host!=null && InodeUtils.isSet(host.getIdentifier())){
            contentlet.setHost(host.getIdentifier());
            contentlet.setFolder(FolderAPI.SYSTEM_FOLDER);
          }else{
            Folder folder = APILocator.getFolderAPI().find(value, APILocator.getUserAPI().getSystemUser(), false);
            if(folder!=null && InodeUtils.isSet(folder.getInode())){
              contentlet.setHost(folder.getHostId());
              contentlet.setFolder(folder.getInode());
            }
          }
        }else if(field.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString()) || field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())){
          if (field.getFieldContentlet().startsWith("float") || field.getFieldContentlet().startsWith("integer")) {
            value = values[0];
          } else {
            for(String temp : values){
              value = temp+","+value;
            }
          }
        }else if(field.getFieldType().equals(Field.FieldType.DATE.toString())){
          value = VelocityUtil.cleanVelocity(values[0]);
          if(value instanceof String){
            if(UtilMethods.isSet(customDatePattern)){
              Date dateValue = new SimpleDateFormat(customDatePattern).parse(value);
              conAPI.setContentletProperty(contentlet, field, dateValue);
              return;
            }
            value = value+" 00:00:00";
          }
        }else if(field.getFieldType().equals(Field.FieldType.DATE_TIME.toString())){
          value = VelocityUtil.cleanVelocity(values[0]);
          if(value instanceof String){
            if(UtilMethods.isSet(customDateTimePattern)){
              Date dateTimeValue = new SimpleDateFormat(customDateTimePattern).parse(value);
              conAPI.setContentletProperty(contentlet, field, dateTimeValue);
View Full Code Here

  private static Contentlet setAllFields(String structureName, List<String> parametersName, List<String[]> values) throws DotDataException{
    LanguageAPI lAPI = APILocator.getLanguageAPI();
    Structure st = StructureCache.getStructureByName(structureName);
    String contentletInode = null;
    long contentLanguageId = 1;
    Field fileField = new Field(),imageField=new Field(),binaryField=new Field();
    List<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
    for (Field field : fields) {
      if(parametersName.contains(field.getVelocityVarName()+"oldFileInode"))
        fileField =field;
      else if(parametersName.contains(field.getVelocityVarName()+"oldImageInode"))
        imageField= field;
      else if(parametersName.contains(field.getVelocityVarName()+"oldBinaryInode"))
        binaryField= field;
    }
   
    for(int i=0; i < parametersName.size(); i++){
      if(parametersName.get(i).equals("customDatePattern"))
        customDatePattern = values.get(i)[0];
      if(parametersName.get(i).equals("customDateTimePattern"))
        customDateTimePattern = values.get(i)[0];
      if(parametersName.get(i).equals("contentLanguageId"))
        contentLanguageId = Long.parseLong(values.get(i)[0]);
    }
   
      
    Contentlet contentlet = new Contentlet();
    contentlet.setStructureInode(st.getInode());
    contentlet.setLanguageId(contentLanguageId);

    for(int i=0; i < parametersName.size(); i++){
      String fieldname = parametersName.get(i);
      String[] fieldValue = values.get(i);
      setField(st, contentlet, fieldname, fieldValue);
     
      //To Update Content
      if(fieldname.equalsIgnoreCase("contentIdentifier"))
        contentlet.setIdentifier(VelocityUtil.cleanVelocity(values.get(i)[0]));
      else if(fieldname.equalsIgnoreCase("contentInode"))
        contentletInode = VelocityUtil.cleanVelocity(values.get(i)[0]);
      else if(fieldname.equalsIgnoreCase(fileField.getVelocityVarName()+"oldFileInode")){
        if(UtilMethods.isSet(VelocityUtil.cleanVelocity(values.get(i)[0]))){
          APILocator.getContentletAPI().setContentletProperty(contentlet, fileField, VelocityUtil.cleanVelocity(values.get(i)[0]));
        }
      }
      else if(fieldname.equalsIgnoreCase(imageField.getVelocityVarName()+"oldImageInode")){
        if(UtilMethods.isSet(VelocityUtil.cleanVelocity(values.get(i)[0]))){
          APILocator.getContentletAPI().setContentletProperty(contentlet, imageField, VelocityUtil.cleanVelocity(values.get(i)[0]));
        }
      }
      else if(fieldname.equalsIgnoreCase(binaryField.getVelocityVarName()+"oldBinaryInode")){
        if(UtilMethods.isSet(VelocityUtil.cleanVelocity(values.get(i)[0]))){
          User user = APILocator.getUserAPI().getSystemUser();
          try {
            File newFile = APILocator.getContentletAPI().getBinaryFile(contentletInode, binaryField.getVelocityVarName(), user);
            contentlet.setBinary(binaryField.getVelocityVarName(), newFile);
          } catch (Exception e) {
            Logger.debug(SubmitContentUtil.class, e.getMessage());
          }
        }
      }
View Full Code Here

          Logger.error(this, "Unable to look up content with inode " + inode, e);
        }
     
        Structure contentletStructure = StructureCache.getStructureByInode(contentlet.getStructureInode());
        Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);
          Field field;
         
          /* Validate if a NumberOfClicks field exists in the contentlet structure
           if not, then create it and populate it.*/
         
        if (!InodeUtils.isSet(contentletStructure.getField("NumberOfClicks").getInode())) {
         
          List<Field> fields = new ArrayList<Field>();
            field = new Field("NumberOfClicks", Field.FieldType.TEXT, Field.DataType.TEXT, contentletStructure,
                        false, false, true, Integer.MAX_VALUE, "0", "0", "",true, true, true);
          FieldFactory.saveField(field);
          fields.add(field);
          FieldsCache.removeFields(contentletStructure);
          FieldsCache.addFields(contentletStructure,fields);
         
        }
        
        /* Get the  value from the NumberOfClicks field for this contentlet, if the value
         * is null, then the field does not exists, otherwise increment its value by one
         * and set it to the contentlet.
         */
        field = contentletStructure.getField("NumberOfClicks");
       
        String countValue = (contentlet.getStringProperty(field.getVelocityVarName()) ==  null) ? field.getDefaultValue() : (String)contentlet.getStringProperty(field.getVelocityVarName());
        int numberOfClicks  = new Integer(countValue).intValue();
        contentlet.setStringProperty(field.getVelocityVarName(),String.valueOf(numberOfClicks));
        conAPI.checkin(contentlet,new HashMap<Relationship, List<Contentlet>>(),new ArrayList<Category>(),new ArrayList<Permission>() ,APILocator.getUserAPI().getSystemUser(),true);
        }
        ActionForward af = new ActionForward(SecurityUtils.stripReferer(request, redirectLink));
          af.setRedirect(true);
          return af;
View Full Code Here

     * http://jira.dotmarketing.net/browse/DOTCMS-3463
     *
     */
    if(fileParameters.size() > 0){
      for(Map<String,Object> value : fileParameters){
        Field field = (Field)value.get("field");
        java.io.File file = (java.io.File)value.get("file");
        if(file!=null){
          try {
            contentlet.setBinary(field.getVelocityVarName(), file);
          } catch (IOException e) {

          }
        }
        else if(field.isRequired()) {
            DotContentletValidationException cve = new DotContentletValidationException("Contentlet's fields are not valid");
            cve.addRequiredField(field);
            throw cve;
        }
         }
    }

    if (st.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
      contentlet.setHost(formHost.getIdentifier());
      Host host = APILocator.getHostAPI().find(formHost.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      if (!perAPI.doesUserHavePermissions(host,"PARENT:"+PermissionAPI.PERMISSION_READ+", CONTENTLETS:"+PermissionAPI.PERMISSION_WRITE+"", user)) {
        throw new DotSecurityException("User doesn't have write permissions to Contentlet");
      }
    }

    /**
     * If the moderator field is set, a work flow task is created
     */
    if(UtilMethods.isSet(moderatorRole)){

      if(!UtilMethods.isSet(contentlet.getStringProperty(Contentlet.WORKFLOW_ACTION_KEY)))
        contentlet.setStringProperty(Contentlet.WORKFLOW_ACTION_KEY, APILocator.getWorkflowAPI().findEntryAction(contentlet, user).getId());

      String contentletTitle = "";

          List<Field> fields = FieldsCache.getFieldsByStructureInode(contentlet.getStructureInode());

          for (Field fld : fields) {
                  if(fld.isListed()){
                      contentletTitle = contentlet.getMap().get(fld.getVelocityVarName()).toString();
                      contentletTitle = contentletTitle.length() > 250 ? contentletTitle.substring(0,250) : contentletTitle;
                  }
          }
      contentlet.setStringProperty(Contentlet.WORKFLOW_COMMENTS_KEY, "A new content titled \"" + UtilHTML.escapeHTMLSpecialChars(contentletTitle.trim()) +
          "\" has been posted by " + UtilHTML.escapeHTMLSpecialChars(user.getFullName()) + " ("+user.getEmailAddress()+")");

      contentlet.setStringProperty(Contentlet.WORKFLOW_ASSIGN_KEY, roleAPI.loadRoleByKey(moderatorRole).getId());
    }
   
    /*
    * Saving file and images
    */
    if(fileParameters.size() > 0) {
        for(Map<String,Object> value : fileParameters) {
             Field field = (Field)value.get("field");
             //http://jira.dotmarketing.net/browse/DOTCMS-3463
             if(field.getFieldType().equals(Field.FieldType.IMAGE.toString())||
                     field.getFieldType().equals(Field.FieldType.FILE.toString())){
               java.io.File uploadedFile = (java.io.File)value.get("file");
               try {
                 if(!UtilMethods.isSet(FileUtil.getBytes(uploadedFile)))
                   continue;
               } catch (IOException e) {
View Full Code Here

   * @param paramName
   * @return boolean
   */
  public static boolean imageOrFileParam(Structure structure, String paramName){

    Field field = structure.getFieldVar(paramName);
    if(UtilMethods.isSet(field) && (field.getFieldType().equals(Field.FieldType.FILE.toString()) || field.getFieldType().equals(Field.FieldType.IMAGE.toString()) || field.getFieldType().equals(Field.FieldType.BINARY.toString()))){
      return true;
    }
    return false;
  }
View Full Code Here

TOP

Related Classes of com.dotmarketing.portlets.structure.model.Field

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.