protected String calculateIndexRemoteUrl(RemoteRepository remoteRepository) { if (StringUtils.startsWith(remoteRepository.getRemoteIndexUrl(), "http")) { String baseUrl = remoteRepository.getRemoteIndexUrl(); return baseUrl.endsWith("/") ? StringUtils.substringBeforeLast(baseUrl, "/") : baseUrl; } String baseUrl = StringUtils.endsWith(remoteRepository.getUrl(), "/") ? StringUtils.substringBeforeLast(remoteRepository.getUrl(), "/") : remoteRepository.getUrl(); baseUrl = StringUtils.isEmpty(remoteRepository.getRemoteIndexUrl()) ? baseUrl + "/.index" : baseUrl + "/" + remoteRepository.getRemoteIndexUrl(); return baseUrl; }
private File prepareTargetFileName( final File file, final SignaturePackaging signaturePackaging, final String signatureLevel) { final File parentDir = file.getParentFile(); final String originalName = StringUtils.substringBeforeLast(file.getName(), "."); final String originalExtension = "." + StringUtils.substringAfterLast(file.getName(), "."); final String level = signatureLevel.toUpperCase(); if (((SignaturePackaging.ENVELOPING == signaturePackaging) || (SignaturePackaging.DETACHED == signaturePackaging)) && level.startsWith("XADES")) { final String form = "xades"; final String levelOnly = DSSUtils.replaceStrStr(level, "XADES-", "").toLowerCase(); final String packaging = signaturePackaging.name().toLowerCase(); return new File( parentDir, originalName + "-" + form + "-" + packaging + "-" + levelOnly + ".xml"); } if (level.startsWith("CADES") && !originalExtension.toLowerCase().equals(".p7m")) { return new File(parentDir, originalName + originalExtension + ".p7m"); } if (level.startsWith("ASIC_S")) { return new File(parentDir, originalName + originalExtension + ".asics"); } if (level.startsWith("ASIC_E")) { return new File(parentDir, originalName + originalExtension + ".asice"); } return new File(parentDir, originalName + "-signed" + originalExtension); }
/** * Creates the specified permission if it does not exist yet. Also creates all intermediate * permission nodes if not present yet. The {@link Session#save()} is not called by this method; * it is the responsibility of the caller. * * @param path the path of the permission to get/create * @param session current JCR session * @return the permission node * @throws RepositoryException in case of an error */ public static JCRNodeWrapper getOrCreatePermission(String path, JCRSessionWrapper session) throws RepositoryException { if (path == null || !path.startsWith("/permissions/")) { throw new IllegalArgumentException("Illegal value for the permission path: " + path); } String basePath = StringUtils.substringBeforeLast(path, "/"); String name = StringUtils.substringAfterLast(path, "/"); JCRNodeWrapper permission = null; JCRNodeWrapper base = null; try { base = session.getNode(basePath); } catch (PathNotFoundException e) { base = getOrCreatePermission(basePath, session); } if (!base.hasNode(name)) { session.checkout(base); permission = base.addNode(name, "jnt:permission"); logger.info("Added permission node {}", permission.getPath()); } else { permission = base.getNode(name); } return permission; }
public String createDefaultTitle( final List<GitCommit> commits, final String sourceBranchName, final String targetBranchName) { if (commits == null || commits.isEmpty()) { return StringUtils.EMPTY; } if (commits.size() == 1) { // if we only have one commit, use it's title as the title of pull request final GitCommit commit = commits.get(0); final String commitMessage = commit.getSubject(); // WebAcess use 80 (because it's common code for many things, and 80 is such a magic number), // but IMHO 80 is too short for title, set it to 120 final int titleLength = 120; if (commitMessage.length() < titleLength) { return commitMessage; } else { // break at last whitespace right before length 120 final String shortCommitMessage = commitMessage.substring(0, titleLength); return StringUtils.substringBeforeLast(shortCommitMessage, "\\s+"); } } // Standard title "merging source branch to target branch" return TfPluginBundle.message( TfPluginBundle.KEY_CREATE_PR_DEFAULT_TITLE, sourceBranchName, targetBranchName); }
public String renameNode(String newLabel) throws AccessDeniedException, ExchangeException, PathNotFoundException, RepositoryException { String returnValue; String parentPath = StringUtils.substringBeforeLast(this.getPath(), "/"); // $NON-NLS-1$ newLabel = Path.getValidatedLabel(newLabel); // don't rename if it uses the same name as the current if (this.getPath().endsWith("/" + newLabel)) { return newLabel; } String dest = parentPath + "/" + newLabel; // $NON-NLS-1$ if (getHierarchyManager().isExist(dest)) { newLabel = Path.getUniqueLabel(getHierarchyManager(), parentPath, newLabel); dest = parentPath + "/" + newLabel; // $NON-NLS-1$ } this.deActivateNode(this.getPath()); if (log.isInfoEnabled()) { log.info("Moving node from " + this.getPath() + " to " + dest); // $NON-NLS-1$ //$NON-NLS-2$ } if (getHierarchyManager().isNodeData(this.getPath())) { Content parentPage = getHierarchyManager().getContent(parentPath); NodeData newNodeData = parentPage.createNodeData(newLabel); NodeData existingNodeData = getHierarchyManager().getNodeData(this.getPath()); newNodeData.setValue(existingNodeData.getString()); existingNodeData.delete(); dest = parentPath; } else { // we can't rename a node. we must move // we must place the node at the same position Content current = getHierarchyManager().getContent(this.getPath()); Content parent = current.getParent(); String placedBefore = null; for (Iterator iter = parent.getChildren(current.getNodeTypeName()).iterator(); iter.hasNext(); ) { Content child = (Content) iter.next(); if (child.getHandle().equals(this.getPath())) { if (iter.hasNext()) { child = (Content) iter.next(); placedBefore = child.getName(); } } } getHierarchyManager().moveTo(this.getPath(), dest); // now set at the same place as before if (placedBefore != null) { parent.orderBefore(newLabel, placedBefore); } } Content newPage = getHierarchyManager().getContent(dest); returnValue = newLabel; newPage.updateMetaData(); newPage.save(); return returnValue; }
/** * Saves a value edited directly inside the tree. This can also be a lable * * @return name of the view */ public String saveValue() { String saveName = this.getRequest().getParameter("saveName"); // $NON-NLS-1$ Tree tree = getTree(); // value to save is a node data's value (config admin) boolean isNodeDataValue = "true" .equals(this.getRequest().getParameter("isNodeDataValue")); // $NON-NLS-1$ //$NON-NLS-2$ // value to save is a node data's type (config admin) boolean isNodeDataType = "true" .equals(this.getRequest().getParameter("isNodeDataType")); // $NON-NLS-1$ //$NON-NLS-2$ String value = StringUtils.defaultString(this.getRequest().getParameter("saveValue")); // $NON-NLS-1$ displayValue = StringUtils.EMPTY; // value to save is a content's meta information boolean isMeta = "true".equals(this.getRequest().getParameter("isMeta")); // $NON-NLS-1$ //$NON-NLS-2$ // value to save is a label (name of page, content node or node data) boolean isLabel = "true".equals(this.getRequest().getParameter("isLabel")); // $NON-NLS-1$ //$NON-NLS-2$ if (isNodeDataValue || isNodeDataType) { tree.setPath(StringUtils.substringBeforeLast(path, "/")); // $NON-NLS-1$ saveName = StringUtils.substringAfterLast(path, "/"); // $NON-NLS-1$ } else { // "/modules/templating/Templates/x" tree.setPath(path); } if (isLabel) { displayValue = rename(value); } else if (isNodeDataType) { int type = Integer.valueOf(value).intValue(); synchronized (ExclusiveWrite.getInstance()) { displayValue = tree.saveNodeDataType(saveName, type); } } else { synchronized (ExclusiveWrite.getInstance()) { displayValue = tree.saveNodeData(saveName, value, isMeta); } } // if there was a displayValue passed show it instead of the written value displayValue = StringUtils.defaultString( this.getRequest().getParameter("displayValue"), value); // $NON-NLS-1$ // @todo should be handled in a better way but, at the moment, this is better than nothing if (path.startsWith("/subscribers/")) { // $NON-NLS-1$ Subscriber.reload(); } else if (path.startsWith("/server/MIMEMapping")) { // $NON-NLS-1$ MIMEMapping.reload(); } return VIEW_VALUE; }
/** Clears out associated .done files for the processed data files. */ protected void removeDoneFiles(String dataFileName) { File doneFile = new File( StringUtils.substringBeforeLast(dataFileName, ".") + TemConstants.DONE_FILE_SUFFIX); if (doneFile.exists()) { doneFile.delete(); } }
@SuppressWarnings({"unchecked", "rawtypes"}) private static void processConfigFile(File configFile) throws IOException, FileNotFoundException { if (configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) { logger.debug("Ignoring file '{}'", configFile.getName()); return; } logger.debug("Processing config file '{}'", configFile.getName()); ConfigurationAdmin configurationAdmin = (ConfigurationAdmin) ConfigActivator.configurationAdminTracker.getService(); if (configurationAdmin != null) { // we need to remember which configuration needs to be updated // because values have changed. Map<Configuration, Dictionary> configsToUpdate = new HashMap<Configuration, Dictionary>(); // also cache the already retrieved configurations for each pid Map<Configuration, Dictionary> configMap = new HashMap<Configuration, Dictionary>(); String pid; String filenameWithoutExt = StringUtils.substringBeforeLast(configFile.getName(), "."); if (filenameWithoutExt.contains(".")) { // it is a fully qualified namespace pid = filenameWithoutExt; } else { pid = getServicePidNamespace() + "." + filenameWithoutExt; } List<String> lines = IOUtils.readLines(new FileInputStream(configFile)); if (lines.size() > 0 && lines.get(0).startsWith(PID_MARKER)) { pid = lines.get(0).substring(PID_MARKER.length()).trim(); } for (String line : lines) { String[] contents = parseLine(configFile.getPath(), line); // no valid configuration line, so continue if (contents == null) continue; if (contents[0] != null) { pid = contents[0]; } String property = contents[1]; String value = contents[2]; Configuration configuration = configurationAdmin.getConfiguration(pid, null); if (configuration != null) { Dictionary configProperties = configMap.get(configuration); if (configProperties == null) { configProperties = new Properties(); configMap.put(configuration, configProperties); } if (!value.equals(configProperties.get(property))) { configProperties.put(property, value); configsToUpdate.put(configuration, configProperties); } } } for (Entry<Configuration, Dictionary> entry : configsToUpdate.entrySet()) { entry.getKey().update(entry.getValue()); } } }
/** Create a new link annotation. Already adds the chain to the CAS. */ private AnnotationFS newLink( JCas aJCas, int aBegin, int aEnd, AnnotationFeature aFeature, String aLabelValue) { String baseName = StringUtils.substringBeforeLast(getAnnotationTypeName(), CHAIN) + LINK; Type linkType = CasUtil.getType(aJCas.getCas(), baseName); AnnotationFS newLink = aJCas.getCas().createAnnotation(linkType, aBegin, aEnd); BratAjaxCasUtil.setFeature(newLink, aFeature, aLabelValue); aJCas.getCas().addFsToIndexes(newLink); return newLink; }
/* (non-Javadoc) * @see com.hundsun.ares.studio.core.IARESModule#getParentModule() */ public IARESModule getParentModule() { // 默认模块或第一级模块视为没有父模块 if (isDefaultModule() || getElementName().indexOf('.') == -1) return null; IARESModuleRoot root = getRoot(); String name = getElementName(); String parentModuleName = StringUtils.substringBeforeLast(name, "."); return root.getModule(parentModuleName); }
/** @return the generated web dll names otherwise. */ public Set<String> getWebAssemblyNames() { Set<File> assemblies = getGeneratedAssemblies(null, null); Set<String> assemblyNames = new HashSet<String>(); for (File assembly : assemblies) { assemblyNames.add(StringUtils.substringBeforeLast(assembly.getName(), ".dll")); } return assemblyNames; }
@Before public void setUp() throws Exception { random = new Random(); mediaHeader = batchMediaConverter.getHeader(); productId = Long.valueOf(Math.abs((long) random.nextInt())); sequenceId = Long.valueOf(Math.abs((long) random.nextInt())); importCsv("/octcommoncore/test/testBatch.impex", "utf-8"); // don't import binary data -> temporarily remove MediaTranslator ((DefaultImpexConverter) batchMediaConverter) .setHeader(StringUtils.substringBeforeLast(mediaHeader, ";")); }
protected SortedMap<String, DataSource> lookupDataSourcesByRouter( final String statementName, final Object parameterObject) { SortedMap<String, DataSource> resultMap = new TreeMap<String, DataSource>(); String namespace = StringUtils.substringBeforeLast(statementName, "."); String dsName = shardStrategy.getShardIdentitiesByNamespace(namespace, parameterObject); if (dsName == null) { throw new IllegalStateException("无法找到相应的分库资源,请检查参数列表中是否有传分库字段值, 参数:" + parameterObject); } resultMap.put(dsName, shardDataSourceService.getDataSources().get(dsName)); return resultMap; }
/** * Check whether the given property represents a property within an EBO starting with the sampleBo * object given. This is used to determine if a criteria needs to be applied to the EBO first, * before sending to the normal lookup DAO. * * @param sampleBo business object of the property to be tested * @param propertyName property name to be tested * @return true if the property is within an externalizable business object. */ public static boolean isExternalBusinessObjectProperty(Object sampleBo, String propertyName) { if (propertyName.indexOf(".") > 0 && !StringUtils.contains(propertyName, "add.")) { Class<?> propertyClass = ObjectPropertyUtils.getPropertyType( sampleBo, StringUtils.substringBeforeLast(propertyName, ".")); if (propertyClass != null) { return ExternalizableBusinessObjectUtils.isExternalizableBusinessObjectInterface( propertyClass); } } return false; }
/** * 获取调用者信息 * * @return 找到的堆栈信息,格式为:className.methodName:lineNumber,如果找不到则返回NO_STACK_TRACE:-1 */ protected String __doMakeCallerInfo() { StackTraceElement[] _stacks = new Throwable().getStackTrace(); // 追溯到对应的调用行,如果对应行不存在,则不给出无法确定行号的输出 if (_stacks.length > 3) { StackTraceElement _element = _stacks[3]; return StringUtils.substringBeforeLast(_element.getClassName(), ".") .concat(".") .concat(_element.getMethodName()) .concat(":") .concat(_element.getLineNumber() + StringUtils.EMPTY); } return "NO_STACK_TRACE:-1"; }
/** * Get the complete list of all properties referenced in the fieldValues that are * ExternalizableBusinessObjects. * * <p>This is a list of the EBO object references themselves, not of the properties within them. * * @param boClass business object class of the lookup * @param fieldValues map of lookup criteria from which to return the externalizable business * objects * @return map of lookup criteria that are externalizable business objects * @throws IllegalAccessException * @throws InstantiationException */ public static List<String> getExternalizableBusinessObjectProperties( Class<?> boClass, Map<String, String> fieldValues) throws IllegalAccessException, InstantiationException { Set<String> eboPropertyNames = new HashSet<String>(); Object sampleBo = boClass.newInstance(); for (String key : fieldValues.keySet()) { if (isExternalBusinessObjectProperty(sampleBo, key)) { eboPropertyNames.add(StringUtils.substringBeforeLast(key, ".")); } } return new ArrayList<String>(eboPropertyNames); }
/** * @param path * @param recursive */ public void activateNode(String path, boolean recursive) throws ExchangeException, RepositoryException { String parentPath = StringUtils.substringBeforeLast(path, "/"); if (StringUtils.isEmpty(parentPath)) { parentPath = "/"; } Syndicator syndicator = getActivationSyndicator(path); if (recursive) { activateNodeRecursive(syndicator, parentPath, path); } else { syndicator.activate(parentPath, path); } }
private Class<?> getPropertyTypeForPath(String propertyName) { Class<?> type = bean.getPropertyType(propertyName); if (type == null) { // type not available via BeanWrapper - this happens with e.g. empty list indexes - so // find type by examining GrailsDomainClass Object target = bean.getWrappedInstance(); String path = propertyName.replaceAll("\\[.+?\\]", ""); if (path.indexOf(PATH_SEPARATOR) > -1) { // transform x.y.z into value of x.y and path z target = bean.getPropertyValue(StringUtils.substringBeforeLast(propertyName, ".")); path = StringUtils.substringAfterLast(path, "."); } type = getReferencedTypeForCollection(path, target); } return type; }
public static void main(String[] args) { // String requrl = "http://127.0.0.1:8080/ms/sysMenu/menu.shtml"; // requrl = "https://127.0.0.1:8080/ms/sysMenu/menu.shtml?A=1&B=2#111"; // String uri = getReqUri(requrl); // System.out.println(uri); // System.out.println(StringUtils.remove(uri, "/ms/")); // System.err.println(getReqUri(requrl));\ String menu = "/sysMneu/dataList.do"; String url = "save.do| action.do |/user/manger/abcd.do"; String[] actions = StringUtils.split(url, "|"); String menuUri = StringUtils.substringBeforeLast(menu, "/"); for (String action : actions) { action = StringUtils.trim(action); if (StringUtils.startsWith(action, "/")) System.out.println(action); else System.out.println(menuUri + "/" + action); } }
private static void deleteBucket(final String bucketName, final AmazonS3 s3) { final Preferences prefs = Preferences.userRoot(); final String createdBuckets = prefs.get(BUCKETS_KEY, ""); try { s3.deleteBucket(bucketName); if (createdBuckets.contains("," + bucketName + ",")) { prefs.put(BUCKETS_KEY, createdBuckets.replace("," + bucketName + ",", ",")); } else if (createdBuckets.endsWith("," + bucketName)) { final String strippedBuckets = StringUtils.substringBeforeLast(createdBuckets, "," + bucketName); prefs.put(BUCKETS_KEY, strippedBuckets); } } catch (final IOException e) { System.out.println("Could not delete bucket."); e.printStackTrace(); } }
/** * Creates a module from the group of strings which represents each field of the module. * * @param matcher Matcher which contains the fields. It cannot be null. * @return If the module already exists, return the existing module, otherwise returns the created * module from the matcher's fields. */ private TestSuite getModule(final Matcher matcher) { Validate.notNull(matcher, "The matcher cannot be null."); String moduleName = "default"; if (matcher.group(MODULE_NAME) != null) { moduleName = matcher.group(MODULE_NAME).trim(); } if (moduleName.endsWith(":")) { moduleName = StringUtils.substringBeforeLast(moduleName, ":"); } if (!modules.containsKey(moduleName)) { modules.put(moduleName, new TestSuite(moduleName)); } return modules.get(moduleName); }
@Override public EasyuiDataGridJson datagrid(EasyuiDataGrid dg, String learningcenterId) { EasyuiDataGridJson listjson = new EasyuiDataGridJson(); Example example = new Example(YztLearningcenterComment.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("yztLearningcenterId", learningcenterId); // criteria.andEqualTo("parentid","0"); String filterRules = dg.getFilterRules(); if (filterRules != null && !"[]".equals(filterRules)) { List<FieldFilter> filtersr = JSON.parseArray(filterRules, FieldFilter.class); for (FieldFilter ft : filtersr) { // postparam.append(" and "+ft.getField()+" like '%"+ft.getValue().trim().replace(" ", // "%")+"%' "); criteria.andLike(ft.getField(), "%" + ft.getValue().trim().replaceAll(" ", "%") + "%"); } } // 加入排序 if (dg.getSort() != null && dg.getOrder() != null) { String orderby = ""; String[] order = dg.getSort().split(","); String[] sort = dg.getOrder().split(","); for (int i = 0; i < order.length; i++) { orderby += order[i] + " " + sort[i] + ","; } orderby = StringUtils.substringBeforeLast(orderby, ","); example.setOrderByClause(orderby); } else { example.setOrderByClause(" createtime desc "); } listjson.setTotal(selectCountByExample(example)); // 分页查询 PageHelper.startPage(dg.getPage(), dg.getRows()); listjson.setRows(selectByExample(example)); return listjson; }
/** * Finds directories and files within a given directory and its subdirectories. * * @param classLoader * @param rootPath the root directory, for example org/sonar/sqale, or a file in this root * directory, for example org/sonar/sqale/index.txt * @param * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", * "org/sonar/sqale/foo/bar.txt}. Never null. */ public static Collection<String> listResources( ClassLoader classLoader, String rootPath, Predicate<String> predicate) { String jarPath = null; JarFile jar = null; try { Collection<String> paths = Lists.newArrayList(); rootPath = StringUtils.removeStart(rootPath, "/"); URL root = classLoader.getResource(rootPath); if (root != null) { checkJarFile(root); // Path of the root directory // Examples : // org/sonar/sqale/index.txt -> rootDirectory is org/sonar/sqale // org/sonar/sqale/ -> rootDirectory is org/sonar/sqale // org/sonar/sqale -> rootDirectory is org/sonar/sqale String rootDirectory = rootPath; if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) { rootDirectory = StringUtils.substringBeforeLast(rootPath, "/"); } jarPath = root.getPath().substring(5, root.getPath().indexOf("!")); // strip out only the JAR file jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8)); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(rootDirectory) && predicate.apply(name)) { paths.add(name); } } } return paths; } catch (Exception e) { throw Throwables.propagate(e); } finally { closeJar(jar, jarPath); } }
public Content copyMoveNode(String source, String destination, boolean move) throws ExchangeException, RepositoryException { // todo: ??? generic -> RequestInterceptor.java if (getHierarchyManager().isExist(destination)) { String parentPath = StringUtils.substringBeforeLast(destination, "/"); // $NON-NLS-1$ String label = StringUtils.substringAfterLast(destination, "/"); // $NON-NLS-1$ label = Path.getUniqueLabel(getHierarchyManager(), parentPath, label); destination = parentPath + "/" + label; // $NON-NLS-1$ } if (move) { if (destination.indexOf(source + "/") == 0) { // $NON-NLS-1$ // todo: disable this possibility in javascript // move source into destinatin not possible return null; } this.deActivateNode(source); try { getHierarchyManager().moveTo(source, destination); } catch (Exception e) { // try to move below node data return null; } } else { // copy getHierarchyManager().copyTo(source, destination); } // SessionAccessControl.invalidateUser(this.getRequest()); Content newContent = getHierarchyManager().getContent(destination); try { newContent.updateMetaData(); newContent.getMetaData().setUnActivated(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Exception caught: " + e.getMessage(), e); // $NON-NLS-1$ } newContent.save(); return newContent; }
@RequestMapping(method = RequestMethod.POST) public String extend( HttpServletRequest request, HttpServletResponse response, @ModelAttribute("extensionForm") @Valid ExtensionForm extensionForm, BindingResult result) { if (result.hasErrors()) { return EXTENSION_TILE; } DSSDocument toExtendDocument = WebAppUtils.toDSSDocument(extensionForm.getSignedFile()); DSSDocument extendedDocument = signingService.extend( extensionForm.getSignatureForm(), extensionForm.getSignaturePackaging(), extensionForm.getSignatureLevel(), toExtendDocument, WebAppUtils.toDSSDocument(extensionForm.getOriginalFile())); String originalName = toExtendDocument.getName(); String extendedFileName = StringUtils.substringBeforeLast(originalName, ".") + "-extended." + StringUtils.substringAfterLast(originalName, "."); response.setContentType(extendedDocument.getMimeType().getMimeTypeString()); response.setHeader("Content-Disposition", "attachment; filename=" + extendedFileName); try { IOUtils.copy( new ByteArrayInputStream(extendedDocument.getBytes()), response.getOutputStream()); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }
@Override protected List<Long> getScope(Context ctx, String senderId, Object... args) { List<Long> userIds = new ArrayList<Long>(); RecordSet liked_Users = new RecordSet(); if (getSettingKey(ctx).equals(Constants.NTF_MY_APP_LIKE)) { /* RecordSet es_shared_Users = p.findWhoSharedApp((String)args[0], 200); for (Record ue : es_shared_Users) { if (!userIds.contains(Long.parseLong(ue.getString("source"))) && !ue.getString("source").equals("0") && !ue.getString("source").equals("")) { userIds.add(Long.parseLong(ue.getString("source"))); } liked_Users = p.likedUsers(Constants.APK_OBJECT, (String)args[0], 0, 200); } */ // =========================new send to ,from conversation========================= String packageName = (String) args[0].toString().trim(); String[] a = StringUtils.split(packageName, "-"); if (a.length > 1) packageName = a[0]; List<String> reasons = new ArrayList<String>(); reasons.add(String.valueOf(Constants.C_APK_SHARE)); ConversationLogic conversation = GlobalLogics.getConversation(); RecordSet conversation_users = conversation.getConversation(ctx, Constants.APK_OBJECT, packageName, reasons, 0, 0, 100); for (Record r : conversation_users) { if (!userIds.contains(Long.parseLong(r.getString("from_")))) userIds.add(Long.parseLong(r.getString("from_"))); } List<String> reasons1 = new ArrayList<String>(); reasons1.add(String.valueOf(Constants.C_APK_LIKE)); RecordSet conversation_users1 = conversation.getConversation(ctx, Constants.APK_OBJECT, packageName, reasons1, 0, 0, 100); AccountLogic account = GlobalLogics.getAccount(); liked_Users.addAll( account.getUsers( ctx, (String) args[1], conversation_users1.joinColumnValues("from_", ","), "user_id,display_name", false)); // =========================new send to ,from conversation end ==================== } if (userIds.contains(Long.parseLong((String) args[1]))) userIds.remove(Long.parseLong((String) args[1])); // exclude sender if (StringUtils.isNotBlank(senderId)) { userIds.remove(Long.parseLong(senderId)); } try { IgnoreLogic ignore = GlobalLogics.getIgnore(); userIds = ignore.formatIgnoreUserListP(ctx, userIds, "", ""); List<Long> lu = new ArrayList<Long>(); for (Record r : liked_Users) { lu.add(Long.parseLong(r.getString("user_id"))); } lu = ignore.formatIgnoreUserListP(ctx, lu, "", ""); for (int i = liked_Users.size() - 1; i >= 0; i--) { if (!lu.contains(Long.parseLong(liked_Users.get(i).getString("user_id")))) liked_Users.remove(i); } } catch (Exception e) { } List<String> l = new ArrayList<String>(); int i = 0; for (Record user : liked_Users) { if (i > 3) break; String userId = user.getString("user_id"); String displayName = user.getString("display_name"); if (StringUtils.contains(displayNames, displayName)) { continue; } else { displayNames += displayName + ", "; l.add( "<a href=\"borqs://profile/details?uid=" + userId + "&tab=2\">" + displayName + "</a>"); i++; } } nameLinks = StringUtils.join(l, ", "); if (StringUtils.isNotBlank(displayNames)) { displayNames = StringUtils.substringBeforeLast(displayNames, ","); } return userIds; }
public JCRItemWrapper getItem(String path, final boolean checkVersion) throws PathNotFoundException, RepositoryException { if (sessionCacheByPath.containsKey(path)) { return sessionCacheByPath.get(path); } if (path.contains(DEREF_SEPARATOR)) { JCRNodeWrapper parent = (JCRNodeWrapper) getItem(StringUtils.substringBeforeLast(path, DEREF_SEPARATOR), checkVersion); return dereference(parent, StringUtils.substringAfterLast(path, DEREF_SEPARATOR)); } Map<String, JCRStoreProvider> dynamicMountPoints = sessionFactory.getDynamicMountPoints(); for (Map.Entry<String, JCRStoreProvider> mp : dynamicMountPoints.entrySet()) { if (path.startsWith(mp.getKey() + "/")) { String localPath = path.substring(mp.getKey().length()); JCRStoreProvider provider = mp.getValue(); Item item = getProviderSession(provider).getItem(provider.getRelativeRoot() + localPath); if (item.isNode()) { return provider.getNodeWrapper((Node) item, localPath, null, this); } else { return provider.getPropertyWrapper((Property) item, this); } } } Map<String, JCRStoreProvider> mountPoints = sessionFactory.getMountPoints(); for (Map.Entry<String, JCRStoreProvider> mp : mountPoints.entrySet()) { String key = mp.getKey(); if (key.equals("/") || path.equals(key) || path.startsWith(key + "/")) { String localPath = path; if (!key.equals("/")) { localPath = localPath.substring(key.length()); } JCRStoreProvider provider = mp.getValue(); if (localPath.equals("")) { localPath = "/"; } // Item item = getProviderSession(provider).getItem(localPath); Session session = getProviderSession(provider); if (session instanceof JahiaSessionImpl && getUser() != null && sessionFactory.getCurrentAliasedUser() != null && sessionFactory.getCurrentAliasedUser().equals(getUser())) { ((JahiaSessionImpl) session).toggleThisSessionAsAliased(); } Item item = session.getItem(provider.getRelativeRoot() + localPath); if (item.isNode()) { final Node node = (Node) item; JCRNodeWrapper wrapper = provider.getNodeWrapper(node, localPath, null, this); if (getUser() != null && sessionFactory.getCurrentAliasedUser() != null && !sessionFactory.getCurrentAliasedUser().equals(getUser())) { final JCRNodeWrapper finalWrapper = wrapper; JCRTemplate.getInstance() .doExecuteWithUserSession( sessionFactory.getCurrentAliasedUser().getUsername(), getWorkspace().getName(), getLocale(), new JCRCallback<Object>() { public Object doInJCR(JCRSessionWrapper session) throws RepositoryException { return session.getNodeByUUID(finalWrapper.getIdentifier(), checkVersion); } }); } if (checkVersion && (versionDate != null || versionLabel != null) && node.isNodeType("mix:versionable")) { wrapper = getFrozenVersionAsRegular(node, provider); } sessionCacheByPath.put(path, wrapper); sessionCacheByIdentifier.put(wrapper.getIdentifier(), wrapper); return wrapper; } else { return provider.getPropertyWrapper((Property) item, this); } } } throw new PathNotFoundException(path); }
// 获取业务分析所需的字段信息将它们写入到redis中 public void execute(Tuple tuple) { // 发射到此bolt的字段均有值,直接获取即可 firewalls_access_bean = new Xinguan_FireWalls_AccessBean(); // 获取字段信息 firewalls_access_bean.setSys_time( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.SYSTIME)); firewalls_access_bean.setLog_time( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.LOGTIME)); firewalls_access_bean.setSrc_ip(tuple.getStringByField(Xinguan_FireWalls_AccessFileds.SRCIP)); firewalls_access_bean.setSrc_port( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.SRCPORT)); firewalls_access_bean.setUser_portal( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.PORTAL)); firewalls_access_bean.setDst_ip(tuple.getStringByField(Xinguan_FireWalls_AccessFileds.DSTIP)); firewalls_access_bean.setDst_port( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.DSTPORT)); firewalls_access_bean.setProto( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.PROTOCOLS)); firewalls_access_bean.setAppname( tuple.getStringByField(Xinguan_FireWalls_AccessFileds.APPLICATIONS)); // 每条记录2016-01-30包含的内容字段如下: // 系统获取日志记录的时间,日志记录的实际时间,ipv4源ip,ipv4源端口,源ip对应的portal账号, // ipv4目的ip,ipv4目的端口,对应的协议封装层次(从传输层到应用层,采用,隔开),对应的应用名称 // 直接将信息写入redis操作 redisserver = RedisServer.getInstance(); String log_time = firewalls_access_bean.getLog_time(); // 日志记录的会话时间 String srcip = firewalls_access_bean.getSrc_ip(); // 获取源ip String dstip = firewalls_access_bean.getDst_ip(); // 获取目的ip String dstport = firewalls_access_bean.getDst_port(); // 目的端口 String user = firewalls_access_bean.getUser_portal(); // 用户portal String application = firewalls_access_bean.getProto(); // 对应的访问协议 String key = null; // key String field = null; // field String value = null; // value String cur_date = null; // cur_date是存放日志当前日期YYYY-MM-DD String pass_date = null; // pass_date存放已经过去的日期YYYY-MM-DD String cur_time = null; // cur_time是存放日志当前时间HH:mm:SS String start_time = null; // 用于记录ip已登记的起始时间点 String end_time = null; // 用于记录ip已登记的最后时间点 long occur = 0; // 登记ip的出现次数 int len_b = 1; // 记录整数位个数 int len_a = 1; // 记录整数位个数 String[] hms = null; // 将当前日志时间拆分为HH,mm,SS // 目前由于未明确存储压力,暂不保存任何明细日志,仅保存统计信息 // 时间必须是正确格式的时间才能进行比较和录入清单 if (log_time != null && StringUtils.equals(log_time, "none") == false) { cur_date = StringUtils.substringBeforeLast(log_time, " "); cur_time = StringUtils.substringAfterLast(log_time, " "); // 处理源ip相关统计信息,srcip必须是ip格式才进行redis操作 if (srcip != null && StringUtils.equals(srcip, "none") == false) { // 删除过期的key // srcip值存在,则判断是否时间已经超过一天 pass_date = null; key = "src_date_" + srcip; if (redisserver.exists(key) == true) { pass_date = redisserver.get(key); // pass_date先用于存放已有的时间日志 } redisserver.set(key, cur_date); // 第一步是存当前源ip出现的日期 if (pass_date != null) { if (cur_date.compareTo(pass_date) > 0) { // 删除所有过期的key值 redisserver.del("src_" + pass_date); redisserver.del("src_" + pass_date + "_" + srcip); redisserver.del("src_" + pass_date + "_detail1_" + srcip); redisserver.del("src_" + pass_date + "_detail2_" + srcip); } } // 1.1.源ip的set,支持用于排序使用 key = "src_" + cur_date; redisserver.sadd(key, srcip); // 1.1结束 // 记录当前活跃ip的列表信息,整个结构在redis中称为散列表 // 1.2.包含了每个源ip一天中的起始出现时间,最后出现时间,出现次数,以及时间跨度信息,还有对应归属的portal账号 key = "src_" + cur_date + "_" + srcip; // 由于事务是并发在进行,而cluster不支持事务,所以对于插入过程,必须有相应的判断措施 if (redisserver.hexists(key, "ip") == false) redisserver.hset(key, "ip", srcip); start_time = redisserver.hget(key, "start"); if (start_time == null) { redisserver.hset(key, "start", cur_time); start_time = cur_time; } if (cur_time.compareTo(start_time) < 0) { redisserver.hset(key, "start", cur_time); start_time = cur_time; } end_time = redisserver.hget(key, "end"); if (end_time == null) { redisserver.hset(key, "end", cur_time); end_time = cur_time; } if (cur_time.compareTo(end_time) > 0) { redisserver.hset(key, "end", cur_time); end_time = cur_time; } value = redisserver.hget(key, "times"); if (value == null) { redisserver.hset(key, "times", "1_1_1"); } else { occur = Integer.valueOf((value.split("_")[2])) + 1; len_b = String.valueOf(occur).length(); len_a = String.valueOf(len_b).length(); value = String.valueOf(len_a) + "_" + String.valueOf(len_b) + "_" + String.valueOf(occur); redisserver.hset(key, "times", value); } end_time = TimeFormatter.get_nowaday_length(start_time, end_time); // 存放时间跨度 redisserver.hset(key, "time_len", end_time); value = redisserver.hget(key, "user"); if (value == null) { redisserver.hset(key, "user", "none"); // 默认添加none值 } else if (StringUtils.equals(user.toLowerCase(), "none") == false) { redisserver.hset(key, "user", user); // 有portal更新,则默认将当前ip归属到该portal下 } // 1.2结束对源ip的活跃情况统计 hms = cur_time.split(":"); // 将当前日志时间拆分为HH,mm,SS if (hms.length == 3 && hms[1].length() == 2) { // 1.3.继续采用hash方式,保存访问的目的ip热点情况 key = "src_" + cur_date + "_detail1_" + srcip; // 记录源ip在对应时间段【按照15分钟】间隔中的出现次数,总次数从"src_"+cur_date+"_"+srcip->times中获取,此处不重复记录 if (hms[1].compareTo("00") >= 0 && hms[1].compareTo("15") < 0) hms[2] = "0"; else if (hms[1].compareTo("15") >= 0 && hms[1].compareTo("30") < 0) hms[2] = "1"; else if (hms[1].compareTo("30") >= 0 && hms[1].compareTo("45") < 0) hms[2] = "2"; else if (hms[1].compareTo("45") >= 0) hms[2] = "3"; field = hms[0] + "_" + hms[2]; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf(value) + 1; redisserver.hset(key, field, String.valueOf(occur)); // 1.3结束,此字段用于绘图,可以直接通过当前日期YYYY-MM-DD段获取到,使用HKEYS(key)可以获取所有field,缺少的时间段在绘图上写0 // dstip必须是ip格式才进行redis操作 if (dstip != null && StringUtils.equals(dstip, "none") == false) { // 1.4.保存目的ip,端口的访问热度信息,对源pi访问目的ip地址访问的相关排序请在页面完成,redis上不支持做排序 key = "src_" + cur_date + "_detail2_" + srcip; // 以下字段的设计将保证字段聚集,顺序读取,ip与端口成对保存在key中 // 记录访问的目的ip端口次数 field = dstip + "_" + dstport + "_1"; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf(value) + 1; redisserver.hset(key, field, String.valueOf(occur)); // 记录最近15分钟访问的目的ip端口次数,该值为 当天小时段HH_所在刻钟区间_访问次数 构成 // 判断对应的HH,刻钟区间之后,就能够进行最近15分钟的目的地址访问量排序,此处仅提供字段,具体操作前台页面完成 field = dstip + "_" + dstport + "_2"; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf((value.split("_")[2])) + 1; value = hms[0] + "_" + hms[2] + "_" + String.valueOf(occur); redisserver.hset(key, field, value); // 记录当前访问目的ip端口的portal field = dstip + "_" + dstport + "_3"; value = redisserver.hget(key, field); if (value == null) redisserver.hset(key, field, user); else if (StringUtils.equals(user.toLowerCase(), "none") == false) { redisserver.hset(key, field, user); // 有portal更新,则默认将当前访问的目的ip归为该portal下的行为 } // 记录当前最新访问的目的ip端口对应使用的传输应用协议 field = dstip + "_" + dstport + "_4"; redisserver.hset(key, field, application); // 1.4结束源ip对目的ip端口的访问热度情况统计,使用HKEYS(key)可以获取所有field // ====================截至目前,上边的代码段是对源ip活跃度,源ip活跃明细,共含4个大类key的定义============== // dstip值存在,则判断是否时间已经超过一天 pass_date = null; key = "dst_date_" + dstip; if (redisserver.exists(key) == true) { pass_date = redisserver.get(key); // pass_date先用于存放已有的时间日志 } redisserver.set(key, cur_date); // 第一步是存当前目的ip出现的日期 if (pass_date != null) { if (cur_date.compareTo(pass_date) > 0) { // 删除所有过期的key值 redisserver.del("dst_" + pass_date); redisserver.del("dst_" + pass_date + "_" + dstip); redisserver.del("dst_" + pass_date + "_detail1_" + dstip); redisserver.del("dst_" + pass_date + "_detail2_" + dstip); } } // 处理目的ip相关统计信息,dstip必须是ip格式才进行redis操作 // 2.1.目的ip的set,支持用于被访问热度排序 key = "dst_" + cur_date; redisserver.sadd(key, dstip); // 2.1结束 // 记录当前繁忙的服务器ip的列表信息,整个结构在redis中称为散列表 // 2.2.包含了每个目的ip开始被访问时间,最后被访问时间,当天被访问总次数,以及时间跨度信息,当前15分钟的变化量 key = "dst_" + cur_date + "_" + dstip; // 由于事务是并发在进行,而cluster不支持事务,所以对于插入过程,必须有相应的判断措施 if (redisserver.hexists(key, "ip") == false) redisserver.hset(key, "ip", dstip); start_time = redisserver.hget(key, "start"); if (start_time == null) { redisserver.hset(key, "start", cur_time); start_time = cur_time; } if (cur_time.compareTo(start_time) < 0) { redisserver.hset(key, "start", cur_time); start_time = cur_time; } end_time = redisserver.hget(key, "end"); if (end_time == null) { redisserver.hset(key, "end", cur_time); end_time = cur_time; } if (cur_time.compareTo(end_time) > 0) { redisserver.hset(key, "end", cur_time); end_time = cur_time; } occur = 1; value = redisserver.hget(key, "times"); if (value == null) { redisserver.hset(key, "times", "1_1_1"); } else { occur = Integer.valueOf((value.split("_")[2])) + 1; len_b = String.valueOf(occur).length(); len_a = String.valueOf(len_b).length(); value = String.valueOf(len_a) + "_" + String.valueOf(len_b) + "_" + String.valueOf(occur); redisserver.hset(key, "times", value); } end_time = TimeFormatter.get_nowaday_length(start_time, end_time); // 存放服务器最近被访问时间跨度 redisserver.hset(key, "time_len", end_time); // 记录最近15分钟目的ip访问次数,该值为 当天小时段HH_所在刻钟区间_数值位数A_数值位数B_访问次数 构成 // 这样写的好处是便于进行最近15分钟的目的地址访问量进行排序, // 数值位数A描述的是数值位数B的数字量,即描述的是几位整数,而数值位数B描述的是访问次数的整数位数 // 这样写之后能够满足对近15分钟繁忙程度的排序需求 value = redisserver.hget(key, "recent"); // 并发访问,此处要防止出现未写先读的保护 if (value == null || StringUtils.contains(value, "_") == false || value.split("_").length < 5) { redisserver.hset(key, "recent", hms[0] + "_" + hms[2] + "_1_1_1"); } else { occur = Integer.valueOf((value.split("_")[4])) + 1; len_b = String.valueOf(occur).length(); len_a = String.valueOf(len_b).length(); value = hms[0] + "_" + hms[2] + "_" + String.valueOf(len_a) + "_" + String.valueOf(len_b) + "_" + String.valueOf(occur); redisserver.hset(key, "recent", value); } // 2.2结束对目的ip的繁忙情况统计 // 2.3.继续采用hash方式,保存目的ip繁忙情况 key = "dst_" + cur_date + "_detail1_" + dstip; // 记录源ip在对应时间段【按照15分钟】间隔中的出现次数,总次数从"dst_"+cur_date+"_"+dstip->times中获取,此处不重复记录 field = hms[0] + "_" + hms[2]; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf(value) + 1; redisserver.hset(key, field, String.valueOf(occur)); // 2.3结束,此字段用于绘图,可以直接通过当前日期YYYY-MM-DD段获取到,使用HKEYS(key)可以获取所有field,缺少的时间段在绘图上写0 // 2.4.保存源pi访问目的ip地址热度详情,相关排序请在页面完成,redis上不支持做排序 key = "dst_" + cur_date + "_detail2_" + dstip; // 以下字段的设计将保证字段聚集,顺序读取,ip与端口成对保存在key中 // 记录访问的目的ip端口次数 field = srcip + "_1"; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf(value) + 1; redisserver.hset(key, field, String.valueOf(occur)); // 记录最近15分钟源ip发起访问的次数,该值为 当天小时段HH_所在刻钟区间_访问次数 构成 // 判断对应的HH,刻钟区间之后,就能够进行最近15分钟的目的地址访问量排序,此处仅提供字段,具体操作前台页面完成 field = srcip + "_2"; value = redisserver.hget(key, field); if (value == null) occur = 1; else occur = Integer.valueOf((value.split("_")[2])) + 1; value = hms[0] + "_" + hms[2] + "_" + String.valueOf(occur); redisserver.hset(key, field, value); // 记录访问本服务器的源ip的portal field = srcip + "_3"; value = redisserver.hget(key, field); if (value == null) redisserver.hset(key, field, user); else if (StringUtils.equals(user.toLowerCase(), "none") == false) { redisserver.hset(key, field, user); // 有portal更新,则默认将当前访问的目的ip归为该portal下的行为 } // 记录源ip使用的传输应用协议 field = srcip + "_4"; redisserver.hset(key, field, application); // 2.4结束源ip对目的ip端口的访问热度情况统计,使用HKEYS(key)可以获取所有field } } } } // 释放内存 log_time = null; srcip = null; dstip = null; dstport = null; user = null; application = null; key = null; field = null; value = null; cur_date = null; cur_time = null; pass_date = null; start_time = null; end_time = null; hms = null; redisserver = null; firewalls_access_bean = null; collector.ack(tuple); }
/** build the context for batch archive confirm */ public String buildDownloadContext( VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { context.put("tlang", rb); buildMenu(context); // get list of existing archives Collection<File> files = Collections.<File>emptySet(); File archiveBaseDir = new File(serverConfigurationService.getString("archive.storage.path", "sakai/archive")); if (archiveBaseDir.exists() && archiveBaseDir.isDirectory()) { files = FileUtils.listFiles(archiveBaseDir, new SuffixFileFilter(".zip"), null); } List<SparseFile> zips = new ArrayList<SparseFile>(); SimpleDateFormat dateFormatIn = new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat dateFormatOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); // porcess the list. also get the hash for the file if it exists for (File f : files) { String absolutePath = f.getAbsolutePath(); SparseFile sf = new SparseFile(); sf.setFilename(f.getName()); sf.setAbsolutePath(absolutePath); sf.setSize(FileUtils.byteCountToDisplaySize(f.length())); // get the datetime string, its the last part of the file name, convert back to a date that we // can display String dateTimeStr = StringUtils.substringAfterLast(StringUtils.removeEnd(f.getName(), ".zip"), "-"); try { Date date = dateFormatIn.parse(dateTimeStr); sf.setDateCreated(dateFormatOut.format(date)); } catch (ParseException pe) { // ignore, just don't set the date } // get siteId, first part of name String siteId = StringUtils.substringBeforeLast(f.getName(), "-"); sf.setSiteId(siteId); // try to get site title if the site still exists try { Site site = siteService.getSite(siteId); sf.setSiteTitle(site.getTitle()); } catch (IdUnusedException e) { // ignore, no site available } // get the hash. need to read it from the file. Same filename but diff extension String hashFilePath = StringUtils.removeEnd(absolutePath, ".zip"); hashFilePath = hashFilePath + ".sha1"; File hashFile = new File(hashFilePath); try { String hash = FileUtils.readFileToString(hashFile); sf.setHash(hash); } catch (IOException e) { // ignore, dont use the hash } zips.add(sf); } context.put("archives", zips); return "-download"; }
@Override public boolean matchFilePattern(String antPattern) { String patternWithoutFileSuffix = StringUtils.substringBeforeLast(antPattern, "."); WildcardPattern matcher = WildcardPattern.create(patternWithoutFileSuffix, "."); return matcher.match(getKey()); }