/**
   * Verifies what we were doing to the current bundle, it was received for this server?, or this
   * server is trying to send it...., we don't want to retry bundles we received.
   *
   * @param request
   * @param config
   * @return
   */
  private Boolean sendingBundle(
      HttpServletRequest request, PushPublisherConfig config, String bundleId)
      throws DotDataException {

    // Get the local address
    String remoteIP = request.getRemoteHost();
    int port = request.getLocalPort();
    if (!UtilMethods.isSet(remoteIP)) {
      remoteIP = request.getRemoteAddr();
    }

    /*
    Getting the bundle end points in order to compare if this current server it is an end point or not.
    If it is is because we received this bundle as we were a targeted end point server.
    */

    List<Environment> environments =
        APILocator.getEnvironmentAPI().findEnvironmentsByBundleId(bundleId);

    for (Environment environment : environments) {

      List<PublishingEndPoint> endPoints =
          APILocator.getPublisherEndPointAPI()
              .findSendingEndPointsByEnvironment(environment.getId());
      for (PublishingEndPoint endPoint : endPoints) {

        // Getting the end point details
        String endPointAddress = endPoint.getAddress();
        String endPointPort = endPoint.getPort();

        if (endPointAddress.equals(remoteIP) && endPointPort.equals(String.valueOf(port))) {
          return false;
        }
      }
    }

    return true;
  }
Example #2
0
  public static void fixImagesTable() throws SQLException {
    DotConnect dc = new DotConnect();
    List<String> imageIds = new ArrayList<String>();
    final String selectImageIdsSQL = "select i.imageid from image i";
    String deleteImageSQL = "delete from image where imageid like '' or imageid is null";
    dc.setSQL(selectImageIdsSQL);
    List<HashMap<String, String>> results = null;
    try {
      results = dc.getResults();
    } catch (DotDataException e) {
      Logger.error(MaintenanceUtil.class, e.getMessage(), e);
    }
    for (HashMap<String, String> r : results) {
      imageIds.add(r.get("imageid").toString());
    }

    for (int i = 0; i < imageIds.size(); i++) {
      if (!UtilMethods.isSet(imageIds.get(i))) {
        dc.setSQL(deleteImageSQL);
        dc.getResult();
      }
    }
  }
Example #3
0
 /** Description of the Method */
 public boolean sendMessage() {
   MimeMultipart mp = new MimeMultipart();
   try {
     // if there is a text and an html section
     if (sendingText.getCount() > 1) {
       sendingText.setSubType("alternative");
     }
     // if we are sending attachments
     if (sendingAttachments.getCount() > 0) {
       MimeBodyPart bp = new MimeBodyPart();
       bp.setContent(sendingAttachments);
       mp.addBodyPart(bp, 0);
       bp = new MimeBodyPart();
       bp.setContent(sendingText);
       mp.addBodyPart(bp, 0);
     } else {
       mp = sendingText;
     }
     Logger.debug(this, "Getting the MailContext.");
     /*
      *
      * Get the mail session from
      *
      * the container Context
      */
     Session session = null;
     Context ctx = null;
     try {
       ctx = (Context) new InitialContext().lookup("java:comp/env");
       session = (javax.mail.Session) ctx.lookup("mail/MailSession");
     } catch (Exception e1) {
       try {
         Logger.debug(this, "Using the jndi intitialContext().");
         ctx = new InitialContext();
         session = (javax.mail.Session) ctx.lookup("mail/MailSession");
       } catch (Exception e) {
         Logger.error(this, "Exception occured finding a mailSession in JNDI context.");
         Logger.error(this, e1.getMessage(), e1);
         return false;
       }
     }
     if (session == null) {
       Logger.debug(this, "No Mail Session Available.");
       return false;
     }
     Logger.debug(
         this, "Delivering mail using: " + session.getProperty("mail.smtp.host") + " as server.");
     MimeMessage message = new MimeMessage(session);
     message.addHeader("X-RecipientId", String.valueOf(getRecipientId()));
     if ((fromEmail != null) && (fromName != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail, fromName));
     } else if ((fromEmail != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail));
     }
     if (toName != null) {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient, toName));
       }
     } else {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(cc)) {
       String[] recipients = cc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.CC, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(bcc)) {
       String[] recipients = bcc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));
       }
     }
     message.setSubject(subject, encoding);
     message.setContent(mp);
     Transport.send(message);
     result = "Send Ok";
     return true;
   } catch (javax.mail.SendFailedException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.SendFailedException:")
                 + "javax.mail.SendFailedException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (MessagingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.MessagingException:")
                 + "javax.mail.MessagingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (UnsupportedEncodingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("java.io.UnsupportedEncodingException:")
                 + "java.io.UnsupportedEncodingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   }
 }
