Package com.dotmarketing.portlets.structure.model

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


    }
    if (RegEX.contains(url, mastRegEx)) {
      boolean ADMIN_MODE = (session.getAttribute(com.dotmarketing.util.WebKeys.ADMIN_MODE_SESSION) != null);
      boolean EDIT_MODE = ((session.getAttribute(com.dotmarketing.util.WebKeys.EDIT_MODE_SESSION) != null) && ADMIN_MODE);

      Structure structure = null;
      User user = null;
      try {
        user = wuserAPI.getLoggedInUser(request);
      } catch (Exception e1) {
        Logger.error(URLMapFilter.class, e1.getMessage(), e1);
      }
 
      List<ContentletSearch> cons = null;
      Collections.sort(patternsCache, new Comparator<PatternCache>(){
        public int compare(PatternCache o1, PatternCache o2) {
          String regex1 = o1.getRegEx();
          String regex2 = o2.getRegEx();
          if(!regex1.endsWith("/")){
            regex1+="/";
          }
          if(!regex2.endsWith("/")){
            regex2+="/";
          }
       
          int regExLength1 = getSlashCount(regex1);
            int regExLength2 = getSlashCount(regex2);
          if(regExLength1 < regExLength2){
                return 1;
            }else if(regExLength1 > regExLength2){
                return -1;
              }else{
                return 0
              }
        }
      });
      for (PatternCache pc : patternsCache) {
        List<RegExMatch> matches = RegEX.findForUrlMap(url, pc.getRegEx());
        if (matches != null && matches.size() > 0) {
          query = new StringBuilder();
          List<RegExMatch> groups = matches.get(0).getGroups();
          List<String> fieldMatches = pc.getFieldMatches();
          structure = StructureCache.getStructureByInode(pc.getStructureInode());
          List<Field> fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
          query.append("+structureName:").append(structure.getVelocityVarName()).append(" +deleted:false ");
          if (EDIT_MODE || ADMIN_MODE) {
            query.append("+working:true ");
          } else {
            query.append("+live:true ");
          }

          // Set Host Stuff
          boolean hasHostField = false;
          Boolean hostIsRequired = false;
          for (Field field : fields) {
            if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
              hasHostField = true;
              if (field.isRequired()) {
                hostIsRequired = true;
              }
              break;
            }
          }
          if (hasHostField) {
            if (host != null) {
              //if (hostIsRequired) {
              //query.append("+conhost:" + host.getIdentifier() + " ");
              //} else {
              try {
                query.append("+(conhost:").append(host.getIdentifier()).append(" ")
                     .append("conhost:").append(whostAPI.findSystemHost(wuserAPI.getSystemUser(), true).getIdentifier()).append(") ");
              } catch (Exception e) {
                Logger.error(URLMapFilter.class, e.getMessage()
                    + " : Unable to build host in query : ", e);
              }
              //}
            }
          }

          // build fields
          int counter = 0;
          for (RegExMatch regExMatch : groups) {
            String value = regExMatch.getMatch();
            if (value.endsWith("/")) {
              value = value.substring(0, value.length() - 1);
            }
            query.append("+").append(structure.getVelocityVarName()).append(".").append(fieldMatches.get(counter)).append(":")
                .append(value).append(" ");
            counter++;
          }
         
          try {
              long sessionLang=WebAPILocator.getLanguageWebAPI().getLanguage(request).getId();
              long defaultLang=APILocator.getLanguageAPI().getDefaultLanguage().getId();
             
              boolean checkIndex=false;
           
                        if(request.getParameter("language_id")==null && Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE",false)) {
                            // consider default language. respecting language_id in parameters
                            query.append(" +(languageId:").append(defaultLang).append(" languageId:").append(sessionLang).append(") ");
                            checkIndex=true;
                        }
                        else {
                            // respect session language
                            query.append(" +languageId:").append(sessionLang).append(" ");
                        }
             
            cons = conAPI.searchIndex(query.toString(), 2, 0, (hostIsRequired?"conhost, modDate": "modDate"), user, true);
            int idx = 0;
            if(checkIndex && cons.size()==2) {
                // prefer session setting
                Contentlet second=conAPI.find(cons.get(1).getInode(), user, true);
                if(second.getLanguageId()==sessionLang)
                    idx=1;
            }
            ContentletSearch c = cons.get(idx);
            session.setAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE,String.valueOf(conAPI.find(c.getInode(), user, true).getLanguageId()));
            request.setAttribute(WebKeys.WIKI_CONTENTLET, c.getIdentifier());
            request.setAttribute(WebKeys.WIKI_CONTENTLET_INODE, c.getInode());
            request.setAttribute(WebKeys.CLICKSTREAM_IDENTIFIER_OVERRIDE, c.getIdentifier());
            request.setAttribute(WebKeys.WIKI_CONTENTLET_URL, url);
            String[] x = url.split("/");
            for(int i=0;i<x.length;i++){
              if(UtilMethods.isSet(x[i])){
                request.setAttribute("URL_ARG" + i, x[i]);
              }
            }
           
            break;
          } catch (DotDataException e) {
            Logger.warn(this, "DotDataException", e);
          } catch (DotSecurityException e) {
            Logger.warn(this, "DotSecurityException", e);
          } catch(java.lang.IndexOutOfBoundsException iob){
            Logger.warn(this, "No urlmap contentlent found uri:" + url + " query:" + query.toString());
          }catch(Exception e){
            Logger.warn(this, "No index?" + e.getMessage());
          }
        }
      }
     
   
      if (structure != null && UtilMethods.isSet(structure.getDetailPage())) {
        Identifier ident;
        try {
          ident = APILocator.getIdentifierAPI().find(structure.getDetailPage());
          if(ident ==null || ! UtilMethods.isSet(ident.getInode())){
            throw new DotRuntimeException("No valid detail page for structure '" + structure.getName() + "'. Looking for detail page id=" + structure.getDetailPage());
          }

         
          if((cons != null && cons.size() > 0) || !urlFallthrough){
           
View Full Code Here


        contentlet = conAPI.find(commentsOptions.get("contentInode"), user, true);
      }catch(DotDataException e){
        Logger.error(this, "Unable to look up comment with inode " + commentsOptions.get("contentInode"), e);
      }

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

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

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

      Contentlet contentletComment = new Contentlet();

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

      contentletComment.setLanguageId(beanContentlet.getLanguageId());

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

      Field field;

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

        field = commentsStructure.getFieldVar("title");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

      conAPI.setContentletProperty(contentletComment, field, comment);

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




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






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

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

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


      /* get the next in the order */
 
View Full Code Here

      String referrer,String userName,String userEmail,String userComment,String commentQuestion, HashMap<String, String> commentsOptions)
  {

    //This needs to be updated to use a lucene fix
    // Condition
    Structure commentsStructure = StructureCache.getStructureByVelocityVarName(CommentsWebAPI.commentsVelocityStructureName);
    Field field = commentsStructure.getFieldVar("emailResponse");
    String responseField = field.getFieldContentlet();

    //Get the Email Field
    field = commentsStructure.getFieldVar("email");
    String emailField = field.getVelocityVarName();

    //Get the Date Published Field
    field = commentsStructure.getFieldVar("datePublished");
    String dateField = field.getVelocityVarName();

    //Get the Email Response Field
    field = commentsStructure.getFieldVar("emailResponse");
    String emailResponseField = field.getVelocityVarName();

    // Order
    String order = "";
View Full Code Here

      /**
       * Getting content structure
       */
      String structureInode = request.getParameter("structure");
      Structure st = StructureCache.getStructureByInode(structureInode);


      /**
       * Getting options flags
       */
      String options = request.getParameter("options");
      if(UtilMethods.isSet(options)){
        options = PublicEncryptionFactory.decryptString(options);
        String[] opt = options.split(";");
        for(String text: opt){
          if(text.indexOf("contentUseCaptcha") != -1){
            useCaptcha = Boolean.parseBoolean(text.substring(text.indexOf("=")+1));
          }else if(text.indexOf("contentUseAudioCaptcha") != -1){
            useAudioCaptcha = Boolean.parseBoolean(text.substring(text.indexOf("=")+1));
          }else if(text.indexOf("contentAutoPublish") != -1){
            autoPublish = Boolean.parseBoolean(text.substring(text.indexOf("=")+1));
          }else if(text.indexOf("contentModeration") != -1){
            moderatorRole = text.substring(text.indexOf("=")+1);
          }
        }
      }

      /**
       * Setting content values
       */
      URLEncoder encoder = new URLEncoder();
      StringBuilder paramsBuff=new StringBuilder();
      List<String> parametersName = new ArrayList<String>();
      List<String[]> values = new ArrayList<String[]>();
      List<String> parametersfileName = new ArrayList<String>();
      List<String[]> filevalues = new ArrayList<String[]>();
      java.util.Enumeration<String> parameterNames = request.getParameterNames();
      Map <String, String> parameters=  new HashMap <String, String> ();
      String parameterName;
      String emailvalues;
      String []emailvaluessep;
      List <String> emails= new ArrayList <String>();
      if (st.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
        emailvalues = st.getFieldVar("formEmail").getValues();
        if(UtilMethods.isSet(emailvalues)){
          emailvalues = emailvalues.trim().toLowerCase();
        }
        else {
            emailvalues = "";
        }
        if (UtilMethods.isSet(emailvalues)) {
          if (emailvalues.contains(",")) {
            emailvaluessep = emailvalues.split(",");
            for (String email : emailvaluessep) {
              if(RegEX.contains(email.trim(),"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,}){1}$)"))
                emails.add(email.trim());
              else throw new Exception("The email list provided by the Form is incorrectly formmated, please enter on the Form properties a valid email addresses separated by a comma.");
            }
          }else
            if(RegEX.contains(emailvalues.trim(),"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,}){1}$)"))
              emails.add(emailvalues.trim());
            else throw new Exception("The email provided by the Form is incorrect, please enter on the Form properties valid email address. ");
        }

        parameters.put("formTitle", st.getFieldVar("formTitle").getValues());
        parameters.put("formEmail", emailvalues);
        parameters.put("formReturnPage", st.getFieldVar("formReturnPage").getValues());


      }

      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);
        }

      }
      if(fileFields.size() > 0){

        for(Field f : fileFields){
          java.io.File uploadedFile = uploadReq.getFile(f.getVelocityVarName());
          String title = uploadReq.getFileName(f.getVelocityVarName());
          fileNames.add(title);

          if(f.isRequired() && !UtilMethods.isSet(title)){
            cve.addRequiredField(f);
            hasError = true;
            continue;
          }
          if(uploadedFile!=null && uploadedFile.length()> 0) {
            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);
          }
        }
      }

      if(hasError){
        throw cve;
      }

      /**
       * Save content
       */
      Contentlet contentlet = SubmitContentUtil.createContent(st, cats, userId, parametersName, values, options, fileParameters, autoPublish, host, moderatorRole);



      message.add(Globals.MESSAGE_KEY, new ActionMessage("message.contentlet.save"));
      session.setAttribute(Globals.MESSAGE_KEY, message);

      HibernateUtil.commitTransaction();
      if(!APILocator.getContentletAPI().isInodeIndexed(contentlet.getInode())){
        Logger.error(this, "Unable to index contentlet");
      }
      if (st.getStructureType()== Structure.STRUCTURE_TYPE_FORM ){
        if(st.getFieldVar("formReturnPage")!= null && UtilMethods.isSet(st.getFieldVar("formReturnPage").getValues())){
          af.setPath(st.getFieldVar("formReturnPage").getValues());
        }
        if(UtilMethods.isSet(request.getParameter("formReturnPageOverride"))){
          af.setPath(request.getParameter("formReturnPageOverride"));
        }
        parameters.put("returnUrl", af.getPath());
View Full Code Here

          contentlet = conAPI.checkout(inode, APILocator.getUserAPI().getSystemUser(), true);
        }catch(DotDataException e){
          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);
