List of usage examples for org.apache.commons.lang3 StringUtils startsWith
public static boolean startsWith(final CharSequence str, final CharSequence prefix)
Check if a CharSequence starts with a specified prefix.
null s are handled without exceptions.
From source file:com.adguard.android.service.FilterServiceImpl.java
/** * Checks the rules of non ascii symbols and control symbols * * @param userRule rule//ww w . jav a 2 s . c o m * * @return true if correct rule or false */ private boolean validateRuleText(String userRule) { return StringUtils.isNotBlank(userRule) && userRule.matches(ASCII_SYMBOL) && StringUtils.length(userRule) > MIN_RULE_LENGTH && !StringUtils.startsWith(userRule, COMMENT) && !StringUtils.startsWith(userRule, ADBLOCK_META_START) && !StringUtils.contains(userRule, MASK_OBSOLETE_SCRIPT_INJECTION) && !StringUtils.contains(userRule, MASK_OBSOLETE_STYLE_INJECTION); }
From source file:com.adobe.acs.commons.wcm.impl.SiteMapServlet.java
private Collection<Resource> getAssetFolders(Page page, ResourceResolver resolver) { List<Resource> allAssetFolders = new ArrayList<Resource>(); ValueMap properties = page.getProperties(); String[] configuredAssetFolderPaths = properties.get(damAssetProperty, String[].class); if (configuredAssetFolderPaths != null) { // Sort to aid in removal of duplicate paths. Arrays.sort(configuredAssetFolderPaths); String prevPath = "#"; for (String configuredAssetFolderPath : configuredAssetFolderPaths) { // Ensure that this folder is not a child folder of another // configured folder, since it will already be included when // the parent folder is traversed. if (StringUtils.isNotBlank(configuredAssetFolderPath) && !configuredAssetFolderPath.equals(prevPath) && !StringUtils.startsWith(configuredAssetFolderPath, prevPath + "/")) { Resource assetFolder = resolver.getResource(configuredAssetFolderPath); if (assetFolder != null) { prevPath = configuredAssetFolderPath; allAssetFolders.add(assetFolder); }//from w w w .java 2s . c o m } } } return allAssetFolders; }
From source file:Heuristics.TermLevelHeuristics.java
public boolean isImmediatelyFollowedByVerbPastTense(String status, String termOrig) { String temp = status.substring(status.indexOf(termOrig)).trim(); boolean pastTense; String[] nextTerms = temp.split(" "); if (nextTerms.length > 1) { temp = nextTerms[1].trim();/*w w w.j av a 2 s .com*/ pastTense = StringUtils.endsWith(temp, "ed"); if (pastTense) { return true; } pastTense = StringUtils.endsWith(temp, "ought") & !StringUtils.startsWith(temp, "ought"); if (pastTense) { return true; } else { return false; } } else { return false; } }
From source file:com.mirth.connect.connectors.smtp.SmtpDispatcher.java
@Override public Response send(ConnectorProperties connectorProperties, ConnectorMessage connectorMessage) { SmtpDispatcherProperties smtpDispatcherProperties = (SmtpDispatcherProperties) connectorProperties; String responseData = null;// ww w. j a v a 2s . c o m String responseError = null; String responseStatusMessage = null; Status responseStatus = Status.QUEUED; String info = "From: " + smtpDispatcherProperties.getFrom() + " To: " + smtpDispatcherProperties.getTo() + " SMTP Info: " + smtpDispatcherProperties.getSmtpHost() + ":" + smtpDispatcherProperties.getSmtpPort(); eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.WRITING, info)); try { Email email = null; if (smtpDispatcherProperties.isHtml()) { email = new HtmlEmail(); } else { email = new MultiPartEmail(); } email.setCharset(charsetEncoding); email.setHostName(smtpDispatcherProperties.getSmtpHost()); try { email.setSmtpPort(Integer.parseInt(smtpDispatcherProperties.getSmtpPort())); } catch (NumberFormatException e) { // Don't set if the value is invalid } try { int timeout = Integer.parseInt(smtpDispatcherProperties.getTimeout()); email.setSocketTimeout(timeout); email.setSocketConnectionTimeout(timeout); } catch (NumberFormatException e) { // Don't set if the value is invalid } // This has to be set before the authenticator because a session shouldn't be created yet configuration.configureEncryption(connectorProperties, email); if (smtpDispatcherProperties.isAuthentication()) { email.setAuthentication(smtpDispatcherProperties.getUsername(), smtpDispatcherProperties.getPassword()); } Properties mailProperties = email.getMailSession().getProperties(); // These have to be set after the authenticator, so that a new mail session isn't created configuration.configureMailProperties(mailProperties); if (smtpDispatcherProperties.isOverrideLocalBinding()) { mailProperties.setProperty("mail.smtp.localaddress", smtpDispatcherProperties.getLocalAddress()); mailProperties.setProperty("mail.smtp.localport", smtpDispatcherProperties.getLocalPort()); } /* * NOTE: There seems to be a bug when calling setTo with a List (throws a * java.lang.ArrayStoreException), so we are using addTo instead. */ for (String to : StringUtils.split(smtpDispatcherProperties.getTo(), ",")) { email.addTo(to); } // Currently unused for (String cc : StringUtils.split(smtpDispatcherProperties.getCc(), ",")) { email.addCc(cc); } // Currently unused for (String bcc : StringUtils.split(smtpDispatcherProperties.getBcc(), ",")) { email.addBcc(bcc); } // Currently unused for (String replyTo : StringUtils.split(smtpDispatcherProperties.getReplyTo(), ",")) { email.addReplyTo(replyTo); } for (Entry<String, String> header : smtpDispatcherProperties.getHeaders().entrySet()) { email.addHeader(header.getKey(), header.getValue()); } email.setFrom(smtpDispatcherProperties.getFrom()); email.setSubject(smtpDispatcherProperties.getSubject()); AttachmentHandlerProvider attachmentHandlerProvider = getAttachmentHandlerProvider(); String body = attachmentHandlerProvider.reAttachMessage(smtpDispatcherProperties.getBody(), connectorMessage); if (StringUtils.isNotEmpty(body)) { if (smtpDispatcherProperties.isHtml()) { ((HtmlEmail) email).setHtmlMsg(body); } else { email.setMsg(body); } } /* * If the MIME type for the attachment is missing, we display a warning and set the * content anyway. If the MIME type is of type "text" or "application/xml", then we add * the content. If it is anything else, we assume it should be Base64 decoded first. */ for (Attachment attachment : smtpDispatcherProperties.getAttachments()) { String name = attachment.getName(); String mimeType = attachment.getMimeType(); String content = attachment.getContent(); byte[] bytes; if (StringUtils.indexOf(mimeType, "/") < 0) { logger.warn("valid MIME type is missing for email attachment: \"" + name + "\", using default of text/plain"); attachment.setMimeType("text/plain"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else if ("application/xml".equalsIgnoreCase(mimeType) || StringUtils.startsWith(mimeType, "text/")) { logger.debug("text or XML MIME type detected for attachment \"" + name + "\""); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, charsetEncoding, false); } else { logger.debug("binary MIME type detected for attachment \"" + name + "\", performing Base64 decoding"); bytes = attachmentHandlerProvider.reAttachMessage(content, connectorMessage, null, true); } ((MultiPartEmail) email).attach(new ByteArrayDataSource(bytes, mimeType), name, null); } /* * From the Commons Email JavaDoc: send returns * "the message id of the underlying MimeMessage". */ responseData = email.send(); responseStatus = Status.SENT; responseStatusMessage = "Email sent successfully."; } catch (Exception e) { eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), connectorMessage.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(), "Error sending email message", e)); responseStatusMessage = ErrorMessageBuilder.buildErrorResponse("Error sending email message", e); responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), "Error sending email message", e); // TODO: Exception handling // connector.handleException(new Exception(e)); } finally { eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getDestinationName(), ConnectionStatusEventType.IDLE)); } return new Response(responseStatus, responseData, responseStatusMessage, responseError); }
From source file:com.databasepreservation.cli.CLI.java
/** * Given the arguments, determines the DatabaseModuleFactory objects that * should be used to create the import and export modules * * @param args//from w ww . j av a2 s . c o m * The command line arguments * @return A pair of DatabaseModuleFactory objects containing the selected * import and export module factories * @throws ParseException * If the arguments could not be parsed or are invalid */ private DatabaseModuleFactoriesPair getModuleFactories(List<String> args) throws ParseException { // check if args contains exactly one import and one export module String importModuleName = null; String exportModuleName = null; int importModulesFound = 0; int exportModulesFound = 0; Iterator<String> argsIterator = args.iterator(); try { while (argsIterator.hasNext()) { String arg = argsIterator.next(); if ("-i".equals(arg) || "--import".equals(arg)) { importModuleName = argsIterator.next(); importModulesFound++; } else if ("-e".equals(arg) || "--export".equals(arg)) { exportModuleName = argsIterator.next(); exportModulesFound++; } else if (StringUtils.startsWith(arg, "--import=")) { // 9 is the size of the string "--import=" importModuleName = arg.substring(9); importModulesFound++; } else if (StringUtils.startsWith(arg, "--export=")) { // 9 is the size of the string "--export=" exportModuleName = arg.substring(9); exportModulesFound++; } } } catch (NoSuchElementException e) { LOGGER.debug("NoSuchElementException", e); throw new ParseException("Missing module name."); } if (importModulesFound != 1 || exportModulesFound != 1) { throw new ParseException("Exactly one import module and one export module must be specified."); } // check if both module names correspond to real module names DatabaseModuleFactory importModuleFactory = null; DatabaseModuleFactory exportModuleFactory = null; for (DatabaseModuleFactory factory : factories) { String moduleName = factory.getModuleName(); if (moduleName.equalsIgnoreCase(importModuleName) && factory.producesImportModules()) { importModuleFactory = factory; } if (moduleName.equalsIgnoreCase(exportModuleName) && factory.producesExportModules()) { exportModuleFactory = factory; } } if (importModuleFactory == null) { throw new ParseException("Invalid import module."); } else if (exportModuleFactory == null) { throw new ParseException("Invalid export module."); } return new DatabaseModuleFactoriesPair(importModuleFactory, exportModuleFactory); }
From source file:de.micromata.genome.util.runtime.jndi.SimpleNamingContext.java
@Override public Object lookup(String lookupName) throws NameNotFoundException { try {//w w w .java 2 s . c om return lookupImpl(lookupName); } catch (NameNotFoundException ex) { String prefix = "java:comp/env/"; if (StringUtils.startsWith(lookupName, prefix) == false) { return lookupImpl(prefix + lookupName); } throw ex; } }
From source file:com.sonicle.webtop.vfs.Service.java
private String storeIcon(Store store) { String uri = store.getUri();//from ww w. j a va 2s . c o m if (store.getBuiltIn()) { return "storeMyDocs"; } else { if (StringUtils.startsWith(uri, "dropbox")) { return "storeDropbox"; } else if (StringUtils.startsWith(uri, "file")) { return "storeFile"; } else if (StringUtils.startsWith(uri, "ftp")) { return "storeFtp"; } else if (StringUtils.startsWith(uri, "ftps")) { return "storeFtp"; } else if (StringUtils.startsWith(uri, "googledrive")) { return "storeGooDrive"; } else if (StringUtils.startsWith(uri, "sftp")) { return "storeFtp"; } else if (StringUtils.startsWith(uri, "webdav")) { return "storeWebdav"; } else if (StringUtils.startsWith(uri, "smb")) { return "storeSmb"; } else { return "store-xs"; } } }
From source file:cgeo.geocaching.CacheDetailActivity.java
@Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.cachedetail_activity); // get parameters final Bundle extras = getIntent().getExtras(); final Uri uri = AndroidBeam.getUri(getIntent()); // try to get data from extras String name = null;//from w w w . j a va 2 s .c om String guid = null; if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); name = extras.getString(Intents.EXTRA_NAME); guid = extras.getString(Intents.EXTRA_GUID); } // When clicking a cache in MapsWithMe, we get back a PendingIntent if (StringUtils.isEmpty(geocode)) { geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent()); } if (geocode == null && uri != null) { geocode = ConnectorFactory.getGeocodeFromURL(uri.toString()); } // try to get data from URI if (geocode == null && guid == null && uri != null) { final String uriHost = uri.getHost().toLowerCase(Locale.US); final String uriPath = uri.getPath().toLowerCase(Locale.US); final String uriQuery = uri.getQuery(); if (uriQuery != null) { Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery); } else { Log.i("Opening URI: " + uriHost + uriPath); } if (uriHost.contains("geocaching.com")) { if (StringUtils.startsWith(uriPath, "/geocache/gc")) { geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US); } else { geocode = uri.getQueryParameter("wp"); guid = uri.getQueryParameter("guid"); if (StringUtils.isNotBlank(geocode)) { geocode = geocode.toUpperCase(Locale.US); guid = null; } else if (StringUtils.isNotBlank(guid)) { geocode = null; guid = guid.toLowerCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); return; } } } } // no given data if (geocode == null && guid == null) { showToast(res.getString(R.string.err_detail_cache)); finish(); return; } // If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details setCacheTitleBar(geocode, name, null); final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress); try { String title = res.getString(R.string.cache); if (StringUtils.isNotBlank(name)) { title = name; } else if (geocode != null && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank() title = geocode; } progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.disposeMessage()); } catch (final RuntimeException ignored) { // nothing, we lost the window } final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0) : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1; createViewPager(pageToOpen, new OnPageSelectedListener() { @Override public void onPageSelected(final int position) { if (Settings.isOpenLastDetailsPage()) { Settings.setLastDetailsPage(position); } // lazy loading of cache images if (getPage(position) == Page.IMAGES) { loadCacheImages(); } requireGeodata = getPage(position) == Page.DETAILS; startOrStopGeoDataListener(false); // dispose contextual actions on page change if (currentActionMode != null) { currentActionMode.finish(); } } }); requireGeodata = pageToOpen == 1; final String realGeocode = geocode; final String realGuid = guid; AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() { @Override public void run() { search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null, false, loadCacheHandler); loadCacheHandler.sendMessage(Message.obtain()); } }); // Load Generic Trackables if (StringUtils.isNotBlank(geocode)) { AndroidRxUtils.bindActivity(this, // Obtain the active connectors and load trackables in parallel. Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors()) .flatMap(new Function<TrackableConnector, Observable<Trackable>>() { @Override public Observable<Trackable> apply(final TrackableConnector trackableConnector) { processedBrands.add(trackableConnector.getBrand()); return Observable.defer(new Callable<Observable<Trackable>>() { @Override public Observable<Trackable> call() { return Observable .fromIterable(trackableConnector.searchTrackables(geocode)); } }).subscribeOn(AndroidRxUtils.networkScheduler); } }).toList()) .subscribe(new Consumer<List<Trackable>>() { @Override public void accept(final List<Trackable> trackables) { // Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors. // Store trackables. genericTrackables.addAll(trackables); if (!trackables.isEmpty()) { // Update the UI if any trackables were found. notifyDataSetChanged(); } } }); } locationUpdater = new CacheDetailsGeoDirHandler(this); // If we have a newer Android device setup Android Beam for easy cache sharing AndroidBeam.enable(this, this); }
From source file:eionet.webq.web.controller.WebQProxyDelegation.java
/** * The method proxies multipart POST requests. If the request target is CDR envelope, then USerFile authorization info is used. * * @param uri the address to forward the request * @param fileId UserFile id stored in session * @param multipartRequest file part in multipart request * @return response from remote host// w ww . ja v a 2s . com * @throws URISyntaxException provide URI is incorrect * @throws IOException could not read file from request */ @RequestMapping(value = "/restProxyFileUpload", method = RequestMethod.POST, produces = "text/html;charset=utf-8") @ResponseBody public String restProxyFileUpload(@RequestParam("uri") String uri, @RequestParam int fileId, MultipartHttpServletRequest multipartRequest) throws URISyntaxException, IOException { UserFile file = userFileHelper.getUserFile(fileId, multipartRequest); if (!multipartRequest.getFileNames().hasNext()) { throw new IllegalArgumentException("File not found in multipart request."); } Map<String, String[]> parameters = multipartRequest.getParameterMap(); // limit request to one file String fileName = multipartRequest.getFileNames().next(); MultipartFile multipartFile = multipartRequest.getFile(fileName); HttpHeaders authorization = new HttpHeaders(); if (file != null && StringUtils.startsWith(uri, file.getEnvelope())) { authorization = envelopeService.getAuthorizationHeader(file); } HttpHeaders fileHeaders = new HttpHeaders(); fileHeaders.setContentDispositionFormData("file", multipartFile.getOriginalFilename()); fileHeaders.setContentType(MediaType.valueOf(multipartFile.getContentType())); MultiValueMap<String, Object> request = new LinkedMultiValueMap<String, Object>(); byte[] content = multipartFile.getBytes(); request.add("file", new HttpEntity<byte[]>(content, fileHeaders)); for (Map.Entry<String, String[]> parameter : parameters.entrySet()) { if (!parameter.getKey().equals("uri") && !parameter.getKey().equals("fileId") && !parameter.getKey().equals("sessionid") && !parameter.getKey().equals("restricted")) { request.add(parameter.getKey(), new HttpEntity<String>(StringUtils.defaultString(parameter.getValue()[0]))); } } HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>( request, authorization); LOGGER.info("/restProxyFileUpload [POST] uri=" + uri); return restTemplate.postForObject(uri, requestEntity, String.class); }
From source file:com.adguard.filter.rules.UrlFilterRule.java
/** * Loads rule properties lazily//from ww w.j a v a 2 s . c o m */ private synchronized void loadRuleProperties() { try { if (regex != null || urlRegexp != null || invalidRule) { // Rule is already loaded return; } String urlRuleText = getRuleText(); if (StringUtils.startsWith(urlRuleText, MASK_WHITE_LIST)) { urlRuleText = urlRuleText.substring(MASK_WHITE_LIST.length()); } int optionsIndex = StringUtils.lastIndexOf(urlRuleText, OPTIONS_DELIMITER); if (optionsIndex > -1) { // Options are specified, parsing it String optionsBase = urlRuleText; urlRuleText = urlRuleText.substring(0, optionsIndex); String options = optionsBase.substring(optionsIndex + 1); loadOptions(options); } // Transform to punycode urlRuleText = toPunycode(urlRuleText); boolean regexRule = urlRuleText.startsWith(MASK_REGEX_RULE) && urlRuleText.endsWith(MASK_REGEX_RULE); if (regexRule) { regex = urlRuleText.substring(MASK_REGEX_RULE.length(), urlRuleText.length() - MASK_REGEX_RULE.length()); // Pre-compile regex rules Pattern pattern = getUrlRegexp(); if (pattern == null) { throw new IllegalArgumentException("ruleText"); } } else { regex = createRegexFromRule(urlRuleText); } } catch (Exception ex) { LoggerFactory.getLogger(this.getClass()).warn("Invalid filter rule: {}\r\n", getRuleText(), ex); invalidRule = true; } }