List of usage examples for org.apache.commons.lang3 StringUtils startsWithIgnoreCase
public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix)
Case insensitive check if a CharSequence starts with a specified prefix.
null s are handled without exceptions.
From source file:com.erudika.para.core.User.java
/** * Is the main identifier a Twitter id/*from w ww . ja v a 2s . c o m*/ * @return true if user is signed in with Twitter */ @JsonIgnore public boolean isTwitterUser() { return StringUtils.startsWithIgnoreCase(identifier, Config.TWITTER_PREFIX); }
From source file:com.marand.thinkmed.medications.business.MedicationsFinderImpl.java
private List<TreeNodeData> filterMedicationsTree(final List<TreeNodeData> medications, final String[] searchSubstrings, final boolean startMustMatch) { final List<TreeNodeData> filteredMedications = new ArrayList<>(); for (final TreeNodeData medicationNode : medications) { final MedicationSimpleDto medicationSimpleDto = (MedicationSimpleDto) medicationNode.getData(); final String medicationSearchName = medicationSimpleDto.getGenericName() != null ? medicationSimpleDto.getGenericName() + " " + medicationNode.getTitle() : medicationNode.getTitle(); medicationNode.setExpanded(false); boolean match = true; if (startMustMatch && searchSubstrings.length > 0) { final String firstSearchString = searchSubstrings[0]; final boolean genericStartsWithFirstSearchString = medicationSimpleDto.getGenericName() != null && StringUtils.startsWithIgnoreCase(medicationSimpleDto.getGenericName(), firstSearchString); final boolean medicationStartsWithFirstSearchString = StringUtils .startsWithIgnoreCase(medicationNode.getTitle(), firstSearchString); if (!genericStartsWithFirstSearchString && !medicationStartsWithFirstSearchString) { match = false;//from w w w . j a v a2s . c o m } } if (match) { for (int i = startMustMatch ? 1 : 0; i < searchSubstrings.length; i++) { if (!StringUtils.containsIgnoreCase(medicationSearchName, searchSubstrings[i])) { match = false; break; } } } if (match) { filteredMedications.add(medicationNode); } else { if (!medicationNode.getChildren().isEmpty()) { final List<TreeNodeData> filteredChildren = filterMedicationsTree(medicationNode.getChildren(), searchSubstrings, startMustMatch); if (!filteredChildren.isEmpty()) { medicationNode.setChildren(filteredChildren); filteredMedications.add(medicationNode); medicationNode.setExpanded(true); } } } } return filteredMedications; }
From source file:com.erudika.para.core.User.java
/** * Is the main identifier a GitHub id//from w w w . j a v a 2 s . com * @return true if user is signed in with GitHub */ @JsonIgnore public boolean isGitHubUser() { return StringUtils.startsWithIgnoreCase(identifier, Config.GITHUB_PREFIX); }
From source file:com.erudika.para.rest.Signer.java
/** * Builds, signs and executes a request to an API endpoint using the provided credentials. * Signs the request using the Amazon Signature 4 algorithm and returns the response. * @param apiClient Jersey Client object * @param accessKey access key// w w w. j a va2s. co m * @param secretKey secret key * @param httpMethod the method (GET, POST...) * @param endpointURL protocol://host:port * @param reqPath the API resource path relative to the endpointURL * @param headers headers map * @param params parameters map * @param jsonEntity an object serialized to JSON byte array (payload), could be null * @return a response object */ public Response invokeSignedRequest(Client apiClient, String accessKey, String secretKey, String httpMethod, String endpointURL, String reqPath, Map<String, String> headers, MultivaluedMap<String, String> params, byte[] jsonEntity) { boolean isJWT = StringUtils.startsWithIgnoreCase(secretKey, "Bearer"); WebTarget target = apiClient.target(endpointURL).path(reqPath); Map<String, String> signedHeaders = null; if (!isJWT) { signedHeaders = signRequest(accessKey, secretKey, httpMethod, endpointURL, reqPath, headers, params, jsonEntity); } if (params != null) { for (Map.Entry<String, List<String>> param : params.entrySet()) { String key = param.getKey(); List<String> value = param.getValue(); if (value != null && !value.isEmpty() && value.get(0) != null) { target = target.queryParam(key, value.toArray()); } } } Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON); if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { builder.header(header.getKey(), header.getValue()); } } Entity<?> jsonPayload = null; if (jsonEntity != null && jsonEntity.length > 0) { try { jsonPayload = Entity.json(new String(jsonEntity, Config.DEFAULT_ENCODING)); } catch (IOException ex) { logger.error(null, ex); } } if (isJWT) { builder.header(HttpHeaders.AUTHORIZATION, secretKey); } else { builder.header(HttpHeaders.AUTHORIZATION, signedHeaders.get(HttpHeaders.AUTHORIZATION)) .header("X-Amz-Date", signedHeaders.get("X-Amz-Date")); } if (jsonPayload != null) { return builder.method(httpMethod, jsonPayload); } else { return builder.method(httpMethod); } }
From source file:com.nike.cerberus.auth.connector.onelogin.OneLoginAuthConnector.java
/** * Request for creating a session login token. This is used to validate a user's credentials with OneLogin. * * @param username OneLogin username// www. j av a2 s . c o m * @param password OneLogin password * @return Session login token */ protected SessionLoginTokenData createSessionLoginToken(final String username, final String password) { CreateSessionLoginTokenRequest request = new CreateSessionLoginTokenRequest().setUsernameOrEmail(username) .setPassword(password).setSubdomain(subdomain); final Response response = execute(buildUrl("api/1/login/auth"), "POST", buildAuthorizationBearerHeader(), request); final CreateSessionLoginTokenResponse createSessionLoginTokenResponse = parseResponseBody(response, CreateSessionLoginTokenResponse.class); if (createSessionLoginTokenResponse.getStatus().isError()) { String msg = String.format("The user %s failed to authenticate for reason: %s", username, createSessionLoginTokenResponse.getStatus().getMessage()); if (createSessionLoginTokenResponse.getStatus().getCode() == 400L) { if (StringUtils.startsWithIgnoreCase(createSessionLoginTokenResponse.getStatus().getMessage(), "MFA")) { throw ApiException.newBuilder().withApiErrors(DefaultApiError.MFA_SETUP_REQUIRED) .withExceptionMessage(msg).build(); } else { throw ApiException.newBuilder().withApiErrors(DefaultApiError.AUTH_BAD_CREDENTIALS) .withExceptionMessage(msg).build(); } } else { throw ApiException.newBuilder().withApiErrors(DefaultApiError.GENERIC_BAD_REQUEST) .withExceptionMessage(msg).build(); } } return createSessionLoginTokenResponse.getData().get(0); }
From source file:com.nridge.core.base.io.xml.DocumentOpXML.java
private void loadOperation(Element anElement) throws IOException { Attr nodeAttr;/* ww w. j a va2 s. com*/ Node nodeItem; Document document; Element nodeElement; DocumentXML documentXML; DSCriteriaXML criteriaXML; String nodeName, nodeValue; mCriteria = null; mDocumentList.clear(); mField.clearFeatures(); String attrValue = anElement.getAttribute(Doc.FEATURE_OP_NAME); if (StringUtils.isNotEmpty(attrValue)) { mField.setName(attrValue); NamedNodeMap namedNodeMap = anElement.getAttributes(); int attrCount = namedNodeMap.getLength(); for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) { nodeAttr = (Attr) namedNodeMap.item(attrOffset); nodeName = nodeAttr.getNodeName(); nodeValue = nodeAttr.getNodeValue(); if (StringUtils.isNotEmpty(nodeValue)) { if ((!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_NAME)) && (!StringUtils.equalsIgnoreCase(nodeName, Doc.FEATURE_OP_COUNT))) mField.addFeature(nodeName, nodeValue); } } } NodeList nodeList = anElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { nodeItem = nodeList.item(i); if (nodeItem.getNodeType() != Node.ELEMENT_NODE) continue; nodeName = nodeItem.getNodeName(); if (nodeName.equalsIgnoreCase(IO.XML_CRITERIA_NODE_NAME)) { nodeElement = (Element) nodeItem; criteriaXML = new DSCriteriaXML(); criteriaXML.load(nodeElement); mCriteria = criteriaXML.getCriteria(); } else if (StringUtils.startsWithIgnoreCase(nodeName, IO.XML_DOCUMENT_NODE_NAME)) { nodeElement = (Element) nodeItem; documentXML = new DocumentXML(); documentXML.load(nodeElement); document = documentXML.getDocument(); if (document != null) mDocumentList.add(document); } } }
From source file:com.blackducksoftware.integration.hub.jenkins.gradle.GradleBuildWrapper.java
@Override public Environment setUp(final AbstractBuild build, final Launcher launcher, final BuildListener listener) throws IOException, InterruptedException { // no failure to report yet final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener); buildLogger.setLogLevel(LogLevel.TRACE); Gradle gradleBuilder = null;/*from www .j a va2s. c o m*/ if (build.getProject() instanceof FreeStyleProject) { // Project should always be a FreeStyleProject, thats why we have the isApplicable() method final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders(); if (builders == null || builders.isEmpty()) { // User didn't configure the job with a Builder buildLogger.error("No Builder found for this job."); buildLogger.error("Will not run the Hub Gradle Build wrapper."); build.setResult(Result.UNSTABLE); return new Environment() { }; // Continue with the rest of the Build } for (final Builder builder : builders) { if (builder instanceof Gradle) { gradleBuilder = (Gradle) builder; } } if (gradleBuilder == null) { // User didn't configure the job with a Gradle Builder buildLogger.error("This Wrapper should be run with a Gradle Builder"); buildLogger.error("Will not run the Hub Gradle Build wrapper."); build.setResult(Result.UNSTABLE); return new Environment() { }; // Continue with the rest of the Build } } else { buildLogger.error("Cannot run the Hub Gradle Build Wrapper for this type of Project."); build.setResult(Result.UNSTABLE); return new Environment() { }; // Continue with the rest of the Build } if (validateConfiguration(buildLogger)) { buildLogger.info("Build Recorder enabled"); buildLogger.info("Hub Jenkins Plugin version : " + getDescriptor().getPluginVersion()); } else { build.setResult(Result.UNSTABLE); return new Environment() { }; // Continue with the rest of the Build } final ThreadLocal<String> originalSwitches = new ThreadLocal<String>(); final ThreadLocal<String> originalTasks = new ThreadLocal<String>(); if (gradleBuilder != null) { originalSwitches.set(gradleBuilder.getSwitches() + ""); originalTasks.set(gradleBuilder.getTasks() + ""); final BDGradleInitScriptWriter writer = new BDGradleInitScriptWriter(build, buildLogger); final FilePath workspace = build.getWorkspace(); FilePath initScript; String initScriptPath; try { if (workspace == null) { buildLogger.error("Workspace: null"); } else { initScript = workspace.createTextTempFile("init-blackduck", "gradle", writer.generateInitScript(), false); if (initScript != null) { initScriptPath = initScript.getRemote(); initScriptPath = initScriptPath.replace('\\', '/'); String newSwitches = originalSwitches.get(); String newTasks = originalTasks.get(); if (!originalSwitches.get().contains("--init-script ") && !originalSwitches.get().contains("init-blackduck")) { newSwitches = newSwitches + " --init-script " + initScriptPath; } if (!originalSwitches.get().contains(" -D" + BDGradleUtil.BUILD_ID_PROPERTY)) { newSwitches = newSwitches + " -D" + BDGradleUtil.BUILD_ID_PROPERTY + "=" + build.getId(); } if (!originalSwitches.get() .contains(" -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY)) { String configurations = getUserScopesToInclude(); configurations = configurations.replaceAll(" ", ""); newSwitches = newSwitches + " -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY + "=" + configurations; } // // Following used to generate the dependency tree // // written to a file // if (!originalSwitches.get().contains(" -D" + // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT)) { // FilePath dependencyTreeFile = new FilePath(workspace, "dependencyTree.txt"); // newSwitches = newSwitches + " -D" + // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT + "='" + // dependencyTreeFile.getRemote() + "'"; // } if (!originalTasks.get().contains("bdCustomTask")) { newTasks = newTasks + " bdCustomTask"; } if (!originalTasks.get().contains("bdDependencyTree")) { newTasks = newTasks + " bdDependencyTree"; } setField(gradleBuilder, "switches", newSwitches); setField(gradleBuilder, "tasks", newTasks); } } } catch (final Exception e) { listener.getLogger().println("Error occurred while writing Gradle Init Script: " + e.getMessage()); build.setResult(Result.FAILURE); } } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); boolean changed = false; try { if (GradleBuildWrapper.class.getClassLoader() != originalClassLoader) { changed = true; Thread.currentThread().setContextClassLoader(GradleBuildWrapper.class.getClassLoader()); } return new Environment() { @Override public boolean tearDown(final AbstractBuild build, final BuildListener listener) throws IOException, InterruptedException { final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener); Gradle gradleBuilder = null; try { if (build.getProject() instanceof FreeStyleProject) { // Project should always be a FreeStyleProject, thats why we have the isApplicable() method final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders(); for (final Builder builder : builders) { if (builder instanceof Gradle) { gradleBuilder = (Gradle) builder; } } } if (gradleBuilder != null) { String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir(); if (StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "${WORKSPACE}") || StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "$WORKSPACE")) { final EnvVars variables = build.getEnvironment(listener); rootBuildScriptDir = BuildHelper.handleVariableReplacement(variables, rootBuildScriptDir); } String fileSeparator = null; try { final VirtualChannel channel = build.getBuiltOn().getChannel(); if (channel == null) { buildLogger.error("Channel build on: null"); } else { fileSeparator = channel.call(new GetSeparator()); } } catch (final IOException e) { buildLogger.error(e.toString(), e); } catch (final InterruptedException e) { buildLogger.error(e.toString(), e); } if (StringUtils.isEmpty(fileSeparator)) { fileSeparator = File.separator; } File workspaceFile = null; if (build.getWorkspace() == null) { // might be using custom workspace workspaceFile = new File(build.getProject().getCustomWorkspace()); } else { workspaceFile = new File(build.getWorkspace().getRemote()); } String workingDirectory = ""; try { workingDirectory = build.getBuiltOn().getChannel() .call(new GetCanonicalPath(workspaceFile)); } catch (final IOException e) { buildLogger.error("Problem getting the working directory on this node. Error : " + e.getMessage(), e); } if (!StringUtils.startsWithIgnoreCase(rootBuildScriptDir, workingDirectory)) { if (workingDirectory.endsWith(fileSeparator)) { rootBuildScriptDir = workingDirectory + rootBuildScriptDir; } else { rootBuildScriptDir = workingDirectory + fileSeparator + rootBuildScriptDir; } } FilePath buildInfo = null; final Node buildOn = build.getBuiltOn(); if (buildOn == null) { buildLogger.error("Node build on: null"); } else { final VirtualChannel channel = buildOn.getChannel(); if (channel == null) { buildLogger.error("Channel build on: null"); } else { // buildInfoFile = new FilePath(channel, workspacePath); buildInfo = new FilePath(channel, rootBuildScriptDir); buildInfo = new FilePath(buildInfo, "build"); buildInfo = new FilePath(buildInfo, "BlackDuck"); buildInfo = new FilePath(buildInfo, BuildInfo.OUTPUT_FILE_NAME); } } if (buildInfo != null) { if (buildInfo.exists()) { return universalTearDown(build, buildLogger, buildInfo, getDescriptor(), BuilderType.GRADLE); } else { buildLogger.error( "The " + BuildInfo.OUTPUT_FILE_NAME + " file does not exist at : " + buildInfo.getRemote() + ", on machine : " + (buildOn == null ? "null" : buildOn.getDisplayName())); build.setResult(Result.UNSTABLE); return true; } } // } } else { buildLogger.error("[WARNING] no gradle build step found"); build.setResult(Result.UNSTABLE); return true; } } catch (final BDJenkinsHubPluginException e) { buildLogger.error(e.getMessage(), e); build.setResult(Result.UNSTABLE); return true; } catch (final Exception e) { buildLogger.error(e.getMessage(), e); build.setResult(Result.UNSTABLE); return true; } finally { if (gradleBuilder != null) { synchronized (this) { try { // restore the original configuration setField(gradleBuilder, "switches", originalSwitches.get()); setField(gradleBuilder, "tasks", originalTasks.get()); } catch (final Exception e) { buildLogger.error(e.getMessage(), e); build.setResult(Result.UNSTABLE); return true; } } } } return true; } }; } finally { if (changed) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } }
From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java
/** * For every header that contains the command 'Set-Cookie' it will call the method {@link #createAndAddCookiesOnStoreForHeader(CookieStore, Header)} *//*from w ww . j a va2 s . c o m*/ protected void createAndAddCookiesOnStoreForHeaders(CookieStore cookieStore, Header[] allHeaders) { for (Header header : allHeaders) { if (StringUtils.startsWithIgnoreCase(header.getName(), "Set-Cookie")) { createAndAddCookiesOnStoreForHeader(cookieStore, header); } } }
From source file:com.moviejukebox.plugin.ImdbPlugin.java
/** * Scan IMDB HTML page for the specified movie *//*from w w w . ja va2 s . c o m*/ private boolean updateImdbMediaInfo(Movie movie) { String imdbID = movie.getId(IMDB_PLUGIN_ID); if (!imdbID.startsWith("tt")) { imdbID = "tt" + imdbID; // Correct the ID if it's wrong movie.setId(IMDB_PLUGIN_ID, imdbID); } String xml = ImdbPlugin.this.getImdbUrl(movie); // Add the combined tag to the end of the request if required if (fullInfo) { xml += "combined"; } xml = getImdbData(xml); if (!Movie.TYPE_TVSHOW.equals(movie.getMovieType()) && (xml.contains("\"tv-extra\"") || xml.contains("\"tv-series-series\""))) { movie.setMovieType(Movie.TYPE_TVSHOW); return Boolean.FALSE; } // We can work out if this is the new site by looking for " - IMDb" at the end of the title String title = HTMLTools.extractTag(xml, "<title>"); if (!Movie.TYPE_TVSHOW.equals(movie.getMovieType()) && title.contains("(TV Series")) { movie.setMovieType(Movie.TYPE_TVSHOW); return Boolean.FALSE; } // Correct the title if "imdb" found if (StringUtils.endsWithIgnoreCase(title, " - imdb")) { title = title.substring(0, title.length() - 7); } else if (StringUtils.startsWithIgnoreCase(title, "imdb - ")) { title = title.substring(7); } // Remove the (VG) or (V) tags from the title title = title.replaceAll(" \\([VG|V]\\)$", ""); //String yearPattern = "(?i).\\((?:TV.|VIDEO.)?(\\d{4})(?:/[^\\)]+)?\\)"; String yearPattern = "(?i).\\((?:TV.|VIDEO.)?(\\d{4})"; Pattern pattern = Pattern.compile(yearPattern, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(title); if (matcher.find()) { // If we've found a year, set it in the movie if (OverrideTools.checkOverwriteYear(movie, IMDB_PLUGIN_ID)) { movie.setYear(matcher.group(1), IMDB_PLUGIN_ID); } // Remove the year from the title title = title.substring(0, title.indexOf(matcher.group(0))); } if (OverrideTools.checkOverwriteTitle(movie, IMDB_PLUGIN_ID)) { movie.setTitle(title, IMDB_PLUGIN_ID); } if (OverrideTools.checkOverwriteOriginalTitle(movie, IMDB_PLUGIN_ID)) { String originalTitle = title; if (xml.contains("<span class=\"title-extra\">")) { originalTitle = HTMLTools.extractTag(xml, "<span class=\"title-extra\">", "</span>"); if (originalTitle.contains("(original title)")) { originalTitle = originalTitle.replace(" <i>(original title)</i>", ""); } else { originalTitle = title; } } movie.setOriginalTitle(originalTitle, IMDB_PLUGIN_ID); } // Update the movie information updateInfo(movie, xml); // update common values updateInfoCommon(movie, xml); if (scrapeAwards) { updateAwards(movie); // Issue 1901: Awards } if (scrapeBusiness) { updateBusiness(movie); // Issue 2012: Financial information about movie } if (scrapeTrivia) { updateTrivia(movie); // Issue 2013: Add trivia } // TODO: Move this check out of here, it doesn't belong. if (downloadFanart && isNotValidString(movie.getFanartURL())) { movie.setFanartURL(getFanartURL(movie)); if (isValidString(movie.getFanartURL())) { movie.setFanartFilename(movie.getBaseName() + fanartToken + "." + fanartExtension); } } // always true return Boolean.TRUE; }
From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLFormElement.java
/** * Submits the form (at the end of the current script execution). *///from w ww .j a v a2s. c o m @JsxFunction public void submit() { final HtmlPage page = (HtmlPage) getDomNodeOrDie().getPage(); final WebClient webClient = page.getWebClient(); final String action = getHtmlForm().getActionAttribute().trim(); if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) { final String js = action.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length()); webClient.getJavaScriptEngine().execute(page, js, "Form action", 0); } else { // download should be done ASAP, response will be loaded into a window later final WebRequest request = getHtmlForm().getWebRequest(null); final String target = page.getResolvedTarget(getTarget()); final boolean forceDownload = webClient.getBrowserVersion().hasFeature(JS_FORM_SUBMIT_FORCES_DOWNLOAD); final boolean checkHash = !webClient.getBrowserVersion() .hasFeature(FORM_SUBMISSION_DOWNLOWDS_ALSO_IF_ONLY_HASH_CHANGED); webClient.download(page.getEnclosingWindow(), target, request, checkHash, forceDownload, "JS form.submit()"); } }