List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:edu.umich.ctools.sectionsUtilityTool.SectionsUtilityToolServlet.java
public void doError(HttpServletRequest request, HttpServletResponse response, String s) throws java.io.IOException { StringBuilder return_url = new StringBuilder(); if (return_url != null && return_url.length() > 1) { return_url.append((return_url.indexOf("?") > 1) ? "&" : "?"); return_url.append("lti_msg=").append(URLEncoder.encode(s, "UTF-8")); response.sendRedirect(return_url.toString()); return;/* ww w . j a v a 2s. c o m*/ } PrintWriter out = response.getWriter(); out.println(s); }
From source file:org.owasp.dependencycheck.analyzer.CPEAnalyzer.java
/** * <p>/*from w ww .j av a2s.c o m*/ * Returns the text created by concatenating the text and the values from * the EvidenceCollection (filtered for a specific confidence). This * attempts to prevent duplicate terms from being added.</p> * <p> * Note, if the evidence is longer then 200 characters it will be * truncated.</p> * * @param text the base text * @param evidence an iterable set of evidence to concatenate * @return the new evidence text */ @SuppressWarnings("null") protected String addEvidenceWithoutDuplicateTerms(final String text, final Iterable<Evidence> evidence) { final String txt = (text == null) ? "" : text; final StringBuilder sb = new StringBuilder(txt.length() * 2); sb.append(' ').append(txt).append(' '); for (Evidence e : evidence) { String value = e.getValue(); if (value.length() > 1000) { value = value.substring(0, 1000); final int pos = value.lastIndexOf(" "); if (pos > 0) { value = value.substring(0, pos); } } if (sb.indexOf(" " + value + " ") < 0) { sb.append(value).append(' '); } } return sb.toString().trim(); }
From source file:org.colombbus.tangara.Configuration.java
private void addClassPathToScriptEngine(File jarFile) throws ConfigurationException { try {/*w w w . j av a 2 s . co m*/ StringBuilder cmd = new StringBuilder(addClassPathCmd); int tagStartPos = cmd.indexOf(parameterTag); int tageEndPos = tagStartPos + parameterTag.length(); cmd.replace(tagStartPos, tageEndPos, jarFile.getAbsolutePath().replace("\\", "/")); // System.out.println("cmd " + cmd.toString()); engine.eval("add-classpath", 1, 1, cmd.toString()); //$NON-NLS-1$ } catch (Exception ex) { String msg = String.format("Failed to load class path %s", jarFile.getName()); //$NON-NLS-1$ System.err.println(msg + " " + ex); throw new ConfigurationException(msg, ex); } }
From source file:org.colombbus.tangara.Configuration.java
/** * Imports a package into the script engine * * @param pkgName/*w ww. j a v a2 s .c om*/ * the name of the package * @throws ConfigurationException * if the package cannot be imported */ private void importPkgToScriptEngine(String pkgName) throws ConfigurationException { try { StringBuilder cmd = new StringBuilder(importPackageCmd); int tagStartPos = cmd.indexOf(parameterTag); int tageEndPos = tagStartPos + parameterTag.length(); cmd.replace(tagStartPos, tageEndPos, pkgName); // System.out.println("cmd " + cmd.toString()); engine.eval("load-packages", 1, 1, cmd.toString()); //$NON-NLS-1$ } catch (Exception ex) { String msg = String.format("Failed to import package %s", pkgName); //$NON-NLS-1$ System.err.println(msg + " " + ex); throw new ConfigurationException(msg, ex); } }
From source file:org.smslib.CSerialDriver.java
public String getResponse() throws IOException { final int MAX_RETRIES = 3; int retry = 0; final StringBuilder buffer = new StringBuilder(BUFFER_SIZE); while (retry < MAX_RETRIES) { try {/* w ww .j a v a2s. c om*/ readResponseToBuffer(buffer); retry = MAX_RETRIES; } catch (ServiceDisconnectedException e) { return "+ERROR:\r\n"; } catch (IOException e) { if (++retry <= MAX_RETRIES) { if (log != null) log.info("IOException reading from serial port. Will retry.", e); try { Thread.sleep(DELAY); } catch (InterruptedException ex) { } } else throw e; } } if (log != null) log.debug("ME: " + escapeJava(buffer.toString())); clearBufferCheckCMTI(); // check to see if any phone call alerts have been triggered if (buffer.indexOf("RING") > 0) { // FIXME should this actually read ">= 0"?! if (srv.isConnected()) { if (srv.getCallHandler() != null) { Pattern p = Pattern.compile("\\+?\\d+"); Matcher m = p.matcher(buffer); String phone = m.find() ? m.group() : ""; srv.getCallHandler().received(srv, new CIncomingCall(phone, new java.util.Date())); } // strip all content relating to RING, and return the rest of the response return buffer.toString() .replaceAll("\\s*RING\\s+[\\p{ASCII}]CLIP[[\\p{Alnum}][\\p{Punct}] ]+\\s\\s", ""); } else return buffer.toString(); } else { return buffer.toString(); } }
From source file:org.alfresco.util.exec.RuntimeExec.java
/** * Get the command that will be executed post substitution. * <p>//from w w w . j a va 2s.com * <code>null</code> properties will be treated as an empty string for substitution * purposes. * * @param properties the properties that the command might be executed with * @return Returns the command that will be executed should the additional properties * be supplied */ public String[] getCommand(Map<String, String> properties) { Map<String, String> execProperties = null; if (properties == defaultProperties) { // we are just using the default properties execProperties = defaultProperties; } else { execProperties = new HashMap<String, String>(defaultProperties); // overlay the supplied properties execProperties.putAll(properties); } // Perform the substitution for each element of the command ArrayList<String> adjustedCommandElements = new ArrayList<String>(20); for (int i = 0; i < command.length; i++) { StringBuilder sb = new StringBuilder(command[i]); for (Map.Entry<String, String> entry : execProperties.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // ignore null if (value == null) { value = ""; } // progressively replace the property in the command key = (VAR_OPEN + key + VAR_CLOSE); int index = sb.indexOf(key); while (index > -1) { // replace sb.replace(index, index + key.length(), value); // get the next one index = sb.indexOf(key, index + 1); } } String adjustedValue = sb.toString(); // Now SPLIT: it if (adjustedValue.startsWith(DIRECTIVE_SPLIT)) { String unsplitAdjustedValue = sb.substring(DIRECTIVE_SPLIT.length()); // There may be quoted arguments here (see ALF-7482) ExecParameterTokenizer quoteAwareTokenizer = new ExecParameterTokenizer(unsplitAdjustedValue); List<String> tokens = quoteAwareTokenizer.getAllTokens(); adjustedCommandElements.addAll(tokens); } else { adjustedCommandElements.add(adjustedValue); } } // done return adjustedCommandElements.toArray(new String[adjustedCommandElements.size()]); }
From source file:org.wso2.carbon.identity.authenticator.inbound.saml2sso.test.SPInitTests.java
/** * Test inbound authentication with redirect binding with invalid signature algorithm parameter. *//* ww w .j a v a 2 s . c o m*/ @Test public void testAuthnRequestSignatureValidationWithInvalidSigAlgForRedirect() { ServiceProviderConfig serviceProviderConfig = TestUtils .getServiceProviderConfigs(TestConstants.SAMPLE_ISSUER_NAME, bundleContext); serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties() .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "true"); try { AuthnRequest samlRequest = TestUtils.buildAuthnRequest("https://localhost:9292/gateway", false, false, TestConstants.SAMPLE_ISSUER_NAME, TestConstants.ACS_URL); String samlRequestString = SAML2AuthUtils.encodeForRedirect(samlRequest); StringBuilder httpQueryString = new StringBuilder( SAML2AuthConstants.SAML_REQUEST + "=" + samlRequestString); httpQueryString.append("&" + SAML2AuthConstants.RELAY_STATE + "=" + URLEncoder.encode("relayState", StandardCharsets.UTF_8.name()).trim()); SAML2AuthUtils.addSignatureToHTTPQueryString(httpQueryString, "http://www.w3.org/2000/09/xmldsig#rsa-sha1", SAML2AuthUtils.getServerCredentials()); httpQueryString.replace(httpQueryString.indexOf("SigAlg=") + 7, httpQueryString.indexOf("&Signature="), "sig_alg"); HttpURLConnection urlConnection = TestUtils.request( TestConstants.GATEWAY_ENDPOINT + "?" + httpQueryString.toString(), HttpMethod.GET, false); String postBody = TestUtils.getContent(urlConnection); // Relay state must be returned for error scenarios as well // Assert.assertTrue(postBody.contains(TestConstants.RELAY_STATE)); Assert.assertEquals(urlConnection.getResponseCode(), 200); Assert.assertNotNull(postBody); String samlResponse = postBody.split("SAMLResponse' value='")[1].split("'>")[0]; Response samlResponseObject = TestUtils.getSAMLResponse(samlResponse); Assert.assertEquals(samlResponseObject.getAssertions().size(), 0); } catch (IOException e) { Assert.fail("Error while running testSAMLInboundAuthentication test case", e); } catch (SAML2SSOServerException e) { Assert.fail("Error while building response object", e); } finally { serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties() .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "false"); } }
From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java
public boolean execute(RequestContext requestContext, String currentState, String targetState) { // To keep track of the registry transaction state boolean transactionStatus = false; OMElement historyOperation = null;/*www .ja v a 2s . co m*/ List<String> otherDependencyList = new ArrayList<String>(); // for logging purposes try { historyOperation = AXIOMUtil.stringToOM("<operation></operation>"); } catch (XMLStreamException e) { log.error(e); } // getting the necessary values from the request context Resource resource = requestContext.getResource(); Registry registry = requestContext.getRegistry(); String resourcePath = requestContext.getResourcePath().getPath(); Map<String, String> currentParameterMap = new HashMap<String, String>(); Map<String, String> newPathMappings; // Returning true since this executor is not compatible with collections if (resource instanceof Collection) { return true; } else if (resource.getMediaType() == null || "".equals(resource.getMediaType().trim())) { log.warn("The media-type of the resource '" + resourcePath + "' is undefined. Hence exiting the service version executor."); return true; } else if (!resource.getMediaType().equals(serviceMediaType)) { // We have a generic copy executor to copy any resource type. // This executor is written for services. // If a resource other than a service comes here, then we simply return true // since we can not handle it using this executor. return true; } // Getting the target environment and the current environment from the parameter map. String targetEnvironment = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), (String) parameterMap.get(TARGET_ENVIRONMENT)); String currentEnvironment = RegistryUtils.getAbsolutePath(registry.getRegistryContext(), (String) parameterMap.get(CURRENT_ENVIRONMENT)); if ((targetEnvironment == null || currentEnvironment == null) || (currentEnvironment.isEmpty() || targetEnvironment.isEmpty())) { log.warn("Current environment and the Target environment has not been defined to the state"); // Here we are returning true because the executor has been configured incorrectly // We do NOT consider that as a execution failure // Hence returning true here return true; } // Here we are populating the parameter map that was given from the UI if (!populateParameterMap(requestContext, currentParameterMap)) { log.error("Failed to populate the parameter map"); return false; } try { // Starting a registry transaction registry.beginTransaction(); Resource newResource = registry.newResource(); // This loop is there to reformat the paths with the new versions. newPathMappings = getNewPathMappings(targetEnvironment, currentEnvironment, currentParameterMap, otherDependencyList); // Once the paths are updated with the new versions we do through the service resource and update the // content of the service resource with the new service version, wsdl path. if (!CommonUtil.isUpdateLockAvailable()) { return false; } CommonUtil.acquireUpdateLock(); try { // Iterating through the list of dependencies for (Map.Entry<String, String> currentParameterMapEntry : currentParameterMap.entrySet()) { if (registry.resourceExists(currentParameterMapEntry.getKey())) { String newTempResourcePath; Resource tempResource = registry.get(currentParameterMapEntry.getKey()); if (!(tempResource instanceof Collection) && tempResource.getMediaType() != null) { updateNewPathMappings(tempResource.getMediaType(), currentEnvironment, targetEnvironment, newPathMappings, currentParameterMapEntry.getKey(), currentParameterMapEntry.getValue()); } StringBuilder resourceContent = new StringBuilder(getResourceContent(tempResource)); // Update resource content to reflect new paths for (Map.Entry<String, String> newPathMappingsEntry : newPathMappings.entrySet()) { if (resourceContent != null && !ENDPOINT_MEDIA_TYPE.equals(tempResource.getMediaType())) { int index; if ((index = resourceContent.indexOf(newPathMappingsEntry.getKey())) > -1) { resourceContent.replace(index, index + newPathMappingsEntry.getKey().length(), newPathMappingsEntry.getValue()); } else if (SCHEMA_MEDIA_TYPE.equals(tempResource.getMediaType())) { updateSchemaRelativePaths(targetEnvironment, currentEnvironment, resourceContent, newPathMappingsEntry); } else if (WSDL_MEDIA_TYPE.equals(tempResource.getMediaType())) { updateWSDLRelativePaths(targetEnvironment, currentEnvironment, resourceContent, newPathMappingsEntry); } } } tempResource.setContent(resourceContent.toString()); newTempResourcePath = newPathMappings.get(tempResource.getPath()); // Checking whether this resource is a service resource // If so, then we handle it in a different way if ((tempResource.getMediaType() != null) && (tempResource.getMediaType().equals(serviceMediaType))) { newResource = tempResource; OMElement serviceElement = getServiceOMElement(newResource); OMFactory fac = OMAbstractFactory.getOMFactory(); // Adding required fields at the top of the xml which will help to easily read in service side Iterator it = serviceElement.getChildrenWithLocalName("newServicePath"); if (it.hasNext()) { OMElement next = (OMElement) it.next(); next.setText(newTempResourcePath); } else { OMElement operation = fac.createOMElement("newServicePath", serviceElement.getNamespace(), serviceElement); operation.setText(newTempResourcePath); } setServiceVersion(serviceElement, currentParameterMap.get(tempResource.getPath())); // This is here to override the default path serviceElement.build(); resourceContent = new StringBuilder(serviceElement.toString()); newResource.setContent(resourceContent.toString()); addNewId(registry, newResource, newTempResourcePath); continue; } addNewId(registry, tempResource, newTempResourcePath); // We add all the resources other than the original one here if (!tempResource.getPath().equals(resourcePath)) { // adding logs historyOperation.addChild(getHistoryInfoElement(newTempResourcePath + " created")); registry.put(newTempResourcePath, tempResource); // copyCommunityFeatures(requestContext, registry, resourcePath, newPathMappings, historyOperation); copyComments(registry, newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); copyRatings(requestContext.getSystemRegistry(), newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); copyAllAssociations(registry, newTempResourcePath, currentParameterMapEntry.getKey(), historyOperation); } } } // We check whether there is a resource with the same name,namespace and version in this environment // if so, we make it return false based on override flag. if (registry.resourceExists(newPathMappings.get(resourcePath)) & !override) { // This means that we should not do this operation and we should fail this String message = "A resource exists with the given version"; requestContext.setProperty(LifecycleConstants.EXECUTOR_MESSAGE_KEY, message); throw new RegistryException(message); } // This is to handle the original resource and put it to the new path registry.put(newPathMappings.get(resourcePath), newResource); historyOperation.addChild(getHistoryInfoElement(newPathMappings.get(resourcePath) + " created")); // Initializing statCollection object StatCollection statCollection = new StatCollection(); // Set action type="association" statCollection.setActionType(ASSOCIATION); statCollection.setAction(""); statCollection.setRegistry(registry.getRegistryContext().getEmbeddedRegistryService() .getSystemRegistry(CurrentSession.getTenantId())); statCollection.setTimeMillis(System.currentTimeMillis()); statCollection.setState(currentState); statCollection.setResourcePath(newPathMappings.get(resourcePath)); statCollection.setUserName(CurrentSession.getUser()); statCollection.setOriginalPath(newPathMappings.get(resourcePath)); statCollection.setTargetState(targetState); statCollection.setAspectName(resource.getProperty(LIFECYCLE_ASPECT_NAME)); // Writing the logs to the registry as history if (isAuditEnabled) { StatWriter.writeHistory(statCollection); } } finally { CommonUtil.releaseUpdateLock(); } // Associating the new resource with the LC String aspectName = resource.getProperty(REGISTRY_LC_NAME); registry.associateAspect(newPathMappings.get(resourcePath), aspectName); makeDependencies(requestContext, currentParameterMap, newPathMappings); makeOtherDependencies(requestContext, newPathMappings, otherDependencyList); // Here we are coping the comments,tags,rating and associations of the original resource copyCommunityFeatures(requestContext, registry, resourcePath, newPathMappings, historyOperation); addSubscriptionAvailableProperty(newResource); requestContext.setResource(newResource); requestContext.setOldResource(resource); requestContext.setResourcePath(new ResourcePath(newPathMappings.get(resourcePath))); // adding logs StatCollection statCollection = (StatCollection) requestContext .getProperty(LifecycleConstants.STAT_COLLECTION); // keeping the old path due to logging purposes newResource.setProperty(LifecycleConstants.REGISTRY_LIFECYCLE_HISTORY_ORIGINAL_PATH + aspectName, statCollection.getOriginalPath()); statCollection.addExecutors(this.getClass().getName(), historyOperation); transactionStatus = true; } catch (RegistryException e) { log.error("Failed to perform registry operation", e); return false; } finally { try { if (transactionStatus) { registry.commitTransaction(); } else { registry.rollbackTransaction(); } } catch (RegistryException e) { log.error("Unable to finish the transaction", e); } } return true; }
From source file:org.sakaiproject.portlets.PortletIFrame.java
/** * Expand one macro reference/*from w w w. j a v a 2s .c om*/ * @param text Expand macros found in this text * @param macroName Macro name */ private void expand(StringBuilder sb, String macroName) { int index; /* * Replace every occurance of the macro in the parameter list */ index = sb.indexOf(macroName); while (index != -1) { String macroValue = URLEncoder.encode(getMacroValue(macroName)); sb.replace(index, (index + macroName.length()), macroValue); index = sb.indexOf(macroName, (index + macroValue.length())); } }
From source file:com.moviejukebox.plugin.AnimatorPlugin.java
/** * Retrieve Animator matching the specified movie name and year. * * This routine is base on a Google request. *//*from w w w. ja v a 2 s . c o m*/ private String getAnimatorId(String movieName, String year) { try { String animatorId = Movie.UNKNOWN; String allmultsId = Movie.UNKNOWN; String sb = movieName; // Unaccenting letters sb = Normalizer.normalize(sb, Normalizer.Form.NFD); // Return simple letters '' & '' sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("" + (char) 774, ""); sb = sb.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); sb = "text=" + URLEncoder.encode(sb, "Cp1251").replace(" ", "+"); // Get ID from animator.ru if (animatorDiscovery) { String uri = "http://www.animator.ru/db/?p=search&SearchMask=1&" + sb; if (StringTools.isValidString(year)) { uri = uri + "&year0=" + year; uri = uri + "&year1=" + year; } String xml = httpClient.request(uri); // Checking for zero results if (xml.contains("[?? ]")) { // It's search results page, searching a link to the movie page int beginIndex; if (-1 != xml.indexOf("? ")) { for (String tmp : HTMLTools.extractTags(xml, "? ", HTML_TD, HTML_HREF, "<br><br>")) { if (0 < tmp.indexOf("[?? ]")) { beginIndex = tmp.indexOf(" .)"); if (beginIndex >= 0) { String year2 = tmp.substring(beginIndex - 4, beginIndex); if (year2.equals(year)) { beginIndex = tmp.indexOf("http://www.animator.ru/db/?p=show_film&fid=", beginIndex); if (beginIndex >= 0) { StringTokenizer st = new StringTokenizer(tmp.substring(beginIndex + 43), " "); animatorId = st.nextToken(); break; } } } } } } } } // Get ID from allmults.org if (multsDiscovery) { URL url = new URL("http://allmults.org/search.php"); URLConnection conn = url.openConnection(YamjHttpClientBuilder.getProxy()); conn.setDoOutput(true); OutputStreamWriter osWriter = null; StringBuilder xmlLines = new StringBuilder(); try { osWriter = new OutputStreamWriter(conn.getOutputStream()); osWriter.write(sb); osWriter.flush(); try (InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "cp1251"); BufferedReader bReader = new BufferedReader(inReader)) { String line; while ((line = bReader.readLine()) != null) { xmlLines.append(line); } } osWriter.flush(); } finally { if (osWriter != null) { osWriter.close(); } } if (xmlLines.indexOf("<div class=\"post\"") != -1) { for (String tmp : HTMLTools.extractTags(xmlLines.toString(), " ? ", "<ul><li>", "<div class=\"entry\"", "</div>")) { int pos = tmp.indexOf("<img "); if (pos != -1) { int temp = tmp.indexOf(" alt=\""); if (temp != -1) { String year2 = tmp.substring(temp + 6, tmp.indexOf("\"", temp + 6) - 1); year2 = year2.substring(year2.length() - 4); if (year2.equals(year)) { temp = tmp.indexOf(" src=\"/images/multiki/"); if (temp != -1) { allmultsId = tmp.substring(temp + 22, tmp.indexOf(".jpg", temp + 22)); break; } } } } } } } return (animatorId.equals(Movie.UNKNOWN) && allmultsId.equals(Movie.UNKNOWN)) ? Movie.UNKNOWN : animatorId + ":" + allmultsId; } catch (IOException error) { LOG.error("Failed retreiving Animator Id for movie : {}", movieName); LOG.error("Error : {}", error.getMessage()); return Movie.UNKNOWN; } }