List of usage examples for org.apache.commons.lang StringUtils startsWith
public static boolean startsWith(String str, String prefix)
Check if a String starts with a specified prefix.
From source file:com.steeleforge.aem.ironsites.wcm.WCMUtil.java
/** * Given a relative path, this method can resolve mappings, append suffix * mangle JCR paths, XSS cleanse, append selectors, and apply extension(s). * /* www . ja va2 s. c o m*/ * @param request * @param path * @param selectors * @param extension * @param suffix * @param extensionSuffix * @param jcrMangle * @param resolverMap * @param sanitize * @return */ public static String getRelativeURL(SlingHttpServletRequest request, String path, String selectors, String extension, String suffix, boolean extensionSuffix, boolean jcrMangle, boolean resolverMap, boolean sanitize) { String href = path; SlingScriptHelper sling = WCMUtil.getSlingScriptHelper(request); ResourceResolver resolver = request.getResourceResolver(); // fail fast if path input doesn't appear to be relative // nor internal if (!StringUtils.startsWith(path, "/") || null == resolver.resolve(path)) { return href; } // check for resolver mapping if requested as parameter href = (resolverMap) ? resolver.map(path) : path; // mangle sling resource paths if necessary (e.g. jcr:content -> _jcr:content)) if (jcrMangle) { href = getMangledPath(href); } StringBuilder sb = new StringBuilder(href); // selectors, if provided if (StringUtils.isNotBlank(selectors)) { sb.append(getDelimitered(selectors, WCMConstants.DELIMITER_SELECTOR)); } // base resource path extension is presumably ".html" by default String ext = (StringUtils.isNotBlank(extension)) ? extension : WCMConstants.HTML; sb.append(getDelimitered(ext, WCMConstants.DELIMITER_EXTENSION)); // suffix (and extension) if provided if (StringUtils.isNotBlank(suffix)) { sb.append(getDelimitered(suffix, WCMConstants.DELIMITER_SUFFIX)); if (extensionSuffix) { sb.append(ext); } } href = sb.toString(); if (sanitize) { XSSAPI xss = (XSSAPI) sling.getService(XSSAPI.class); xss = xss.getRequestSpecificAPI(request); return xss.getValidHref(href); } return href; }
From source file:com.inktomi.wxmetar.MetarParser.java
static boolean parseAltimeter(String token, final Metar metar) { boolean rval = Boolean.FALSE; if (StringUtils.startsWith(token, "A") && token.length() == 5) { rval = Boolean.TRUE;//from w w w. j a v a 2s . c om Integer alt = Integer.parseInt(StringUtils.substring(token, 1, token.length())); metar.altimeter = (float) alt / 100; } return rval; }
From source file:eu.europeana.uim.plugin.solr.service.SolrWorkflowPlugin.java
@Override public boolean process(MetaDataRecord<I> mdr, ExecutionContext<MetaDataRecord<I>, I> context) throws IngestionPluginFailedException, CorruptedDatasetException { mdr.deleteValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD); String overrideChecks = context.getProperties().getProperty(OVERRIDECHECKS); boolean check = false; if (StringUtils.isNotEmpty(overrideChecks)) { check = Boolean.parseBoolean(overrideChecks); }/* w w w. j av a2 s . c o m*/ if (StringUtils.isNotEmpty(context.getProperties().getProperty(CLEARCACHE))) { if (Boolean.parseBoolean(context.getProperties().getProperty(CLEARCACHE))) { OsgiExtractor.clearCache(); VocMemCache.clearCache(solrWorkflowService); } } SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US); try { Date updateDate = sdf.parse((mdr.getValues(EuropeanaModelRegistry.UIMUPDATEDDATE).size() > 0) ? mdr.getValues(EuropeanaModelRegistry.UIMUPDATEDDATE).get(0) : new Date(0).toString()); Date ingestionDate = new Date(context.getValue(date)); if (updateDate.after(ingestionDate) || updateDate.toString().equals(ingestionDate.toString()) || check) { if (mdr.getValues(EuropeanaModelRegistry.STATUS).size() == 0 || !mdr.getValues(EuropeanaModelRegistry.STATUS).get(0).equals(Status.DELETED)) { try { String value = mdr.getValues(EuropeanaModelRegistry.EDMRECORD).get(0); IUnmarshallingContext uctx = bfact.createUnmarshallingContext(); IMarshallingContext marshallingContext = bfact.createMarshallingContext(); marshallingContext.setIndent(2); RDF rdf = (RDF) uctx.unmarshalDocument(new StringReader(value)); RDF rdfCopy = clone(rdf); if (rdf.getAgentList() != null) { for (AgentType agent : rdf.getAgentList()) { dereferenceAgent(rdfCopy, agent); } } if (rdf.getConceptList() != null) { for (Concept concept : rdf.getConceptList()) { dereferenceConcept(rdfCopy, concept); } } if (rdf.getPlaceList() != null) { for (PlaceType place : rdf.getPlaceList()) { dereferencePlace(rdfCopy, place); } } for (ProxyType proxy : rdf.getProxyList()) { if (proxy.getEuropeanaProxy() == null || !proxy.getEuropeanaProxy().isEuropeanaProxy()) { if (StringUtils .isNotEmpty(context.getProperties().getProperty(LIBRARYOFCONGRESS))) { if (Boolean .parseBoolean(context.getProperties().getProperty(LIBRARYOFCONGRESS))) { for (Choice choice : proxy.getChoiceList()) { if (choice.ifSubject()) { if (StringUtils.startsWith(choice.getSubject().getString(), "sh") && StringUtils.isNumeric(StringUtils.substringAfter( choice.getSubject().getString(), "sh"))) { Subject sbj = choice.getSubject(); String subject = "http://data.europeana.eu/concept/loc/" + sbj.getString(); ResourceOrLiteralType.Resource rs = new ResourceOrLiteralType.Resource(); rs.setResource(subject); Subject sbjNrm = new Subject(); sbjNrm.setResource(rs); sbjNrm.setLang(new ResourceOrLiteralType.Lang()); sbjNrm.setString(""); choice.setSubject(sbjNrm); } } } } } dereferenceProxy(rdfCopy, proxy); } } if (rdf.getTimeSpanList() != null) { for (TimeSpanType timespan : rdf.getTimeSpanList()) { dereferenceTimespan(rdfCopy, timespan); } } if (rdf.getWebResourceList() != null) { for (WebResourceType webresource : rdf.getWebResourceList()) { dereferenceWebResource(rdfCopy, webresource); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); RDF rdfFinal = cleanRDF(rdfCopy); ProxyType europeanaProxy = new ProxyType(); EuropeanaProxy prx = new EuropeanaProxy(); prx.setEuropeanaProxy(true); europeanaProxy.setEuropeanaProxy(prx); List<String> years = new ArrayList<String>(); for (ProxyType proxy : rdfFinal.getProxyList()) { years.addAll(new EuropeanaDateUtils().createEuropeanaYears(proxy)); europeanaProxy.setType(proxy.getType()); } List<Year> yearList = new ArrayList<Year>(); for (String year : years) { Year yearObj = new Year(); Lang lang = new Lang(); lang.setLang("def"); yearObj.setLang(lang); yearObj.setString(year); yearList.add(yearObj); } europeanaProxy.setYearList(yearList); for (ProxyType proxy : rdfFinal.getProxyList()) { if (proxy != null && proxy.getEuropeanaProxy() != null && proxy.getEuropeanaProxy().isEuropeanaProxy()) { rdfFinal.getProxyList().remove(proxy); } } rdfFinal.getProxyList().add(europeanaProxy); marshallingContext.marshalDocument(rdfFinal, "UTF-8", null, out); String der = out.toString("UTF-8"); mdr.addValue(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD, der); return true; } catch (JiBXException e) { e.printStackTrace(); context.getLoggingEngine().logFailed(Level.SEVERE, this, e, "JiBX unmarshalling has failed with the following error: " + e.getMessage()); } catch (MalformedURLException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (SecurityException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (NoSuchMethodException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (IllegalAccessException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (InvocationTargetException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } catch (InstantiationException e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } log.log(Level.SEVERE, "Error: " + e.getMessage()); e.printStackTrace(); } } } } catch (Exception e) { if (logEngine != null) { logEngine.logFailed(Level.SEVERE, this, e, e.getMessage()); } e.printStackTrace(); } return false; }
From source file:fr.exanpe.t5.lib.components.GMap.java
private String buildGMapApiUrl() { String url = GOOGLE_MAP_API_BASE_URL; // GMap version if (!gmapApiVersion.matches("^3(\\.[0-9]{1})?$")) { throw new RuntimeException(String.format("The GMap API version: %s is not correct.", gmapApiVersion)); }/*from w w w .j av a2 s. c om*/ url += "v=" + gmapApiVersion; // GMap business client ID if (!StringUtils.isEmpty(gmapClientId)) { if (!StringUtils.startsWith(gmapClientId, "gme-")) { throw new RuntimeException(String .format("Your GMap clientID: %s is not correct, it must start with 'gme-'.", gmapClientId)); } url += "&client=" + gmapClientId; } // Sensor parameter url += "&sensor=true"; // Secure access if (secure) { url = url.replace("http", "https"); } log.debug("Google Maps API URL: {}", url); return url; }
From source file:com.adobe.acs.commons.users.impl.EnsureAce.java
/** * Removes all ACEs for the Service User principal (except those that live beneath the System User's rep:User node) * * @param resourceResolver/*from w w w.j a v a 2 s . c o m*/ * the resource resolver to perform the user management * @param jcrAuthorizable * the Jackrabbit Authorizable Object (User or Group) the Authorizable represents * @param authorizable * the Authorizable to remove * @throws RepositoryException */ public void removeAces(ResourceResolver resourceResolver, Authorizable jcrAuthorizable, AbstractAuthorizable authorizable) throws RepositoryException { final Session session = resourceResolver.adaptTo(Session.class); final JackrabbitAccessControlManager accessControlManager = (JackrabbitAccessControlManager) session .getAccessControlManager(); final List<JackrabbitAccessControlList> acls = findAcls(resourceResolver, authorizable.getPrincipalName(), accessControlManager); for (final JackrabbitAccessControlList acl : acls) { final JackrabbitAccessControlEntry[] aces = (JackrabbitAccessControlEntry[]) acl .getAccessControlEntries(); // Check all the existing ACEs in the ACL for (JackrabbitAccessControlEntry ace : aces) { if (StringUtils.equals(authorizable.getPrincipalName(), ace.getPrincipal().getName())) { if (jcrAuthorizable != null && StringUtils.startsWith(acl.getPath(), jcrAuthorizable.getPath())) { // Skip! Don't ensureRemoval ACE's from the system user itself! } else { acl.removeAccessControlEntry(ace); } } } accessControlManager.setPolicy(acl.getPath(), acl); log.debug("Removed ACE from ACL at [ {} ] for [ {} ]", acl.getPath(), authorizable.getPrincipalName()); } }
From source file:io.mycat.server.ServerConnection.java
public void routeEndExecuteSQL(String sql, int type, SchemaConfig schema) { // /*from www. j a v a 2 s .c o m*/ RouteResultset rrs = null; try { rrs = MycatServer.getInstance().getRouterservice().route( MycatServer.getInstance().getConfig().getSystem(), schema, type, sql, this.charset, this); } catch (Exception e) { StringBuilder s = new StringBuilder(); LOGGER.warn(s.append(this).append(sql).toString() + " err:" + e.toString(), e); String msg = e.getMessage(); writeErrMessage(ErrorCode.ER_PARSE_ERROR, msg == null ? e.getClass().getSimpleName() : msg); return; } if (rrs != null) { // session session.execute(rrs, type); String stmt = StringUtils.upperCase(rrs.getStatement()); if (StringUtils.startsWith(stmt, "DROP")) { TableService tableService = new TableServiceImpl(); String tableName = tableService.getTableName(stmt); tableService.deleteTable(tableName, schema.getName()); } } }
From source file:com.edgenius.wiki.ext.textnut.NutParser.java
/** * Remove tags outside body.//from w w w. j av a2s . c o m * Apply HTML CSS into tag style. * Remove default attribute in tag. * * @param htmlContent * @return */ public String convertNutHTMLToPageHTML(String htmlContent) { //Parse whole HTML, and separator out CSS and tags list inside body. HtmlParser htmlParser = new HtmlParser(); HtmlNodeListenerImpl listener = new HtmlNodeListenerImpl(); htmlParser.scan(htmlContent, listener); StringBuffer css = new StringBuffer(); HTMLNodeContainer body = new HTMLNodeContainer(); //First, exact CSS style part, then remove all element outside body tag int require = 0; //1=css;2=body HTMLNode endNode = null; for (HTMLNode node : listener.getHtmlNode()) { if (!node.isTextNode() && "style".equals(node.getTagName()) && !node.isCloseTag()) { endNode = node.getPair(); require = 1; continue; } if (!node.isTextNode() && "body".equals(node.getTagName()) && !node.isCloseTag()) { endNode = node.getPair(); require = 2; continue; } if (endNode != null && require == 1) { if (endNode == node) { endNode = null; } else { if (node.isTextNode()) css.append(node.getText()); } continue; } if (endNode != null && require == 2) { if (endNode == node) { break; } else { body.add(node); } } } // parse and create a stylesheet composition CSSOMParser parser = new CSSOMParser(); //I don't know how to use CSSParser API to quick located style by selector, so blow map will be used for this purpose //its key is selector text, value is style list separated by ";" which is able to use in tag "class" attribute. Map<String, String> selectors = new HashMap<String, String>(); try { CSSStyleSheet stylesheet = parser .parseStyleSheet(new InputSource(new StringReader(css.toString().trim())), null, null); CSSRuleList ruleList = stylesheet.getCssRules(); for (int idx = 0; idx < ruleList.getLength(); idx++) { CSSRule rule = ruleList.item(idx); if (rule instanceof CSSStyleRule) { CSSStyleDeclaration style = ((CSSStyleRule) rule).getStyle(); StringBuffer buf = new StringBuffer(); int len = style.getLength(); for (int idj = 0; idj < len; idj++) { String name = style.item(idj); String value = style.getPropertyCSSValue(name).getCssText(); if ("margin".equals(name) && value.equals("0px 0px 0px 0px")) { continue; } else if ("font".equals(name) && value.equals("18px Helvetica")) { //This value must coordinate with TextNut default font setting. continue; } buf.append(name).append(":").append(value).append(";"); } //buf could be blank, even so, we still need put it into map so that class attribute can locate style by name selectors.put(((CSSStyleRule) rule).getSelectorText(), buf.toString()); } } //debug use: only for display: // for (int idx = 0; idx < ruleList.getLength(); idx++) { // CSSRule rule = ruleList.item(idx); // if (rule instanceof CSSStyleRule){ // CSSStyleRule styleRule=(CSSStyleRule)rule; // CSSStyleDeclaration style = styleRule.getStyle(); // System.out.println(styleRule.getSelectorText()); // for (int idj = 0; idj < style.getLength(); idj++){ // String name = style.item(idj); // System.out.println(name +"=" + style.getPropertyCSSValue(name).getCssText()); // } // } // } //apply CSS to body tags HTMLNode node; for (Iterator<HTMLNode> iter = body.iterator(); iter.hasNext();) { node = iter.next(); if (node.isTextNode()) continue; if (node.getAttributes() != null && !StringUtils.isBlank(node.getAttributes().get("class"))) { //we only support "tagName.styleName" format selector String style = selectors.get(node.getTagName() + "." + node.getAttributes().get("class")); if (style != null) { if (!"".equals(style)) { //could be blank, if style all removed because they are default value. node.setAttribute("style", style); } node.removeAttribute("class"); } } //embedded files object - <object data="file:///index_1.html">index_1.html</object> if ("object".equals(node.getTagName()) && node.getAttributes() != null && StringUtils.startsWith(node.getAttributes().get("data"), "file://")) { } } return body.toString().trim(); } catch (IOException e) { log.error("Parse CSS failed", e); } return htmlContent; }
From source file:com.iyonger.apm.web.configuration.Config.java
/** * Resolve nGrinder home path./*w ww .j a v a2 s .c om*/ * * @return resolved home */ protected Home resolveHome() { if (StringUtils.isNotBlank(System.getProperty("unit-test"))) { final String tempDir = System.getProperty("java.io.tmpdir"); final File tmpHome = new File(tempDir, ".ngrinder"); if (tmpHome.mkdirs()) { LOG.info("{} is created", tmpHome.getPath()); } try { FileUtils.forceDeleteOnExit(tmpHome); } catch (IOException e) { LOG.error("Error while setting forceDeleteOnExit on {}", tmpHome); } return new Home(tmpHome); } String userHomeFromEnv = System.getenv("NGRINDER_HOME"); String userHomeFromProperty = System.getProperty("ngrinder.home"); if (!StringUtils.equals(userHomeFromEnv, userHomeFromProperty)) { CoreLogger.LOGGER.warn("The path to ngrinder-home is ambiguous:"); CoreLogger.LOGGER.warn(" System Environment: NGRINDER_HOME=" + userHomeFromEnv); CoreLogger.LOGGER.warn(" Java System Property: ngrinder.home=" + userHomeFromProperty); CoreLogger.LOGGER.warn(" '" + userHomeFromProperty + "' is accepted."); } String userHome = StringUtils.defaultIfEmpty(userHomeFromProperty, userHomeFromEnv); if (StringUtils.isEmpty(userHome)) { userHome = System.getProperty("user.home") + File.separator + NGRINDER_DEFAULT_FOLDER; } else if (StringUtils.startsWith(userHome, "~" + File.separator)) { userHome = System.getProperty("user.home") + File.separator + userHome.substring(2); } else if (StringUtils.startsWith(userHome, "." + File.separator)) { userHome = System.getProperty("user.dir") + File.separator + userHome.substring(2); } userHome = FilenameUtils.normalize(userHome); File homeDirectory = new File(userHome); CoreLogger.LOGGER.info("nGrinder home directory:{}.", homeDirectory.getPath()); return new Home(homeDirectory); }
From source file:com.cloudbees.plugins.deployer.DeployNowRunAction.java
/** * Hack to help determine if {@link org.kohsuke.stapler.StaplerRequest#getSubmittedForm()} will bomb out * * @param req the request to check.// w w w . j ava 2 s . c o m * @return {@code true} if likely that {@link org.kohsuke.stapler.StaplerRequest#getSubmittedForm()} will return * something. */ private static boolean hasSubmittedForm(StaplerRequest req) { if (StringUtils.startsWith(req.getContentType(), "multipart/")) { FileItem item = null; try { item = req.getFileItem("json"); } catch (ServletException e) { // if we bomb out here, so will req.getSubmittedForm() return false; } catch (IOException e) { // if we bomb out here, so will req.getSubmittedForm() return false; } if (item != null) { return true; } } else { return req.getParameter("json") != null; } return false; }
From source file:com.htmlhifive.tools.codeassist.core.proposal.H5ProposalCreater.java
/** * ????????????./*from ww w . ja v a 2 s .c o m*/ * * @param proposal * @param elem ?? * @return ???????? */ private boolean isOptionFileProposal(IJavaCompletionProposal proposal, VarReferenceBean elem) { return StringUtils.startsWith(proposal.getDisplayString(), elem.getKey()); }