View Full Code Here

   * @return Contentlet
   * @throws DotDataException
   */
  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);
View Full Code Here

   * @return Contentlet
   * @throws DotDataException
   */
  private static Contentlet setAllFields(String structureName, List<String> parametersName, List<String[]> values) throws DotDataException{

    Structure st = StructureCache.getStructureByName(structureName);
    Contentlet contentlet = new Contentlet();
    contentlet.setStructureInode(st.getInode());
    contentlet.setLanguageId(langAPI.getDefaultLanguage().getId());

    for(int i=0; i < parametersName.size(); i++){
      String fieldname = parametersName.get(i);
      String[] fieldValue = values.get(i);
View Full Code Here

   * @throws DotSecurityException
   * @deprecated this methods was deprecated because it hits the database, try to use the lucene search methods instead.
   */
  public List<Contentlet> getLastestContents(String structureType, String categoryName, int maxResults) throws DotDataException, DotSecurityException {
    Category category = categoryAPI.findByName(categoryName, user, true);
    Structure structure = StructureCache.getStructureByType(structureType);
    return getLastestContents(structure, category, maxResults);
  }
View Full Code Here

   * @throws DotSecurityException
   * @deprecated this methods was deprecated because it hits the database, try to use the lucene search methods instead.
   */
  public List<Contentlet> getLastestContents(String structureType, String categoryName) throws DotDataException, DotSecurityException {
    Category category = categoryAPI.findByName(categoryName, user, true);
    Structure structure = StructureCache.getStructureByType(structureType);
    return getLastestContents(structure, category);
  }
View Full Code Here

   * @return The field found
   * @deprecated This method was deprecated because it uses the presentation name of the field
   *              we encourage the use of the logical name of the field instead @see getFieldByLogicalName
   */
  public Field getFieldByName(String structureType, String fieldName) {
    Structure st = StructureCache.getStructureByType(structureType);
    return getFieldByName(st, fieldName);
  }
View Full Code Here

TOP

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

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.