Example #4
0
  @SuppressWarnings("unchecked")
  public static InputStream buildStream(HTMLPage htmlPage, Identifier identifier, boolean EDIT_MODE)
      throws DotDataException, DotSecurityException {
    String folderPath = (!EDIT_MODE) ? "live/" : "working/";
    InputStream result;
    StringBuilder sb = new StringBuilder();

    ContentletAPI conAPI = APILocator.getContentletAPI();
    Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, EDIT_MODE);
    if (cmsTemplate == null || !InodeUtils.isSet(cmsTemplate.getInode())) {
      Logger.error(
          This.class,
          "PAGE DOES NOT HAVE A VALID TEMPLATE (template unpublished?) : page id "
              + htmlPage.getIdentifier()
              + ":"
              + identifier.getURI());
    }

    // gets pageChannel for this path
    java.util.StringTokenizer st =
        new java.util.StringTokenizer(String.valueOf(identifier.getURI()), "/");
    String pageChannel = null;
    if (st.hasMoreTokens()) {
      pageChannel = st.nextToken();
    }

    // set the page cache var
    if (htmlPage.getCacheTTL() > 0 && LicenseUtil.getLevel() > 99) {
      sb.append("#set($dotPageCacheDate = \"").append(new java.util.Date()).append("\")");
      sb.append("#set($dotPageCacheTTL = \"").append(htmlPage.getCacheTTL()).append("\")");
    }

    // set the host variables
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();

    Host host = htmlPageAPI.getParentHost(htmlPage);
    sb.append("#if(!$doNotParseTemplate)");
    sb.append("$velutil.mergeTemplate('")
        .append(folderPath)
        .append(host.getIdentifier())
        .append(".")
        .append(Config.getStringProperty("VELOCITY_HOST_EXTENSION"))
        .append("')");
    sb.append(" #end ");

    // creates the context where to place the variables
    // Build a context to pass to the page
    sb.append("#if(!$doNotSetPageInfo)");
    sb.append("#set ( $quote = '\"' )");
    sb.append("#set ($HTMLPAGE_INODE = \"")
        .append(String.valueOf(htmlPage.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_IDENTIFIER = \"")
        .append(String.valueOf(htmlPage.getIdentifier()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_TITLE = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append(
            "#set ($HTMLPAGE_FRIENDLY_NAME = \""
                + UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");
    sb.append("#set ($TEMPLATE_INODE = \"")
        .append(String.valueOf(cmsTemplate.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getMetadata()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"#fixBreaks($HTMLPAGE_META)\")");

    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoDescription()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"#fixBreaks($HTMLPAGE_DESCRIPTION)\")");

    sb.append("#set ($HTMLPAGE_KEYWORDS = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoKeywords()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_KEYWORDS = \"#fixBreaks($HTMLPAGE_KEYWORDS)\")");

    sb.append("#set ($HTMLPAGE_SECURE = \"")
        .append(String.valueOf(htmlPage.isHttpsRequired()))
        .append("\" )");
    sb.append("#set ($VTLSERVLET_URI = \"")
        .append(UtilMethods.encodeURIComponent(identifier.getURI()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_REDIRECT = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getRedirect()))
        .append("\" )");

    sb.append("#set ($pageTitle = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append("#set ($pageChannel = \"").append(pageChannel).append("\" )");
    sb.append("#set ($friendlyName = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");

    Date moddate = null;
    if (UtilMethods.isSet(htmlPage.getModDate())) {
      moddate = htmlPage.getModDate();
    } else {
      moddate = htmlPage.getStartDate();
    }

    moddate = new Timestamp(moddate.getTime());

    sb.append("#set ($HTML_PAGE_LAST_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append("#set ($HTMLPAGE_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append(" #end ");

    // get the containers for the page and stick them in context
    // List identifiers = InodeFactory.getChildrenClass(cmsTemplate, Identifier.class);

    List<Container> containerList =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);

    Iterator i = containerList.iterator();
    while (i.hasNext()) {
      Container ident = (Container) i.next();

      Container c = null;
      if (EDIT_MODE) {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findWorkingVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      } else {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findLiveVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      }
      // sets container to load the container file
      sb.append("#set ($container")
          .append(ident.getIdentifier())
          .append(" = \"")
          .append(folderPath)
          .append(ident.getIdentifier())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"))
          .append("\" )");

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean dynamicContainer = UtilMethods.isSet(c.getLuceneQuery());

      int langCounter = 0;

      List<Contentlet> contentlets = new ArrayList<Contentlet>();
      List<Contentlet> contentletsFull = new ArrayList<Contentlet>();
      if (!dynamicContainer) {
        Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
        Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
        // The container doesn't have categories
        try {
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getId(),
                  idenContainer.getId(),
                  sort,
                  EDIT_MODE,
                  -1,
                  APILocator.getUserAPI().getSystemUser(),
                  false);
          if (EDIT_MODE) contentletsFull = contentlets;
          else
            contentletsFull =
                conAPI.findPageContentlets(
                    idenHtmlPage.getId(),
                    idenContainer.getId(),
                    sort,
                    true,
                    -1,
                    APILocator.getUserAPI().getSystemUser(),
                    false);
        } catch (Exception e) {
          Logger.error(PageServices.class, "Unable to retrive contentlets on page", e);
        }
        Logger.debug(
            PageServices.class,
            "HTMLPage= "
                + htmlPage.getInode()
                + " Container="
                + c.getInode()
                + " Language=-1 Contentlets="
                + contentlets.size());
      }
      // this is to filter the contentlets list removing the repited identifiers
      if (contentlets.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentlets) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentlets = contentletsFilter;
      }
      if (contentletsFull.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentletsFull) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentletsFull = contentletsFilter;
      }

      StringBuilder widgetpree = new StringBuilder();
      StringBuilder widgetpreeFull = new StringBuilder();

      StringBuilder contentletList = new StringBuilder();
      int count = 0;
      for (Contentlet contentlet : contentlets) {
        contentletList
            .append(count == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpree.append(field.getValues().trim());
        }
        if (++count >= c.getMaxContentlets()) break;
      }

      StringBuilder contentletListFull = new StringBuilder();
      int countFull = 0;
      for (Contentlet contentlet : contentletsFull) {
        contentletListFull
            .append(countFull == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpreeFull.append(field.getValues().trim());
        }
        if (++countFull >= c.getMaxContentlets()) break;
      }

      sb.append("#if($request.session.getAttribute(\"tm_date\"))");
      sb.append(widgetpreeFull);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletListFull.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(countFull)
          .append(")");
      sb.append("#else ");
      sb.append(widgetpree);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletList.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(count)
          .append(")");
      sb.append("#end ");
      langCounter++;
    }

    if (htmlPage.isHttpsRequired()) {
      sb.append(" #if(!$ADMIN_MODE  && !$request.isSecure())");
      sb.append("    #if($request.getQueryString())");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')?$request.getQueryString()\")");
      sb.append("    #else ");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')\")");
      sb.append("    #end ");
      sb.append("    $response.sendRedirect(\"$REDIRECT_URL\")");
      sb.append(" #end ");
    }

    sb.append("#if($HTMLPAGE_REDIRECT != \"\")");
    sb.append("    $response.sendRedirect(\"$HTMLPAGE_REDIRECT\")");
    sb.append("#end");

    Identifier iden = APILocator.getIdentifierAPI().find(cmsTemplate);

    sb.append("#if(!$doNotParseTemplate)");
    if (cmsTemplate.isDrawed()) { // We have a designed template
      // Setting some theme variables
      sb.append("#set ($dotTheme = $templatetool.theme(\"")
          .append(cmsTemplate.getTheme())
          .append("\",\"")
          .append(host.getIdentifier())
          .append("\"))");
      sb.append("#set ($dotThemeLayout = $templatetool.themeLayout(\"")
          .append(cmsTemplate.getInode())
          .append("\" ))");
      // Merging our template
      sb.append("$velutil.mergeTemplate(\"$dotTheme.templatePath\")");
    } else {
      sb.append("$velutil.mergeTemplate('")
          .append(folderPath)
          .append(iden.getInode())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"))
          .append("')");
    }
    sb.append("#end");

    try {

      if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) {
        String realFolderPath =
            (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator;
        String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
        String filePath =
            realFolderPath
                + identifier.getInode()
                + "."
                + Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION");
        if (velocityRootPath.startsWith("/WEB-INF")) {
          velocityRootPath = com.liferay.util.FileUtil.getRealPath(velocityRootPath);
        }
        velocityRootPath += java.io.File.separator;

        java.io.BufferedOutputStream tmpOut =
            new java.io.BufferedOutputStream(
                new java.io.FileOutputStream(
                    new java.io.File(
                        ConfigUtils.getDynamicVelocityPath() + java.io.File.separator + filePath)));
        // Specify a proper character encoding
        OutputStreamWriter out =
            new OutputStreamWriter(tmpOut, UtilMethods.getCharsetConfiguration());

        out.write(sb.toString());

        out.flush();
        out.close();
        tmpOut.close();
      }
    } catch (Exception e) {
      Logger.error(PageServices.class, e.toString(), e);
    }
    try {
      result = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e1) {
      result = new ByteArrayInputStream(sb.toString().getBytes());
      Logger.error(ContainerServices.class, e1.getMessage(), e1);
    }
    return result;
  }
  /** Returns the list of ids the user is trying to remote publish. */
  private List<String> getIdsToPush(
      List<String> assetIds, String _contentFilterDate, SimpleDateFormat dateFormat)
      throws ParseException, DotDataException {

    List<String> ids = new ArrayList<String>();

    for (String _assetId : assetIds) {

      if (_assetId != null && !_assetId.trim().isEmpty()) {

        if (ids.contains(_assetId)) {
          continue;
        }

        // check for the categories
        if (_assetId.contains("user_") || _assetId.contains("users_")) { // Trying to publish users
          // If we are trying to push users a filter date must be available
          if (_assetId.contains("users_")) {
            Date filteringDate = dateFormat.parse(_contentFilterDate);
            // Get users where createdate >= ?
            List<String> usersIds =
                APILocator.getUserAPI().getUsersIdsByCreationDate(filteringDate, 0, -1);
            if (usersIds != null) {
              for (String id : usersIds) {
                ids.add("user_" + id);
              }
            }
          } else {
            ids.add(_assetId);
          }
        } else if (_assetId.equals("CAT")) {
          ids.add(_assetId);
        } else if (_assetId.contains(".jar")) { // Check for OSGI jar bundles
          ids.add(_assetId);
        } else {
          // if the asset is a folder put the inode instead of the identifier
          try {
            Folder folder = null;
            try {
              folder = APILocator.getFolderAPI().find(_assetId, getUser(), false);
            } catch (DotSecurityException e) {
              Logger.error(
                  getClass(),
                  "User: "******" does not have permission to access folder. Folder identifier: "
                      + _assetId);
            } catch (DotDataException e) {
              Logger.info(getClass(), "FolderAPI.find(): Identifier is null");
            }

            if (folder != null && UtilMethods.isSet(folder.getInode())) {
              ids.add(_assetId);
            } else {
              // if the asset is not a folder and has identifier, put it, if not, put the inode
              Identifier iden = APILocator.getIdentifierAPI().findFromInode(_assetId);
              if (!ids.contains(iden.getId())) { // Multiples languages have the same identifier
                ids.add(iden.getId());
              }
            }

          } catch (DotStateException e) {
            ids.add(_assetId);
          }
        }
      }
    }

    return ids;
  }
Example #6
0
 /**
  * Will pull only working/live from the DB to search/replace on the FS
  *
  * @param textToSearchFor
  * @param textToReplaceWith
  * @param mimeTypesOfFile Will search for things like text/Velocity in the DB. It will put a %
  *     after what you pass so text would pass text% in the like to the DB
  * @return
  */
 private static boolean fileAssetSearchAndReplace(
     String textToSearchFor, String textToReplaceWith, String mimeTypesOfFile) {
   Logger.info(MaintenanceUtil.class, "Starting Search and Replace");
   boolean hasErrors = false;
   DotConnect dc = new DotConnect();
   dc.setSQL(
       "SELECT inode,file_name FROM file_asset fa, fileasset_version_info fvi WHERE mime_type LIKE '"
           + mimeTypesOfFile
           + "%' AND (fa.inode = fvi.working_inode OR fa.inode = fvi.live_inode)");
   List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
   try {
     results = dc.loadResults();
   } catch (DotDataException e) {
     Logger.error(
         MaintenanceUtil.class,
         "Unable to pull files from DB to search for on filesystem : " + e.getMessage(),
         e);
     hasErrors = true;
     Logger.info(MaintenanceUtil.class, "Finished Search and Replace With Errors");
     return true;
   }
   File f = null;
   String s = null;
   for (Map<String, Object> result : results) {
     if (!UtilMethods.isSet(result.get("inode").toString())) {
       hasErrors = true;
       Logger.error(MaintenanceUtil.class, "Empty or null file inode found");
       continue;
     }
     try {
       f =
           new File(
               fileAPI.getRealAssetPath(
                   result.get("inode").toString(),
                   UtilMethods.getFileExtension(result.get("file_name").toString())));
     } catch (Exception e) {
       hasErrors = true;
       Logger.error(
           MaintenanceUtil.class,
           "Unable to load the file with inode "
               + result.get("inode").toString()
               + " : "
               + e.getMessage(),
           e);
       f = null;
       continue;
     }
     if (!f.exists() || f.length() > 1310712000) {
       hasErrors = true;
       Logger.error(
           MaintenanceUtil.class,
           "Unable to load the file with inode " + result.get("inode").toString());
       f = null;
       continue;
     }
     try {
       s = FileUtils.readFileToString(f, "UTF-8");
       s = s.replace(textToSearchFor, textToReplaceWith);
       FileUtils.writeStringToFile(f, s, "UTF-8");
     } catch (Exception e) {
       hasErrors = true;
       Logger.error(MaintenanceUtil.class, "Unable to replace file contents for " + f.getPath());
     }
     s = null;
     f = null;
   }
   Logger.info(MaintenanceUtil.class, "Finished Search and Replace");
   return hasErrors;
 }
Example #7
0
  /**
   * Will replace text in the DB within the following tables. NOTE: This is intended to replace code
   * so we only go after columns/tables that could have HTML or Velocity code in them. Contentlet -
   * text and text_area columns Containers - code,pre_loop and post_loop Template - body Field -
   * field_values for the widget code Link - url
   *
   * @param textToSearchFor - Cannot be NULL or Empty String
   * @param textToReplaceWith - Cannot be NULL
   * @return boolean if the method found errors. It will catch DB errors so that the replace will
   *     run everywhere it can.
   */
  public static boolean DBSearchAndReplace(String textToSearchFor, String textToReplaceWith) {
    boolean hasErros = false;
    if (!UtilMethods.isSet(textToSearchFor)) {
      Logger.info(MaintenanceUtil.class, "Returning because text to search for is null or empty");
    }
    if (textToReplaceWith == null) {
      Logger.info(MaintenanceUtil.class, "Returning because text to replace is null");
    }
    DotConnect dc = new DotConnect();
    Logger.info(
        MaintenanceUtil.class, "ABOUT TO UPDATE COLUMNS text[1-25] ON THE CONTENTLET TABLE");
    int count = 1;
    StringBuilder SQL = new StringBuilder("UPDATE contentlet SET ");
    while (count < 26) {
      if (count > 1) {
        SQL.append(",");
      }
      if (DbConnectionFactory.isMsSql()) {
        SQL.append("text" + count + " = replace(cast(text" + count + " as varchar(max)),?,?)");
      } else {
        SQL.append("text" + count + " = replace(text" + count + ",?,?)");
      }
      count++;
    }

    dc.setSQL(
        SQL.toString()
            + " WHERE contentlet.inode = (SELECT working_inode FROM contentlet_version_info cvi WHERE (cvi.working_inode = contentlet.inode OR cvi.live_inode =contentlet.inode)) ");
    count = 1;
    while (count < 26) {
      dc.addParam(textToSearchFor);
      dc.addParam(textToReplaceWith);
      count++;
    }
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(
          MaintenanceUtil.class, "Problem updating contentlet table : " + e.getMessage(), e);
    }

    Logger.info(
        MaintenanceUtil.class, "ABOUT TO UPDATE COLUMNS text_area[1-25] ON THE CONTENTLET TABLE");
    count = 1;
    SQL = new StringBuilder("UPDATE contentlet SET ");
    while (count < 26) {
      if (count > 1) {
        SQL.append(",");
      }
      if (DbConnectionFactory.isMsSql()) {
        SQL.append(
            "text_area" + count + " = replace(cast(text_area" + count + " as varchar(max)),?,?)");
      } else {
        SQL.append("text_area" + count + " = replace(text_area" + count + ",?,?)");
      }
      count++;
    }

    dc.setSQL(
        SQL.toString()
            + "WHERE contentlet.inode = (SELECT working_inode FROM contentlet_version_info cvi WHERE (cvi.working_inode = contentlet.inode OR cvi.live_inode =contentlet.inode)) ");
    count = 1;
    while (count < 26) {
      dc.addParam(textToSearchFor);
      dc.addParam(textToReplaceWith);
      count++;
    }
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(
          MaintenanceUtil.class, "Problem updating contentlet table : " + e.getMessage(), e);
    }
    Logger.info(
        MaintenanceUtil.class,
        "ABOUT TO UPDATE COLUMNS code, pre_loop, and post_loop ON THE containers TABLE");
    if (DbConnectionFactory.isMsSql()) {
      dc.setSQL(
          "UPDATE containers SET code=replace(cast(code as varchar(max)),?,?),pre_loop=replace(cast(pre_loop as varchar(max)),?,?),post_loop=replace(cast(post_loop as varchar(max)),?,?) WHERE containers.inode = (SELECT working_inode FROM container_version_info cvi WHERE (cvi.working_inode = containers.inode OR cvi.live_inode =containers.inode)) ");
    } else {
      dc.setSQL(
          "UPDATE containers SET code=replace(code,?,?),pre_loop=replace(pre_loop,?,?),post_loop=replace(post_loop,?,?) WHERE containers.inode = (SELECT working_inode FROM container_version_info cvi WHERE (cvi.working_inode = containers.inode OR cvi.live_inode =containers.inode)) ");
    }
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(
          MaintenanceUtil.class, "Problem updating containers table : " + e.getMessage(), e);
    }
    Logger.info(MaintenanceUtil.class, "ABOUT TO UPDATE body COLUMN ON THE template TABLE");
    if (DbConnectionFactory.isMsSql()) {
      dc.setSQL(
          "UPDATE template SET body=replace(cast(body as varchar(max)),?,?) WHERE template.inode = (SELECT working_inode FROM template_version_info tvi WHERE (tvi.working_inode = template.inode OR tvi.live_inode = template.inode)) ");
    } else {
      dc.setSQL(
          "UPDATE template SET body=replace(body,?,?) WHERE template.inode = (SELECT working_inode FROM template_version_info tvi WHERE (tvi.working_inode = template.inode OR tvi.live_inode = template.inode)) ");
    }
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(MaintenanceUtil.class, "Problem updating template table : " + e.getMessage(), e);
    }
    Logger.info(MaintenanceUtil.class, "ABOUT TO UPDATE field_values COLUMN ON THE field TABLE");
    if (DbConnectionFactory.isMsSql()) {
      dc.setSQL("UPDATE field SET field_values=replace(cast(field_values as varchar(max)),?,?)");
    } else {
      dc.setSQL("UPDATE field SET field_values=replace(field_values,?,?)");
    }
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(MaintenanceUtil.class, "Problem updating field table : " + e.getMessage(), e);
    }
    Logger.info(MaintenanceUtil.class, "ABOUT TO UPDATE url COLUMN ON THE links TABLE");
    if (DbConnectionFactory.isMsSql()) {
      dc.setSQL(
          "UPDATE links SET url=replace(cast(url as varchar(max)),?,?) WHERE links.inode = (SELECT working_inode FROM link_version_info lvi WHERE (lvi.working_inode = links.inode OR lvi.live_inode = links.inode)) ");
    } else {
      dc.setSQL(
          "UPDATE links SET url=replace(url,?,?) WHERE links.inode = (SELECT working_inode FROM link_version_info lvi WHERE (lvi.working_inode = links.inode OR lvi.live_inode = links.inode)) ");
    }
    dc.addParam(textToSearchFor);
    dc.addParam(textToReplaceWith);
    try {
      dc.loadResult();
    } catch (DotDataException e) {
      hasErros = true;
      Logger.error(MaintenanceUtil.class, "Problem updating links table : " + e.getMessage(), e);
    }
    Logger.info(MaintenanceUtil.class, "Finished Updating DB");
    return hasErros;
  }