public void init(Object obj) { if (!Config.getBooleanProperty("ENABLE_SCRIPTING", false)) { return; } ViewContext context = (ViewContext) obj; this.request = context.getRequest(); ctx = context.getVelocityContext(); try { host = WebAPILocator.getHostWebAPI().getCurrentHost(request); } catch (PortalException e1) { Logger.error(this, e1.getMessage(), e1); } catch (SystemException e1) { Logger.error(this, e1.getMessage(), e1); } catch (DotDataException e1) { Logger.error(this, e1.getMessage(), e1); } catch (DotSecurityException e1) { Logger.error(this, e1.getMessage(), e1); } userAPI = WebAPILocator.getUserWebAPI(); try { user = userAPI.getLoggedInFrontendUser(request); backuser = userAPI.getLoggedInUser(request); respectFrontendRoles = true; } catch (Exception e) { Logger.error(this, "Error finding the logged in user", e); } }
/** * Downloads a Bundle file for a given bundle id. * * @param request HttpRequest * @param response HttpResponse * @throws IOException If fails sending back to the user response information */ public void downloadBundle(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (!APILocator.getLayoutAPI() .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) { response.sendError(401); return; } } catch (DotDataException e1) { Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1); response.sendError(401); return; } Map<String, String> map = getURIParams(); response.setContentType("application/x-tgz"); String bid = map.get("bid"); PublisherConfig config = new PublisherConfig(); config.setId(bid); File bundleRoot = BundlerUtil.getBundleRoot(config); ArrayList<File> list = new ArrayList<File>(1); list.add(bundleRoot); File bundle = new File(bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz"); if (!bundle.exists()) { response.sendError(500, "No Bundle Found"); return; } response.setHeader("Content-Disposition", "attachment; filename=" + config.getId() + ".tar.gz"); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(bundle)); byte[] buf = new byte[4096]; int len; while ((len = in.read(buf, 0, buf.length)) != -1) { response.getOutputStream().write(buf, 0, len); } } catch (Exception e) { Logger.warn(this.getClass(), "Error Downloading Bundle.", e); } finally { try { in.close(); } catch (Exception ex) { Logger.warn(this.getClass(), "Error Closing Stream.", ex); } } return; }
public NavResult(String parent, String hostId, String folderId) { this.hostId = hostId; this.folderId = folderId; this.parent = parent; hrefVelocity = false; title = href = ""; order = 0; checkPermissions = Config.getBooleanProperty("ENABLE_NAV_PERMISSION_CHECK", false); try { sysuser = APILocator.getUserAPI().getSystemUser(); } catch (DotDataException e) { Logger.warn(this, e.getMessage(), e); } }
/** * Publish a given Bundle file * * @param request HttpRequest * @param response HttpResponse * @throws FileUploadException If fails uploading the file * @throws IOException If fails reading the given File content or sending back to the user a * response */ public void uploadBundle(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException { try { if (!APILocator.getLayoutAPI() .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) { response.sendError(401); return; } } catch (DotDataException e1) { Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1); response.sendError(401); return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = (List<FileItem>) upload.parseRequest(request); InputStream bundle = items.get(0).getInputStream(); String bundleName = items.get(0).getName(); String bundlePath = ConfigUtils.getBundlePath() + File.separator; String bundleFolder = bundleName.substring(0, bundleName.indexOf(".tar.gz")); String endpointId = getUser().getUserId(); response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); PublishAuditStatus status; try { status = PublishAuditAPI.getInstance().updateAuditTable(endpointId, null, bundleFolder); // Write file on FS FileUtil.writeToFile(bundle, bundlePath + bundleName); if (!status.getStatus().equals(Status.PUBLISHING_BUNDLE)) { new Thread(new PublishThread(bundleName, null, endpointId, status)).start(); } out.print( "<html><head><script>isLoaded = true;</script></head><body><textarea>{'status':'success'}</textarea></body></html>"); } catch (DotPublisherException e) { // TODO Auto-generated catch block out.print( "<html><head><script>isLoaded = true;</script></head><body><textarea>{'status':'error'}</textarea></body></html>"); } }
@Override public List<String> findUpdatedFileIdsByURI( Host host, String pattern, boolean include, Date startDate, Date endDate) { Set<String> ret = new HashSet<String>(); String likepattern = RegEX.replaceAll(pattern, "%", "\\*"); String concat; if (DbConnectionFactory.isMySql()) { concat = " concat(ii.parent_path, ii.asset_name) "; } else if (DbConnectionFactory.isMsSql()) { concat = " (ii.parent_path + ii.asset_name) "; } else { concat = " (ii.parent_path || ii.asset_name) "; } StringBuilder bob = new StringBuilder(); DotConnect dc = new DotConnect(); // files modified itself bob = new StringBuilder(); bob.append("SELECT vi.identifier as pident from fileasset_version_info vi ") .append("join identifier ii on (ii.id=vi.identifier) ") .append("where vi.version_ts >= ? ") .append(" and vi.version_ts <= ? ") .append(" and vi.live_inode is not null and vi.deleted=") .append(DbConnectionFactory.getDBFalse()) .append(" and ii.host_inode=? ") .append(" and ") .append(concat) .append(include ? " LIKE ?" : " NOT LIKE ?"); dc.setSQL(bob.toString()); dc.addParam(startDate); dc.addParam(endDate); dc.addParam(host.getIdentifier()); dc.addParam(likepattern); try { for (Map<String, Object> row : dc.loadObjectResults()) ret.add((String) row.get("pident")); } catch (DotDataException e) { Logger.error(HTMLPageFactoryImpl.class, e.getMessage(), e); } return new ArrayList<String>(ret); }
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(); } } }
/** * Will update inode type column in db * * @return */ public static void removeOphanedInodes(String tableName, String inodeType) { String inodesToDeleteSql = "select inode from inode where type = ? and inode not in " + "(select inode from " + tableName + ")"; String deleteSQL = "delete from inode where type = ? and inode not in " + "(select inode from " + tableName + ")"; DotConnect dc = new DotConnect(); dc.setSQL(inodesToDeleteSql); dc.addParam(inodeType); List<HashMap<String, String>> results = null; try { results = dc.getResults(); } catch (DotDataException e) { Logger.error(MaintenanceUtil.class, e.getMessage(), e); } List<String> inodesToDelete = new ArrayList<String>(); for (HashMap<String, String> r : results) { inodesToDelete.add(r.get("inode")); } cleanInodesFromTree(inodesToDelete, 500); cleanPermissionReferences(inodesToDelete, 500); dc.setSQL(deleteSQL); dc.addParam(inodeType); if (tableName.contains("event")) { Logger.info(MaintenanceUtil.class, inodeType); } dc.getResult(); }
/** * Moves a file into the given directory OR host * * @param file File to be moved * @param parent Destination Folder * @param host Destination Host * @return true if move success, false otherwise * @throws DotDataException * @throws DotStateException * @throws DotSecurityException */ private Boolean moveFile(File file, Folder parent, Host host) throws DotStateException, DotDataException, DotSecurityException { HostAPI hostAPI = APILocator.getHostAPI(); // Find file identifier Identifier identifier = com.dotmarketing.business.APILocator.getIdentifierAPI().find(file); // gets working container File workingWebAsset = (File) APILocator.getVersionableAPI() .findWorkingVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); // gets live container File liveWebAsset = (File) APILocator.getVersionableAPI() .findLiveVersion(identifier, APILocator.getUserAPI().getSystemUser(), false); // checks if another identifer with the same name exists in the same Boolean fileNameExists; if (parent != null) { fileNameExists = fileNameExists(parent, file.getFileName()); } else { fileNameExists = fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName()); } if (fileNameExists) { return false; } // assets cache if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) { LiveCache.removeAssetFromCache(liveWebAsset); } WorkingCache.removeAssetFromCache(workingWebAsset); // gets old parent Folder oldParent = APILocator.getFolderAPI() .findParentFolder(workingWebAsset, APILocator.getUserAPI().getSystemUser(), false); /*oldParent.deleteChild(workingWebAsset); if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) { oldParent.deleteChild(liveWebAsset); } //add new Parent parent.addChild(workingWebAsset); if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) { parent.addChild(liveWebAsset); }*/ // gets identifier for this webasset and changes the uri and persists it User systemUser; try { systemUser = APILocator.getUserAPI().getSystemUser(); if (host == null) { host = hostAPI.findParentHost(parent, systemUser, false); } } catch (DotDataException e) { Logger.error(FileFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } catch (DotSecurityException e) { Logger.error(FileFactory.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } identifier.setHostId(host.getIdentifier()); identifier.setURI(parent != null ? workingWebAsset.getURI(parent) : workingWebAsset.getURI()); // HibernateUtil.saveOrUpdate(identifier); APILocator.getIdentifierAPI().save(identifier); if (UtilMethods.isSet(liveWebAsset)) CacheLocator.getIdentifierCache().removeFromCacheByVersionable(liveWebAsset); // IdentifierCache.addAssetToIdentifierCache(liveWebAsset); // Add to Preview and Live Cache if ((liveWebAsset != null) && (InodeUtils.isSet(liveWebAsset.getInode()))) { LiveCache.removeAssetFromCache(liveWebAsset); LiveCache.addToLiveAssetToCache(liveWebAsset); } WorkingCache.removeAssetFromCache(workingWebAsset); WorkingCache.addToWorkingAssetToCache(workingWebAsset); if (file.isShowOnMenu()) { // existing folder with different show on menu ... need to regenerate menu if (parent != null) { RefreshMenus.deleteMenu(oldParent, parent); CacheLocator.getNavToolCache().removeNav(parent.getHostId(), parent.getInode()); } else { RefreshMenus.deleteMenu(oldParent); } CacheLocator.getNavToolCache().removeNav(oldParent.getHostId(), oldParent.getInode()); } return true; }
public Map<String, Object> fetchTemplates( Map<String, String> query, Map<String, String> queryOptions, int start, int count, List<String> sort) throws PortalException, SystemException, DotDataException, DotSecurityException { HttpServletRequest req = WebContextFactory.get().getHttpServletRequest(); User user = userWebAPI.getLoggedInUser(req); boolean respectFrontendRoles = userWebAPI.isLoggedToFrontend(req); if (count <= 0) count = 10; List<Template> fullListTemplates = new ArrayList<Template>(); List<Template> totalTemplates = new ArrayList<Template>(); Host host = hostAPI.find(query.get("hostId"), user, respectFrontendRoles); try { String filter = query.get("fullTitle"); if (UtilMethods.isSet(filter)) { filter = filter.replaceAll("\\*", ""); filter = filter.replaceAll("\\?", ""); } if (UtilMethods.isSet(query.get("hostId"))) { int startF = start; int countF = count; if (start == 0) { Template t = new Template(); t.setOwner(user.getUserId()); t.setModUser(user.getUserId()); t.setInode("0"); t.setTitle("--- " + LanguageUtil.get(user, "All-Hosts") + " ---"); t.setIdentifier("0"); fullListTemplates.add(t); totalTemplates.add(t); countF = count - 1; } else { startF = start - 1; } fullListTemplates.addAll( templateAPI.findTemplatesUserCanUse( user, host.getHostname(), filter, true, startF, countF)); totalTemplates.addAll( templateAPI.findTemplatesUserCanUse(user, host.getHostname(), filter, true, 0, 1000)); } // doesn't currently respect archived if (fullListTemplates.size() == 0) { fullListTemplates.addAll( templateAPI.findTemplatesUserCanUse( user, "", filter, true, start, start > 0 ? count : count + 1)); totalTemplates.addAll(templateAPI.findTemplatesUserCanUse(user, "", filter, true, 0, 1000)); } } catch (DotDataException e) { Logger.error(this, e.getMessage(), e); throw new DotDataException(e.getMessage(), e); } // Collections.sort(fullListTemplates, new TemplateComparator(baseHostId)); Map<String, Object> results = new HashMap<String, Object>(); List<Map<String, Object>> list = new LinkedList<Map<String, Object>>(); boolean shouldIncludeTemplate = true; String toInclude = queryOptions.get("includeTemplate"); for (Template template : fullListTemplates) { Map<String, Object> contMap = buildTemplateMap(template); list.add(contMap); } if (toInclude != null && shouldIncludeTemplate) { Template template = templateAPI.findWorkingTemplate( toInclude, APILocator.getUserAPI().getSystemUser(), false); if (template != null) { list.add(buildTemplateMap(template)); } } // totalTemplates = templateAPI.findTemplatesAssignedTo(host); // if(start >= list.size()) start = list.size() - 1; // if(start < 0) start = 0; // if(start + count >= list.size()) count = list.size() - start; // List<Map<String, Object>> templates = list.subList(start, start + count); results.put("totalResults", totalTemplates.size()); results.put("list", list); return results; }
public void publish(HttpServletRequest request, HttpServletResponse response) throws WorkflowActionFailureException { try { PublisherAPI publisherAPI = PublisherAPI.getInstance(); String _assetId = request.getParameter("assetIdentifier"); String _contentPushPublishDate = request.getParameter("remotePublishDate"); String _contentPushPublishTime = request.getParameter("remotePublishTime"); String _contentPushExpireDate = request.getParameter("remotePublishExpireDate"); String _contentPushExpireTime = request.getParameter("remotePublishExpireTime"); String _iWantTo = request.getParameter("iWantTo"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-H-m"); Date publishDate = dateFormat.parse(_contentPushPublishDate + "-" + _contentPushPublishTime); List<String> ids = new ArrayList<String>(); try { // check for the categories if (_assetId.equals("CAT")) { ids.add(_assetId); } else { // if the asset is a folder put the inode instead of the identifier Folder folder = null; try { folder = APILocator.getFolderAPI().find(_assetId, getUser(), false); } catch (DotDataException e) { } 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); ids.add(iden.getId()); } } } catch (DotStateException e) { ids.add(_assetId); } catch (DotSecurityException e) { e.printStackTrace(); } String bundleId = UUID.randomUUID().toString(); if (_iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH) || _iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE)) { publisherAPI.addContentsToPublish(ids, bundleId, publishDate, getUser()); } if (_iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_EXPIRE) || _iWantTo.equals(RemotePublishAjaxAction.DIALOG_ACTION_PUBLISH_AND_EXPIRE)) { if ((!"".equals(_contentPushExpireDate.trim()) && !"".equals(_contentPushExpireTime.trim()))) { bundleId = UUID.randomUUID().toString(); Date expireDate = dateFormat.parse(_contentPushExpireDate + "-" + _contentPushExpireTime); publisherAPI.addContentsToUnpublish(ids, bundleId, expireDate, getUser()); } } } catch (DotPublisherException e) { Logger.debug(PushPublishActionlet.class, e.getMessage()); throw new WorkflowActionFailureException(e.getMessage()); } catch (ParseException e) { Logger.debug(PushPublishActionlet.class, e.getMessage()); throw new WorkflowActionFailureException(e.getMessage()); } catch (DotDataException e) { Logger.error(PushPublishActionlet.class, e.getMessage(), e); } }
/** * Generates and flush an Unpublish bundle for a given bundle id and operation (publish/unpublish) * * @param request HttpRequest * @param response HttpResponse * @throws IOException If fails sending back to the user response information */ public void downloadUnpushedBundle(HttpServletRequest request, HttpServletResponse response) throws IOException { try { if (!APILocator.getLayoutAPI() .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) { response.sendError(401); return; } } catch (DotDataException e1) { Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1); response.sendError(401); return; } // Read the parameters Map<String, String> map = getURIParams(); String bundleId = map.get("bundleId"); String paramOperation = map.get("operation"); if (bundleId == null || bundleId.isEmpty()) { Logger.error(this.getClass(), "No Bundle Found with id: " + bundleId); response.sendError(500, "No Bundle Found with id: " + bundleId); return; } // What we want to do with this bundle PushPublisherConfig.Operation operation = PushPublisherConfig.Operation.PUBLISH; if (paramOperation != null && paramOperation.equalsIgnoreCase("unpublish")) { operation = PushPublisherConfig.Operation.UNPUBLISH; } File bundle; String generatedBundleId; try { // Generate the bundle file for this given operation Map<String, Object> bundleData = generateBundle(bundleId, operation); bundle = (File) bundleData.get("file"); generatedBundleId = (String) bundleData.get("id"); } catch (Exception e) { Logger.error(this.getClass(), "Error trying to generate bundle with id: " + bundleId, e); response.sendError(500, "Error trying to generate bundle with id: " + bundleId); return; } response.setContentType("application/x-tgz"); response.setHeader("Content-Disposition", "attachment; filename=" + bundle.getName()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(bundle)); byte[] buf = new byte[4096]; int len; while ((len = in.read(buf, 0, buf.length)) != -1) { response.getOutputStream().write(buf, 0, len); } } catch (Exception e) { Logger.error(this.getClass(), "Error reading bundle stream for bundle id: " + bundleId, e); response.sendError(500, "Error reading bundle stream for bundle id: " + bundleId); } finally { try { in.close(); } catch (Exception ex) { Logger.error(this.getClass(), "Error closing Stream for bundle: " + bundleId, ex); } // Clean the just created bundle because on each download we will generate a new bundle file // with a new id in order to avoid conflicts with ids File bundleRoot = BundlerUtil.getBundleRoot(generatedBundleId); File compressedBundle = new File(ConfigUtils.getBundlePath() + File.separator + generatedBundleId + ".tar.gz"); if (compressedBundle.exists()) { compressedBundle.delete(); if (bundleRoot.exists()) { com.liferay.util.FileUtil.deltree(bundleRoot); } } } }
public void executeAction( WorkflowProcessor processor, Map<String, WorkflowActionClassParameter> params) throws WorkflowActionFailureException { String tweatThis = null; try { tweatThis = processor.getWorkflowMessage(); if (!UtilMethods.isSet(tweatThis) && UtilMethods.isSet(params.get("fieldVar").getValue())) { tweatThis = processor.getContentlet().getStringProperty(params.get("fieldVar").getValue()); } if (UtilMethods.isSet(tweatThis)) { if (tweatThis.length() > 140) { String error = LanguageUtil.get( PublicCompanyFactory.getDefaultCompanyId(), PublicCompanyFactory.getDefaultCompany().getLocale(), "Tweet-too-long"); if (error.equals("Tweet-too-long")) { error = error.replaceAll("-", " "); } throw new DotValidationException(error); } String consumerKey = null, consumerSecret = null, password = null, userName = null, accessToken = null, accessTokenSecret = null; consumerKey = params.get("consumerKey").getValue(); consumerSecret = params.get("consumerSecret").getValue(); accessToken = params.get("accessToken").getValue(); accessTokenSecret = params.get("accessTokenSecret").getValue(); String path = APILocator.getContentletAPI() .getUrlMapForContentlet( processor.getContentlet(), APILocator.getUserAPI().getSystemUser(), false); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Status stat = twitter.updateStatus(tweatThis); WorkflowComment comment = new WorkflowComment(); comment.setPostedBy(processor.getUser().getUserId()); comment.setComment("Tweeted: " + tweatThis + " twitterId:" + stat.getId()); comment.setWorkflowtaskId(processor.getTask().getId()); try { APILocator.getWorkflowAPI().saveComment(comment); } catch (DotDataException e) { Logger.error(CommentOnWorkflowActionlet.class, e.getMessage(), e); } } } catch (Exception e) { Logger.error(TwitterActionlet.class, e.getMessage()); throw new WorkflowActionFailureException(e.getMessage()); } }
/** * 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; }
/** * 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; }