Package com.dotmarketing.portlets.structure.model

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


  }

  private void _loadForm(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      FieldForm fieldForm = (FieldForm) form;
      Field field = (Field) req.getAttribute(WebKeys.Field.FIELD);

      String structureInode = field.getStructureInode();
      structureInode = (InodeUtils.isSet(structureInode) ? structureInode : req.getParameter("structureInode"));

      field.setStructureInode(structureInode);
      BeanUtils.copyProperties(fieldForm, field);

      if (fAPI.isElementDivider(field)) {
        fieldForm.setElement(FieldAPI.ELEMENT_DIVIDER);
      } else if (fAPI.isElementdotCMSTab(field)) {
        fieldForm.setElement(FieldAPI.ELEMENT_TAB);
      } else if (fAPI.isElementConstant(field)) {
        fieldForm.setElement(FieldAPI.ELEMENT_CONSTANT);
      } else {
        fieldForm.setElement(FieldAPI.ELEMENT_FIELD);
      }

      List<String> values = new ArrayList<String>();
      List<String> names = new ArrayList<String>();
      fieldForm.setDataType(field.getFieldContentlet().replaceAll("[0-9]*", ""));
      fieldForm.setFreeContentletFieldsValue(values);
      fieldForm.setFreeContentletFieldsName(names);
    } catch (Exception ex) {
      Logger.warn(EditFieldAction.class, ex.toString(),ex);
    }
