/** * 对源代码进行格式化,格式化失败返回原格式 * * @param sourceCode * @return */ public static String formatCode(String sourceCode) { BufferedReader reader = new BufferedReader(new StringReader(sourceCode)); try { StringBuilder header = new StringBuilder(); StringBuilder content = new StringBuilder(); String lineSeparator = System.getProperty("line.separator", "\n"); boolean isHeader = true; String line; while ((line = reader.readLine()) != null) { line = StringUtils.trim(line); if (StringUtils.isBlank(line)) { continue; } if (isHeader && (StringUtils.startsWith(line, "package") || StringUtils.startsWith(line, "import"))) { header.append(line).append(lineSeparator); } else { isHeader = false; content.append(line).append(lineSeparator); } } String finalCode = StringUtils.trim(content.toString()); finalCode = formatBodyCode(finalCode); return header.append(finalCode).toString(); } catch (Exception e) { LOG.error("格式化源代码失败", e); // 忽略,返回原格式 } finally { IOUtils.closeQuietly(reader); } return sourceCode; }
private void trimConf(Conf conf) { if (conf == null) return; conf.setConfGroup(StringUtils.trim(conf.getConfGroup())); conf.setConfKey(StringUtils.trim(conf.getConfKey())); conf.setConfValue(StringUtils.trim(conf.getConfValue())); conf.setConfDefaultValue(StringUtils.trim(conf.getConfDefaultValue())); }
@Override public void configure(Map<String, String> parameters) throws IllegalArgumentException, IllegalStateException { if (this.parameters != null) { throw new IllegalStateException( "cannot change configuration, may be already in use somewhere"); } directoryName = parameters.get(PARAM_DIRECTORY); if (directoryName != null) { directoryName = directoryName.trim(); } if (directoryName == null || directoryName.isEmpty()) { throw new IllegalArgumentException( "missing directory parameter. A directory name is necessary"); } fetchDirectory(); idField = directory.getIdField(); schema = directory.getSchema(); if (schema.endsWith("xvocabulary")) { hierarchical = true; parentField = "parent"; separator = "/"; } String parentFieldParam = StringUtils.trim(parameters.get(PARAM_PARENT_FIELD)); String separatorParam = StringUtils.trim(parameters.get(PARAM_SEPARATOR)); if (!StringUtils.isBlank(parentFieldParam) && !StringUtils.isBlank(separatorParam)) { hierarchical = true; parentField = parentFieldParam; separator = separatorParam; } this.parameters = new HashMap<String, Serializable>(); this.parameters.put(PARAM_DIRECTORY, directory.getName()); }
@Override public long login( HttpServletRequest request, HttpServletResponse response, String loginName, String pwd, boolean persistent) throws PassportAccountException { loginName = StringUtils.trim(loginName); pwd = StringUtils.trim(pwd); if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(pwd)) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Passport passport = passportService.getPassportByLoginName(loginName); if (null == passport || !StringUtils.equals(passport.getPassword(), DigestUtils.md5Hex(pwd))) { throw new PassportAccountException(PassportAccountException.ACCOUNT_OR_PWD_ERROR); } Thirdparty tp = null; TpUser tpUser = tpUserService.getTpUserByUid(passport.getId()); if (null != tpUser) { tp = InitData.getTpByTpNameAndJoinType(tpUser.getTpName(), JoinTypeEnum.CONNECT); } doLogin( request, response, passport.getId(), tp != null ? tp.getId() : 0L, RunType.WEB, persistent); nativeLoginCounter.incr(null, 1); return passport.getId(); }
/** * Parses a {@link SimpleConcept} from a String * * @param concept * @return * @author jmayaalv */ public static SimpleConcept parse(String concept) { if (StringUtils.isBlank(concept)) { return null; } concept = StringUtils.trim(concept); if ((StringUtils.countMatches(concept, "(") == (StringUtils.countMatches(concept, ")"))) && StringUtils.startsWith(concept, "(") && StringUtils.endsWith(concept, ")")) { concept = StringUtils.substring(concept, 1, concept.length() - 1); } boolean negated = false; if (concept.startsWith(".NO")) { negated = true; concept = StringUtils.remove(concept, ".NO"); concept = StringUtils.trim(concept); } if (StringUtils.isBlank(concept)) { throw new RuntimeException("Concept can't be parsed: " + concept); } if ((StringUtils.countMatches(concept, "(") == (StringUtils.countMatches(concept, ")"))) && StringUtils.startsWith(concept, "(") && StringUtils.endsWith(concept, ")")) { concept = StringUtils.substring(concept, 1, concept.length() - 1); } if (StringUtils.contains(concept, " ")) { return null; // not a SimpleConcep } return new SimpleConcept(Integer.parseInt(concept), negated); }
private ParamStruct processParameter(SMInputCursor ruleC) throws XMLStreamException { ParamStruct param = new ParamStruct(); // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT String keyAttribute = ruleC.getAttrValue("key"); if (StringUtils.isNotBlank(keyAttribute)) { param.key = StringUtils.trim(keyAttribute); } // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT String typeAttribute = ruleC.getAttrValue("type"); if (StringUtils.isNotBlank(typeAttribute)) { param.type = RuleParamType.parse(typeAttribute); } SMInputCursor paramC = ruleC.childElementCursor(); while (paramC.getNext() != null) { String propNodeName = paramC.getLocalName(); String propText = StringUtils.trim(paramC.collectDescendantText(false)); if (StringUtils.equalsIgnoreCase("key", propNodeName)) { param.key = propText; } else if (StringUtils.equalsIgnoreCase("description", propNodeName)) { param.description = propText; } else if (StringUtils.equalsIgnoreCase("type", propNodeName)) { param.type = RuleParamType.parse(propText); } else if (StringUtils.equalsIgnoreCase("defaultValue", propNodeName)) { param.defaultValue = propText; } } return param; }
protected void parseBindingConfig(String bindingConfigs, LgtvBindingConfig config) throws BindingConfigParseException { String bindingConfig = StringUtils.substringBefore(bindingConfigs, ","); String bindingConfigTail = StringUtils.substringAfter(bindingConfigs, ","); String[] configParts = bindingConfig.trim().split(":"); if (configParts.length != 3) { throw new BindingConfigParseException( "Lgtv binding must contain three parts separated by ':'"); } String command = StringUtils.trim(configParts[0]); String deviceId = StringUtils.trim(configParts[1]); String deviceCommand = StringUtils.trim(configParts[2]); // Advanced command start with # character if (!deviceCommand.startsWith(ADVANCED_COMMAND_KEY)) { try { LgTvCommand.valueOf(deviceCommand); } catch (Exception e) { throw new BindingConfigParseException("Unregonized command '" + deviceCommand + "'"); } } // if there are more commands to parse do that recursively ... if (StringUtils.isNotBlank(bindingConfigTail)) { parseBindingConfig(bindingConfigTail, config); } config.put(command, deviceId + ":" + deviceCommand); }
public RulesProfile parse(Reader reader, ValidationMessages messages) { RulesProfile profile = RulesProfile.create(); SMInputFactory inputFactory = initStax(); try { SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader); rootC.advance(); // <profile> SMInputCursor cursor = rootC.childElementCursor(); while (cursor.getNext() != null) { String nodeName = cursor.getLocalName(); if (StringUtils.equals("rules", nodeName)) { SMInputCursor rulesCursor = cursor.childElementCursor("rule"); processRules(rulesCursor, profile, messages); } else if (StringUtils.equals("name", nodeName)) { profile.setName(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equals("language", nodeName)) { profile.setLanguage(StringUtils.trim(cursor.collectDescendantText(false))); } } } catch (XMLStreamException e) { messages.addErrorText("XML is not valid: " + e.getMessage()); } checkProfile(profile, messages); return profile; }
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("link".equalsIgnoreCase(localName)) { String rel = StringUtils.trim(attributes.getValue("rel")); String href = StringUtils.trim(attributes.getValue("href")); if ("shortcut icon".equalsIgnoreCase(rel) || "icon".equalsIgnoreCase(rel)) { if (href.startsWith("http")) { favicon = href; } else { if (!href.startsWith("/")) { // TODO Build relative links relative to base url href = "/" + href; } try { favicon = new URL(url.getProtocol(), url.getHost(), url.getPort(), href).toString(); } catch (MalformedURLException e) { log.error( MessageFormat.format( "Error building absolute url for favicon {0} from page {1}", href, url.toString()), e); } } } return; } }
private void extractPageRange(String pageRange) { String[] pageRangeArray = pageRange.split(PAGE_RANGE_SEPARATOR); int firstPage = Integer.parseInt(StringUtils.trim(pageRangeArray[0])); int lastPage = Integer.parseInt(StringUtils.trim(pageRangeArray[1])); for (int i = firstPage; i < lastPage + 1; i++) { getPagesList().add(i); } }
public Settings appendProperty(String key, String value) { String newValue = properties.get(definitions.validKey(key)); if (StringUtils.isEmpty(newValue)) { newValue = StringUtils.trim(value); } else { newValue += "," + StringUtils.trim(value); } return setProperty(key, newValue); }
@Override public void switchVO2PO(AuditMind po, AuditMindSO so) { po.setDataId(so.getDataId()); po.setSort(so.getSort()); po.setMind(StringUtils.trim(so.getMind())); po.setRealname(StringUtils.trim(so.getRealname())); po.setState(so.getState()); po.setAuditDate(StringUtils.trim(so.getAuditDate())); }
protected String cleanseValue(String value) { value = StringUtils.trim(value); value = StringUtils.removeStart(value, "'"); value = StringUtils.removeStart(value, "\""); value = StringUtils.removeEnd(value, "\""); value = StringUtils.removeEnd(value, "'"); value = StringUtils.trim(value); return value; }
private static void processRule(Rule rule, SMInputCursor ruleC) throws XMLStreamException { /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */ String keyAttribute = ruleC.getAttrValue("key"); if (StringUtils.isNotBlank(keyAttribute)) { rule.setKey(StringUtils.trim(keyAttribute)); } /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */ String priorityAttribute = ruleC.getAttrValue("priority"); if (StringUtils.isNotBlank(priorityAttribute)) { rule.setSeverity(RulePriority.valueOf(StringUtils.trim(priorityAttribute))); } List<String> tags = Lists.newArrayList(); SMInputCursor cursor = ruleC.childElementCursor(); while (cursor.getNext() != null) { String nodeName = cursor.getLocalName(); if (StringUtils.equalsIgnoreCase("name", nodeName)) { rule.setName(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equalsIgnoreCase("description", nodeName)) { rule.setDescription(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equalsIgnoreCase("key", nodeName)) { rule.setKey(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equalsIgnoreCase("configKey", nodeName)) { rule.setConfigKey(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equalsIgnoreCase("priority", nodeName)) { rule.setSeverity( RulePriority.valueOf(StringUtils.trim(cursor.collectDescendantText(false)))); } else if (StringUtils.equalsIgnoreCase("cardinality", nodeName)) { rule.setCardinality( Cardinality.valueOf(StringUtils.trim(cursor.collectDescendantText(false)))); } else if (StringUtils.equalsIgnoreCase("status", nodeName)) { rule.setStatus(StringUtils.trim(cursor.collectDescendantText(false))); } else if (StringUtils.equalsIgnoreCase("param", nodeName)) { processParameter(rule, cursor); } else if (StringUtils.equalsIgnoreCase("tag", nodeName)) { tags.add(StringUtils.trim(cursor.collectDescendantText(false))); } } if (Strings.isNullOrEmpty(rule.getKey())) { throw new SonarException("Node <key> is missing in <rule>"); } rule.setTags(tags.toArray(new String[tags.size()])); }
/** * El nombre de la tabla lo saca de la tabla indicada tras el TRANSFORM El municipio de IN (xxxx) * * @param layer * @return */ public static String[] getTableNameFromLayer(LocalgisLayer layer) { String[] transform = {"transform(", "TRANSFORM("}; String[] in = {" in ", " IN "}; int transPos = -1; int inPos = -1; int leftParPos = -1; int rightParPos = -1; String[] datos = new String[5]; String sql = layer.getLayerquery(); // Nombre de tabla transPos = StringUtils.lastIndexOfAny(sql, transform); String subStrTransform = sql.substring(transPos + transform[0].length()); datos[0] = subStrTransform.substring(0, subStrTransform.indexOf(".")); // datos[0] = datos[0].toLowerCase(); // datos[0] = StringUtils.remove(datos[0], "\""); StringUtils.trim(datos[0]); if (datos[0].startsWith("\"GEOMETRY")) { /* * Por aqui no debería entrar nunca está para solucionar una * indicencia cuando en el campo layerquery de la tabla * localgisguiaurbana.layer no tenemos * .....transform("tabla"."GEOMETRY" sino ...transform("GEOMETRY*... * Lo cojo del ppio SELECT "nombreTabla".oid... */ int finTablaPos = -1; String nombreTabla = ""; finTablaPos = sql.indexOf("\"."); // 8=SELECT+ESPACIO nombreTabla = sql.substring(8, finTablaPos); datos[0] = nombreTabla.trim(); } // Municipio inPos = StringUtils.lastIndexOfAny(sql, in); String subStrIn = sql.substring(inPos + 2); leftParPos = subStrIn.indexOf("("); rightParPos = subStrIn.indexOf(")"); if (leftParPos != -1 && rightParPos != -1) { datos[1] = subStrIn.substring(leftParPos + 1, rightParPos); StringUtils.trim(datos[1]); } else { datos[1] = null; } return datos; }
private void addSymbolicLink(Request request, WikiPage page) throws Exception { String linkName = StringUtils.trim(request.getInput("linkName")); String linkPath = StringUtils.trim(request.getInput("linkPath")); PageData data = page.getData(); WikiPageProperty properties = data.getProperties(); WikiPageProperty symLinks = getSymLinkProperty(properties); if (isValidLinkPathName(linkPath) && isValidWikiPageName(linkName, symLinks)) { symLinks.set(linkName, linkPath); page.commit(data); setRedirect(resource); } }
private void processRules( SMInputCursor rulesCursor, RulesProfile profile, ValidationMessages messages) throws XMLStreamException { Map<String, String> parameters = new HashMap<>(); while (rulesCursor.getNext() != null) { SMInputCursor ruleCursor = rulesCursor.childElementCursor(); String repositoryKey = null; String key = null; RulePriority priority = null; parameters.clear(); while (ruleCursor.getNext() != null) { String nodeName = ruleCursor.getLocalName(); if (StringUtils.equals("repositoryKey", nodeName)) { repositoryKey = StringUtils.trim(ruleCursor.collectDescendantText(false)); } else if (StringUtils.equals("key", nodeName)) { key = StringUtils.trim(ruleCursor.collectDescendantText(false)); } else if (StringUtils.equals("priority", nodeName)) { priority = RulePriority.valueOf(StringUtils.trim(ruleCursor.collectDescendantText(false))); } else if (StringUtils.equals("parameters", nodeName)) { SMInputCursor propsCursor = ruleCursor.childElementCursor("parameter"); processParameters(propsCursor, parameters); } } Rule rule = ruleFinder.findByKey(repositoryKey, key); if (rule == null) { messages.addWarningText("Rule not found: " + ruleToString(repositoryKey, key)); } else { ActiveRule activeRule = profile.activateRule(rule, priority); for (Map.Entry<String, String> entry : parameters.entrySet()) { if (rule.getParam(entry.getKey()) == null) { messages.addWarningText( "The parameter '" + entry.getKey() + "' does not exist in the rule: " + ruleToString(repositoryKey, key)); } else { activeRule.setParameter(entry.getKey(), entry.getValue()); } } } } }
public void reminder(WorkflowTask task) throws Exception { String[] reminderStyles = task.getReminderStyle().split(","); for (String style : reminderStyles) { if (StringUtils.trim(style).equalsIgnoreCase(CommonStrings.EMAIL_STYLE)) { emailReminder(task); } else if (StringUtils.trim(style).equalsIgnoreCase(CommonStrings.RTX_STYLE)) { rtxReminder(task); } else if (StringUtils.trim(style).equalsIgnoreCase(CommonStrings.SMS_STYLE)) { smsReminder(task); } else if (StringUtils.trim(style).equalsIgnoreCase(CommonStrings.SWING_STYLE)) { swingReminder(task); } } }
/** * Creates this from a JDOM element. * * @param jdom input */ public UserQueryInput(Element jdom) { // Done in LuceneSearcher#computeQuery // protectRequest(jdom); for (Object e : jdom.getChildren()) { if (e instanceof Element) { Element node = (Element) e; String nodeName = node.getName(); String nodeValue = StringUtils.trim(node.getText()); if (SearchParameter.SIMILARITY.equals(nodeName)) { setSimilarity(jdom.getChildText(SearchParameter.SIMILARITY)); } else { if (StringUtils.isNotBlank(nodeValue)) { if (SECURITY_FIELDS.contains(nodeName) || nodeName.contains("_op")) { addValues(searchPrivilegeCriteria, nodeName, nodeValue); } else if (RESERVED_FIELDS.contains(nodeName)) { searchOption.put(nodeName, nodeValue); } else { // addValues(searchCriteria, nodeName, nodeValue); // Rename search parameter to lucene index field // when needed addValues( searchCriteria, (searchParamToLuceneField.containsKey(nodeName) ? searchParamToLuceneField.get(nodeName) : nodeName), nodeValue); } } } } } }
/** * bean转化成字符串 * * @param bean * @param beanName * @return beanStr */ public static String convertBean2Str(Object bean, String beanName) { StringBuffer str = new StringBuffer(); Class<? extends Object> type = bean.getClass(); try { BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean, new Object[0]); if (result != null && StringUtils.trim(result.toString()).length() != 0) { str.append("&") .append(beanName) .append(".") .append(propertyName) .append("=") .append(result); } } } } catch (Exception e) { log.error(e.getMessage(), e); } return str.indexOf("&") != -1 ? str.substring(1) : str.toString(); }
/** * Generate SELECT statment * * @return */ private String buildSelectSQL() { StringBuffer resultSQL = new StringBuffer(); if (chkComment.getSelection()) { resultSQL.append("/* Tadpole SQL Generator */"); // $NON-NLS-1$ } resultSQL.append("SELECT "); // $NON-NLS-1$ int cnt = 0; StringBuffer sbColumn = new StringBuffer(); for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) { if (allDao.isCheck()) { if (cnt != 0) sbColumn.append("\t, "); // $NON-NLS-1$ if ("*".equals(allDao.getField())) { // $NON-NLS-1$ sbColumn.append(allDao.getSysName()); } else { String strTableAlias = !"".equals(textTableAlias.getText().trim()) ? //$NON-NLS-1$ textTableAlias.getText().trim() + "." + allDao.getSysName() + " as " + allDao.getColumnAlias() : //$NON-NLS-1$ //$NON-NLS-2$ allDao.getSysName() + " as " + allDao.getColumnAlias(); // $NON-NLS-1$ sbColumn.append(strTableAlias); } cnt++; } } if (StringUtils.isEmpty(StringUtils.trim(sbColumn.toString()))) sbColumn.append(" * "); // $NON-NLS-1$ resultSQL.append(sbColumn.toString()); resultSQL.append( " FROM " + this.tableDAO.getSysName() + " " + this.textTableAlias.getText().trim()); // $NON-NLS-1$ //$NON-NLS-2$ cnt = 0; for (ExtendTableColumnDAO allDao : (List<ExtendTableColumnDAO>) tableViewer.getInput()) { if ("PK".equals(allDao.getKey())) { // $NON-NLS-1$ if (cnt == 0) { resultSQL.append(" WHERE "); // $NON-NLS-1$ } else { resultSQL.append(" AND "); // $NON-NLS-1$ } resultSQL.append(allDao.getColumnNamebyTableAlias()).append(" = ? "); // $NON-NLS-1$ if (chkComment.getSelection()) { resultSQL.append("/* " + allDao.getType() + " */"); // $NON-NLS-1$ //$NON-NLS-2$ } cnt++; } } return lastSQLGen(resultSQL.toString()); }
/** * json normal string to pretty string * * @param jsonString * @return */ public static String getPretty(String jsonString) { if (jsonString == null) return ""; // if(logger.isDebugEnabled()) { // logger.debug("======================================================"); // logger.debug("==> ["+ jsonString + "]"); // logger.debug("======================================================"); // } try { JsonParser jp = new JsonParser(); JsonElement je = jp.parse(StringUtils.trim(jsonString)); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String strGson = gson.toJson(je); System.out.println(StringUtils.trimToEmpty(strGson)); if (strGson == null || "null".equals(strGson)) strGson = ""; return strGson; } catch (Exception e) { // logger.error("pretty json", e); } return jsonString; }
/** * Save fileEntry and return the the path. * * @param user current user * @param path path to which this will forward. * @param fileEntry file to be saved * @param targetHosts target host parameter * @param createLibAndResource true if lib and resources should be created as well. * @param validated validated the script or not, 1 is validated, 0 is not. * @param model model * @return script/scriptList */ @RequestMapping(value = "/save/**", method = RequestMethod.POST) public String saveFileEntry( User user, @RemainedPath String path, FileEntry fileEntry, @RequestParam String targetHosts, @RequestParam(defaultValue = "0") String validated, @RequestParam(defaultValue = "false") boolean createLibAndResource, ModelMap model) { Map<String, String> map = new HashMap<String, String>(); map.put("validated", validated); if (StringUtils.isNotBlank(targetHosts)) { map.put("targetHosts", StringUtils.trim(targetHosts)); } fileEntry.setProperties(map); fileEntryService.save(user, fileEntry); String basePath = FilenameUtils.getPath(fileEntry.getPath()); if (createLibAndResource) { fileEntryService.addFolder(user, basePath, "lib", getMessages("script.commit.libfolder")); fileEntryService.addFolder( user, basePath, "resources", getMessages("script.commit.resourcefolder")); } model.clear(); return "redirect:/script/list/" + basePath; }
private void addLink( Study study, Map<Integer, Term> stageForNode, Map<Integer, String> taxonForNode, LabeledCSVParser links, Location location) throws StudyImporterException, NodeFactoryException { Integer consumerNodeID = Integer.parseInt(links.getValueByLabel("ConsumerNodeID")); Integer resourceNodeID = Integer.parseInt(links.getValueByLabel("ResourceNodeID")); String linkType = links.getValueByLabel("LinkType"); InteractType interactType = interactionMapping.get(StringUtils.trim(StringUtils.lowerCase(linkType))); if (interactType == null) { throw new StudyImporterException( "failed to map interaction type [" + linkType + "] in line [" + links.lastLineNumber() + "]"); } Specimen consumer = nodeFactory.createSpecimen(study, taxonForNode.get(consumerNodeID)); consumer.setLifeStage(stageForNode.get(consumerNodeID)); consumer.setExternalId(getNamespace() + ":NodeID:" + consumerNodeID); consumer.caughtIn(location); String resourceName = taxonForNode.get(resourceNodeID); Specimen resource = nodeFactory.createSpecimen(study, resourceName); resource.setLifeStage(stageForNode.get(resourceNodeID)); resource.setExternalId(getNamespace() + ":NodeID:" + resourceNodeID); resource.caughtIn(location); consumer.interactsWith(resource, interactType); }
private void loadRuleKeys() { XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE); // just so it won't try to load DTD in if there's DOCTYPE xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); SMInputFactory inputFactory = new SMInputFactory(xmlFactory); InputStream inputStream = getClass().getResourceAsStream(AndroidLintRulesDefinition.RULES_XML_PATH); InputStreamReader reader = new InputStreamReader(inputStream, Charsets.UTF_8); try { SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader); rootC.advance(); // <rules> SMInputCursor rulesC = rootC.childElementCursor("rule"); while (rulesC.getNext() != null) { // <rule> SMInputCursor cursor = rulesC.childElementCursor(); while (cursor.getNext() != null) { if (StringUtils.equalsIgnoreCase("key", cursor.getLocalName())) { String key = StringUtils.trim(cursor.collectDescendantText(false)); ruleKeys.add(key); } } } } catch (XMLStreamException e) { throw new IllegalStateException("XML is not valid", e); } }
private void processElementChildren( final Element element, final String key, final Map<String, String> properties) { for (int i = 0, size = element.nodeCount(); i < size; i++) { Node node = element.node(i); if (logger.isDebugEnabled()) { logger.debug(String.format("Processing xml element %s", node.getPath())); } if (node instanceof Element) { StringBuilder sbPrefix = new StringBuilder(key); if (sbPrefix.length() > 0) { sbPrefix.append("."); } sbPrefix.append(node.getName()); if (!excludeProperties.contains(sbPrefix.toString())) { processElementChildren((Element) node, sbPrefix.toString(), properties); } } else { StringBuilder sb = new StringBuilder(); if (properties.containsKey(key)) { sb.append(properties.get(key)); if (sb.length() > 0) { sb.append(multivalueSeparator); } } String value = node.getText(); if (StringUtils.isNotBlank(value)) { if (logger.isDebugEnabled()) { logger.debug(String.format("Adding value [%s] for property [%s].", value, key)); } sb.append(value); properties.put(key, StringUtils.trim(sb.toString())); } } } }
public static String getParameter(OAuthMessage requestMessage, String key) { try { return StringUtils.trim(requestMessage.getParameter(key)); } catch (IOException e) { return null; } }
/** * Verifies that a file exists with the specified content. * * @param name the file name * @param content the expected file content * @return the file * @throws IOException for any I/O error */ private File checkContains(String name, String content) throws IOException { checkExists(name); File file = new File(temporaryFolder.getRoot(), name); List<String> fileContent = FileUtil.getFileContent(file.getPath()); assertEquals(1, fileContent.size()); assertEquals(content, StringUtils.trim(fileContent.get(0))); return file; }
public static String joinHostFlags(List<String> flags) { List<String> results = new ArrayList<String>(); for (String flag : flags) { results.add(StringUtils.trim(flag)); } Collections.sort(results); return StringUtils.join(results.toArray(), ","); }
private boolean isLastCommandProcessed(HiveDriverRunHookContext hookContext) { String currentCmd = hookContext.getCommand(); currentCmd = StringUtils.trim(currentCmd.replaceAll("\\n", "")); if (currentCmd.equals(lastCmd)) { return true; } return false; }