View Full Code Here


    try {
      //Building a values HashMap based on the headers/columns position
      HashMap<Integer, Object> values = new HashMap<Integer, Object>();
      Set<Category> categories = new HashSet<Category> ();
      for (Integer column : headers.keySet()) {
        Field field = headers.get(column);
        if (line.length < column) {
          throw new DotRuntimeException("Incomplete line found, the line #" + lineNumber +
          " doesn't contain all the required columns.");
        }
        String value = line[column];
        Object valueObj = value;
        if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
          if (field.getFieldContentlet().startsWith("date")) {
            if(UtilMethods.isSet(value)) {
              try { valueObj = parseExcelDate(value) ;} catch (ParseException e) {
                throw new DotRuntimeException("Line #" + lineNumber + " contains errors, Column: " + field.getFieldName() +
                    ", value: " + value + ", couldn't be parsed as any of the following supported formats: " +
                    printSupportedDateFormats());
              }
            } else {
              valueObj = null;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.DATE_TIME.toString())) {
          if (field.getFieldContentlet().startsWith("date")) {
            if(UtilMethods.isSet(value)) {
              try { valueObj = parseExcelDate(value) ;} catch (ParseException e) {
                throw new DotRuntimeException("Line #" + lineNumber + " contains errors, Column: " + field.getFieldName() +
                    ", value: " + value + ", couldn't be parsed as any of the following supported formats: " +
                    printSupportedDateFormats());
              }
            } else {
              valueObj = null;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.TIME.toString())) {
          if (field.getFieldContentlet().startsWith("date")) {
            if(UtilMethods.isSet(value)) {
              try { valueObj = parseExcelDate(value) ;} catch (ParseException e) {
                throw new DotRuntimeException("Line #" + lineNumber + " contains errors, Column: " + field.getFieldName() +
                    ", value: " + value + ", couldn't be parsed as any of the following supported formats: " +
                    printSupportedDateFormats());
              }
            } else {
              valueObj = null;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.CATEGORY.toString()) || field.getFieldType().equals(Field.FieldType.CATEGORIES_TAB.toString())) {
          valueObj = value;
          if(UtilMethods.isSet(value)) {
            String[] categoryKeys = value.split(",");
            for(String catKey : categoryKeys) {
              Category cat = catAPI.findByKey(catKey.trim(), user, false);
              if(cat == null)
                throw new DotRuntimeException("Line #" + lineNumber + " contains errors, Column: " + field.getFieldName() +
                    ", value: " + value + ", invalid category key found, line will be ignored.");
              categories.add(cat);
            }
          }
        }
        else if (field.getFieldType().equals(Field.FieldType.CHECKBOX.toString()) ||
            field.getFieldType().equals(Field.FieldType.SELECT.toString()) ||
            field.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString()) ||
            field.getFieldType().equals(Field.FieldType.RADIO.toString())
        ) {
          valueObj = value;
          if(UtilMethods.isSet(value))
          {


            String fieldEntriesString = field.getValues()!=null ? field.getValues():"";
            String[] fieldEntries = fieldEntriesString.split("\n");
            boolean found = false;
            for(String fieldEntry : fieldEntries)
            {
              String entryValue = fieldEntry.split("\\|")[1].trim();

              if(entryValue.equals(value) || value.contains(entryValue))
              {
                found = true;
                break;
              }
            }
            if(!found)
            {
              throw new DotRuntimeException("Line #" + lineNumber + " contains errors, Column: " + field.getFieldName() +
                  ", value: " + value + ", invalid value found, line will be ignored.");
            }
          }
          else {
            valueObj = null;
          }
        }
        else if (field.getFieldType().equals(Field.FieldType.TEXT.toString())) {
          if (value.length() > 255)
            value = value.substring(0, 255);
          valueObj = value;
        } else {
          valueObj = value;
        }
        values.put(column, valueObj);
      }

      //Searching contentlets to be updated by key fields
      List<Contentlet> contentlets = new ArrayList<Contentlet>();
      String conditionValues = "";
      StringBuffer buffy = new StringBuffer();
      buffy.append("+structureInode:" + structure.getInode() + " +working:true +deleted:false");


      if (keyFields.size() > 0) {

        for (Integer column : keyFields.keySet()) {
          Field field = keyFields.get(column);
          Object value = values.get(column);
          String text = null;
          if (value instanceof Date || value instanceof Timestamp) {
            SimpleDateFormat formatter = null;
            if(field.getFieldType().equals(Field.FieldType.DATE.toString())
                || field.getFieldType().equals(Field.FieldType.DATE_TIME.toString()))
            {
                DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
              text = df.format((Date)value);
            } else if(field.getFieldType().equals(Field.FieldType.TIME.toString())) {
                DateFormat df = new SimpleDateFormat("HHmmss");
                            text = df.format((Date)value);
            } else {
              formatter = new SimpleDateFormat();
              text = formatter.format(value);
              Logger.warn(getClass(),"importLine: field's date format is undetermined.");
            }
          } else {
            text = value.toString();
          }
          if(!UtilMethods.isSet(text)){
            throw new DotRuntimeException("Line #" + lineNumber + " key field "+field.getFieldName()+" is required since it was defined as a key\n");
          }else{
            buffy.append(" +" +field.getFieldContentlet()+ ":"+ escapeLuceneSpecialCharacter(text));
            conditionValues += conditionValues + value + "-";
          }

          if(choosenKeyField.indexOf(field.getFieldName()) == -1){
            choosenKeyField.append(", "+field.getFieldName());
          }
        }
        contentlets = conAPI.checkoutWithQuery(buffy.toString(), user, true);
      }


      //Creating/updating content
      boolean isNew = false;
      if (contentlets.size() == 0) {
        newContentCounter++;
        isNew = true;
        //if (!preview) {
        Contentlet newCont = new Contentlet();
        newCont.setStructureInode(structure.getInode());
        newCont.setLanguageId(langAPI.getDefaultLanguage().getId());
        contentlets.add(newCont);
        //}
      } else {
        if (conditionValues.equals("") || !keyContentUpdated.contains(conditionValues)) {
          contentToUpdateCounter += contentlets.size();
          if (preview)
            keyContentUpdated.add(conditionValues);
        }
        if (contentlets.size() > 0) {
          myOutput.println("Line #" + lineNumber + ". The key fields choosen match more than one content, in this case: "
              + " matches: " + contentlets.size() + " different content(s), looks like the key fields choosen " +
          "aren't a real key.");
        }

      }


      for (Contentlet cont : contentlets)
      {
        //Fill the new contentlet with the data
        for (Integer column : headers.keySet()) {
          Field field = headers.get(column);
          Object value = values.get(column);
          conAPI.setContentletProperty(cont, field, value);
          if (field.getFieldType().equals(Field.FieldType.TAG.toString()) &&
              value instanceof String) {
            String[] tags = ((String)value).split(",");
            for (String tag : tags) {
              TagFactory.addTagInode((String)tag.trim(), cont.getInode(), "");
            }
          }
        }

        //Check the new contentlet with the validator
        try
        {
          conAPI.validateContentlet(cont,new ArrayList<Category>(categories));
        }
        catch(DotContentletValidationException ex)
        {
          StringBuffer sb = new StringBuffer("Line #" + lineNumber + " contains errors\n");
          HashMap<String,List<Field>> errors = (HashMap<String,List<Field>>) ex.getNotValidFields();
          Set<String> keys = errors.keySet();
          for(String key : keys)
          {
            sb.append(key + ": ");
            List<Field> fields = errors.get(key);
            for(Field field : fields)
            {
              sb.append(field.getFieldName() + ",");
            }
            sb.append("\n");
          }
          throw new DotRuntimeException(sb.toString());
        }
View Full Code Here

      Logger.warn(EditFieldAction.class, ex.toString(),ex);
    }
  }

  private void _deleteField(ActionForm form, ActionRequest req, ActionResponse res) {
    Field field = (Field) req.getAttribute(WebKeys.Field.FIELD);
    Structure structure = StructureFactory.getStructureByInode(field.getStructureInode());

    try {
            _checkUserPermissions(structure, _getUser(req), PERMISSION_PUBLISH);
        } catch (Exception ae) {
            if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
              String message = "message.insufficient.permissions.to.delete";
              SessionMessages.add(req, "error", message);
              return;
            }
        }
    // clean contentlet field in db
    try {
      String type = field.getFieldType();
      if (!fAPI.isElementConstant(field) && !Field.FieldType.LINE_DIVIDER.toString().equals(type)
          && !Field.FieldType.TAB_DIVIDER.toString().equals(type)
          && !Field.FieldType.RELATIONSHIPS_TAB.toString().equals(type)
          && !Field.FieldType.CATEGORIES_TAB.toString().equals(type)
          && !Field.FieldType.PERMISSIONS_TAB.toString().equals(type)
          && !Field.FieldType.HOST_OR_FOLDER.toString().equals(type)) {
        conAPI.cleanField(structure, field, APILocator.getUserAPI().getSystemUser(), false);
      }
      FieldFactory.deleteField(field);
      // Call the commit method to avoid a deadlock
      HibernateUtil.commitTransaction();
      FieldsCache.removeFields(structure);

      ActivityLogger.logInfo(ActivityLogger.class, "Delete Field Action", "User " + _getUser(req).getUserId() + "/" + _getUser(req).getFirstName() + " deleted field " + field.getFieldName() + " to " + structure.getName()
            + " Structure.", HostUtil.hostNameUtil(req, _getUser(req)));

      StructureCache.removeStructure(structure);
      StructureServices.removeStructureFile(structure);

      //Refreshing permissions
      PermissionAPI perAPI = APILocator.getPermissionAPI();
      if(field.getFieldType().equals("host or folder")) {
        conAPI.cleanHostField(structure, APILocator.getUserAPI().getSystemUser(), false);
        perAPI.resetChildrenPermissionReferences(structure);
      }
      StructureFactory.saveStructure(structure);
      // rebuild contentlets indexes
View Full Code Here

      while (enumeration.hasMoreElements()) {
        String parameterName = (String) enumeration.nextElement();
        if (parameterName.indexOf("order_") != -1) {
          String parameterValue = req.getParameter(parameterName);
          String fieldInode = parameterName.substring(parameterName.indexOf("_") + 1);
          Field field = FieldFactory.getFieldByInode(fieldInode);
          field.setSortOrder(Integer.parseInt(parameterValue));
          FieldFactory.saveField(field);

        }
      }
      FieldsCache.clearCache();
View Full Code Here

      throw new DotStateException("Cannot create base fileasset fields on a structure that doesn't exist");
    }
    if (structure.getStructureType() != Structure.STRUCTURE_TYPE_FILEASSET) {
      throw new DotStateException("Cannot create base fileasset fields on a structure that is not a file asset");
    }
    Field field = new Field(HOST_FOLDER_FIELD_NAME, Field.FieldType.HOST_OR_FOLDER, Field.DataType.TEXT, structure, true, false, true, 1,
        "", "", "", true, false, true);

    field.setVelocityVarName(HOST_FOLDER_FIELD);
    FieldFactory.saveField(field);

    field = new Field(BINARY_FIELD_NAME, Field.FieldType.BINARY, Field.DataType.BINARY, structure, true, false, false, 2, "", "", "", true,
        false, false);
    field.setVelocityVarName(BINARY_FIELD);
    FieldFactory.saveField(field);


    field = new Field(TITLE_FIELD_NAME, Field.FieldType.TEXT, Field.DataType.TEXT, structure, true, true, true, 3, "", "", "", true, false,
        true);
    field.setVelocityVarName(TITLE_FIELD);
    field.setListed(false);
    FieldFactory.saveField(field);


    field = new Field(FILE_NAME_FIELD_NAME, Field.FieldType.TEXT, Field.DataType.TEXT, structure, false, true, true, 4, "", "", "", true, true,
        true);
    field.setVelocityVarName(FILE_NAME_FIELD);
    FieldFactory.saveField(field);


    field = new Field(META_DATA_TAB_NAME, Field.FieldType.TAB_DIVIDER, Field.DataType.SECTION_DIVIDER, structure, false, false, false, 5, "", "", "", false,
        false, false);
    field.setVelocityVarName("MetadataTab");
    FieldFactory.saveField(field);


    field = new Field(META_DATA_FIELD_NAME, Field.FieldType.KEY_VALUE, Field.DataType.LONG_TEXT, structure, false, false, false, 6, "", "", "", true,
        true, true);
    field.setVelocityVarName(META_DATA_FIELD);
    FieldFactory.saveField(field);


    field = new Field(SHOW_ON_MENU_NAME, Field.FieldType.CHECKBOX, Field.DataType.TEXT, structure, false, false, true, 7, "|true", "false", "", true, false,
        false);
    field.setVelocityVarName(SHOW_ON_MENU);
    FieldFactory.saveField(field);


    field = new Field(SORT_ORDER_NAME, Field.FieldType.TEXT, Field.DataType.INTEGER, structure, false, false, true, 8, "", "0", "", true, false,
        false);
    field.setVelocityVarName(SORT_ORDER);
    FieldFactory.saveField(field);



    field = new Field(DESCRIPTION_NAME, Field.FieldType.TEXT, Field.DataType.TEXT, structure, false, true, true, 9, "", "", "", true, false,
        true);
    field.setVelocityVarName(DESCRIPTION);
    field.setListed(false);
    field.setSearchable(false);
    FieldFactory.saveField(field);

    FieldsCache.clearCache();
  }
View Full Code Here

          dbNumberOfVotes = Long.parseLong((String) map.get("votes_number"));
          Structure s = c.getStructure();
          if(s == null || !InodeUtils.isSet(s.getInode())){
            continue;
          }
          Field avgField = s.getFieldVar(AVERAGE_RATING_VAR_NAME);
          Field numOfVotesField = s.getFieldVar(NUMBER_OF_VOTES_VAR_NAME);
          if( avgField == null){
            avgField = s.getField("Average Rating");
          }
          if(numOfVotesField ==null){
            numOfVotesField = s.getField("Number Of Votes");
          }
          Float ctAvgFloat = new Float(0);
          Long ctNumberOfVotesObj = null;

          if(avgField != null && c != null){
            try{
              Object ctAvgObj = conAPI.getFieldValue(c, avgField);

              if(ctAvgObj instanceof String) {
                ctAvgFloat = Float.valueOf(((String) ctAvgObj));
              } else {
                ctAvgFloat =  (Float) ctAvgObj;
              }
            }
            catch(Exception e){
              Logger.error(UpdateRatingThread.class, e.getMessage(), e);
            }
          }
          if(numOfVotesField != null && c != null){
            ctNumberOfVotesObj = (Long) conAPI.getFieldValue(c, numOfVotesField);
          }
          if (UtilMethods.isSet(ctAvgFloat) && UtilMethods.isSet(ctNumberOfVotesObj)) {
            ctAvg = ctAvgFloat.floatValue();
            ctNumberOfVotes = ctNumberOfVotesObj.longValue();
            if(ctNumberOfVotes == dbNumberOfVotes){
              continue;
            }

          }
          else {

            struct = StructureCache.getStructureByInode(c.getStructureInode());
            fields = FieldsCache.getFieldsByStructureInode(struct.getInode());

            Field avfield = null;
            Field countfield = null;
            int fieldsSize = fields.size();
            for (int i = 0; i < fieldsSize; ++i) {
              if (fields.get(i).getFieldName().trim().equalsIgnoreCase("Average Rating"))
                avfield = fields.get(i);
              if (fields.get(i).getFieldName().trim().equalsIgnoreCase("Number Of Votes"))
                countfield = fields.get(i);
            }
            if (avfield ==null || countfield == null) {
              fields = FieldFactory.getFieldsByStructure(struct.getInode());
              fieldsSize = fields.size();
              for (int i = 0; i < fieldsSize; ++i) {
                if (fields.get(i).getFieldName().trim().equalsIgnoreCase("Average Rating"))
                  avfield = fields.get(i);
                if (fields.get(i).getFieldName().trim().equalsIgnoreCase("Number Of Votes"))
                  countfield = fields.get(i);
              }
            }

            if (avfield == null) {
              Field averageRatingField = new Field("Average Rating", FieldType.TEXT, DataType.FLOAT, struct, false, false, true, ++fieldsSize, true, true, false);
              averageRatingField.setVelocityVarName(AVERAGE_RATING_VAR_NAME);
              averageRatingField.setReadOnly(false);
              averageRatingField.setListed(false);
              averageRatingField.setSearchable(false);
              averageRatingField.setIndexed(true);
              try{
              averageRatingField.setDefaultValue(Integer.toString(Config.getIntProperty("RATING_MAX_VALUE", 10)));
              }
              catch(Exception e){
                Logger.error(this.getClass(), "unable to set default value for rating field:" + e);
              }
              FieldFactory.saveField(averageRatingField);
              FieldsCache.removeFields(struct);
              StructureCache.removeStructure(struct);
              StructureServices.removeStructureFile(struct);
              StructureFactory.saveStructure(struct);
            }

            if (countfield == null) {
              Field numberOfVotesField = new Field("Number Of Votes", FieldType.TEXT, DataType.INTEGER, struct, false, false, true, ++fieldsSize, true, true, false);
              numberOfVotesField.setVelocityVarName(NUMBER_OF_VOTES_VAR_NAME);
              numberOfVotesField.setReadOnly(false);
              numberOfVotesField.setListed(false);
              numberOfVotesField.setSearchable(false);
              numberOfVotesField.setIndexed(true);
              FieldFactory.saveField(numberOfVotesField);

              FieldsCache.removeFields(struct);
              StructureCache.removeStructure(struct);
              StructureServices.removeStructureFile(struct);
View Full Code Here

    ServletOutputStream out = httpRes.getOutputStream();
    ImportContentletsForm importForm = (ImportContentletsForm) form;

    List<Field> fields = FieldsCache.getFieldsByStructureInode(importForm.getStructure());
    for(int i = 0; i < fields.size(); i++) {
      Field field = fields.get(i);
      if (ImportUtil.isImportableField(field)) {
        String fieldName = field.getFieldName();
        if(fieldName.contains(","))
          out.print("\"" + fieldName + "\"");
        else
          out.print(fieldName);
        if(i < fields.size() - 1)
          out.print(",");
      }
    }
    out.print("\n");

    for(int i = 0; i < fields.size(); i++) {
      Field field = fields.get(i);
      if (ImportUtil.isImportableField(field)) {
        if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
          out.print("MM/dd/yyyy");
        }         
        else if (field.getFieldType().equals(Field.FieldType.DATE_TIME.toString())) {
          out.print("MM/dd/yyyy hh:mm aa");
        }          
        else if (field.getFieldType().equals(Field.FieldType.TIME.toString())) {
          out.print("hh:mm aa");
        }else if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
            out.print("Host/Folder Identifier");
        }else if (field.getFieldType().equals(Field.FieldType.CATEGORY.toString())) {
          out.print("Category Unique Key");
        } else {
          out.print("XXX");
        }
        if(i < fields.size() - 1)
View Full Code Here

      User systemUser = userAPI.getSystemUser();
      Host defaultHost = hostAPI.findDefaultHost(systemUser, false);
      Host systemHost = hostAPI.findSystemHost(systemUser, false);
      Contentlet contentlet;
      List<Field> fields;
      Field field = null;
      for(Map<String, String> inode: inodes) {
        contentlet = contentAPI.checkout(inode.get("inode"), systemUser, false);
        fields = FieldsCache.getFieldsByStructureInode(contentlet.getStructureInode());
        hostIsRequided = false;
        for (int i = 0; i < fields.size(); ++i) {
          field = fields.get(i);
          if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
            if (field.isRequired())
              hostIsRequided = true;
            break;
          }
        }

        if (hostIsRequided) {
          contentlet.setHost(defaultHost.getIdentifier());
          contentlet.setStringProperty(field.getVelocityVarName(), defaultHost.getIdentifier());
        } else {
          contentlet.setHost(systemHost.getIdentifier());
          contentlet.setStringProperty(field.getVelocityVarName(), systemHost.getIdentifier());
        }

        contentlet.setFolder(FolderAPI.SYSTEM_FOLDER);

        contentAPI.checkin(contentlet, systemUser, false);
View Full Code Here

  private synchronized Host createDefaultHost() throws DotDataException,
  DotSecurityException {
      Structure st = StructureCache.getStructureByVelocityVarName("Host");
    List<Field> fields = FieldsCache.getFieldsByStructureInode(st.getInode());
    Field isDefault = null;
      for(Field f : fields){
        if("isDefault".equalsIgnoreCase(f.getVelocityVarName())){
          isDefault=f;
        }

      }


    User systemUser = APILocator.getUserAPI().getSystemUser();



    DotConnect dc = new DotConnect();
    dc.setSQL("select working_inode from contentlet_version_info join contentlet on (contentlet.inode = contentlet_version_info.working_inode) " +
          " where " + isDefault.getFieldContentlet() +" = ? and structure_inode =?");
    dc.addParam(true);
    dc.addParam(st.getInode());

    Host defaultHost = new Host();
View Full Code Here

        HibernateUtil.startTransaction();

        //Create the new structure
        Structure testStructure = createStructure( "JUnit Test Categories Structure_" + String.valueOf( new Date().getTime() ), "junit_test_categories_structure_" + String.valueOf( new Date().getTime() ) );
        //Add a Text field
        Field textField = new Field( "JUnit Test Text", Field.FieldType.TEXT, Field.DataType.TEXT, testStructure, false, true, true, 1, false, false, false );
        FieldFactory.saveField( textField );
        //Add a Category field
        Field categoryField = new Field( "JUnit Movies", Field.FieldType.CATEGORY, Field.DataType.TEXT, testStructure, true, true, true, 2, false, false, true );
        categoryField.setValues( parentCategory.getInode() );
        FieldFactory.saveField( categoryField );

        //***************************************************************
        //Set up a content for the categories structure
        Contentlet contentlet = new Contentlet();
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.