List of usage examples for org.apache.commons.lang3 StringUtils removeStart
public static String removeStart(final String str, final String remove)
Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.
A null source string will return null .
From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java
private List<String> jar(JarInputStream jarStream) throws IOException { List<String> classNames = new ArrayList<String>(); JarEntry entry;/*from ww w.j av a 2 s .c o m*/ while ((entry = jarStream.getNextJarEntry()) != null) { if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } String className = entry.getName(); className = className.replaceFirst(".class$", ""); //war files are treated as .jar files, so takeout WEB-INF/classes className = StringUtils.removeStart(className, "WEB-INF/classes/"); className = className.replace('/', '.'); classNames.add(className); } return classNames; }
From source file:com.xpn.xwiki.plugin.lucene.LucenePlugin.java
/** * Create a {@link SortField} corresponding to the field name. If the field name starts with '-', then the field * (excluding the leading -) will be used for reverse sorting. * //from ww w. ja v a2 s .c o m * @param sortField The name of the field to sort by. If <tt>null</tt>, return a <tt>null</tt> SortField. If starts * with '-', then return a SortField that does a reverse sort on the field. * @return A SortFiled that sorts on the given field, or <tt>null</tt>. */ private SortField getSortField(String sortField) { SortField sort = null; if (!StringUtils.isEmpty(sortField)) { // For the moment assuming everything is a String is enough, since we don't usually want to sort documents // on numerical object properties. sort = new SortField(StringUtils.removeStart(sortField, "-"), SortField.STRING, sortField.startsWith("-")); } return sort; }
From source file:mfi.filejuggler.responsibles.BasicApplication.java
@Responsible(conditions = { Condition.PASSWORD_CHECK_DECRYPT, Condition.PASSWORD_CHECK_ENCRYPT }) public void fjPasswortPruefen(StringBuilder sb, Map<String, String> parameters, Model model) throws Exception { // Die via Hidden Fields durchgeschleiften Parameter uebernehmen, sofern nicht vorhanden Base32 base32 = new Base32(); Object[] keys = parameters.keySet().toArray(); for (Object key : keys) { String keyString = (String) key; if (StringUtils.startsWith(keyString, "pass_routing_")) { String keyOriginal = StringUtils.removeStart(keyString, "pass_routing_"); // Alle nicht gesetzten Parameter setzen. // Damit wird vermieden, dass Sessionvariablen ueberschrieben werden // Ausnahme: Die Ziel-Condition (z.B. FILE_VIEW). Diese immer ueberschreiben, sonst geht bei >1 Versuchen der // Passwort-Eingabe die Ziel-Condition verloren und nach der Eingabe des korrektes Passworts wissen wir nicht mehr, wohin // wir zurueck springen muessen. if (!parameters.containsKey(keyOriginal) || StringUtils.equals(keyOriginal, HTMLUtils.CONDITION)) { String valueDecoded = new String(base32.decode(parameters.get(keyString))); parameters.put(keyOriginal, valueDecoded); // Xystem.out.println("durchschleifen rein:" + keyOriginal + " / " + valueDecoded); }//from w ww . j a va2 s.co m // String valueBase32 = new String(base32.decode(parameters.get(key).getBytes())); // sb.append(HTMLUtils.buildHiddenField("pass_routing_" + key, valueBase32)); } } String pass1 = parameters.get("inapp_pass_one"); String pass2 = parameters.get("inapp_pass_two"); if (model.lookupConversation().getCondition().equals(Condition.PASSWORD_CHECK_ENCRYPT)) { // verschluesseln if (StringUtils.isNotEmpty(pass1) && StringUtils.equals(pass1, pass2)) { // Neues Passwort ist gueltig model.lookupConversation().getEditingFile().prospectivePassword(pass1); } else { model.lookupConversation().getMeldungen() .add("Die Passwrter waren nicht gleich oder leer. Bitte nochmal eingeben."); // Zurueck zur Eingabe model.lookupConversation().setForwardCondition(Condition.PASSWORD_ASK_ENCRYPT); return; } } else { // entschluesseln if (model.lookupConversation().getEditingFile().pendingPassword(pass1)) { // eingegebenes Passwort ist richtig bzw kann die Datei entschluesseln } else { // Zurueck zur Eingabe model.lookupConversation().getMeldungen() .add("Mit dem eingegebenen Passwort konnte die Datei nicht entschlsselt werden."); Security.addCounterToBlacklist(model.getUser()); model.lookupConversation().setForwardCondition(Condition.PASSWORD_ASK_DECRYPT); return; } } // Wenn wir bis hier gekommen sind, ist/sind die Passwoerter richtig und es kann zur eigentlichen Ziel-Condition weitergeleitet // werden. Condition forward = Condition.valueOf( new String(base32.decode(parameters.get("pass_routing_" + HTMLUtils.CONDITION).getBytes()))); model.lookupConversation().setForwardCondition(forward); return; }
From source file:fusion.Fusion.java
private static void getINASameAsLinks(File file) throws FileNotFoundException, IOException, URISyntaxException { try (BufferedReader br = new BufferedReader(new FileReader(file))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { if (line.contains("owl:sameAs")) { sb.append(line);/* w w w . j a va 2 s .c o m*/ sb.append(System.lineSeparator()); } line = br.readLine(); } String linksString = sb.toString(); String[] linksArray = linksString.split("\n"); for (int i = 0; i < linksArray.length; i++) { String value1 = linksArray[i].substring(0, linksArray[i].indexOf(" owl:sameAs")); String value2 = linksArray[i].substring(linksArray[i].lastIndexOf("owl:sameAs ") + 11, linksArray[i].length() - 1); value1 = StringUtils.removeStart(value1, "<"); value2 = StringUtils.removeStart(value2, "<"); value1 = StringUtils.removeStart(value1, "http://www.ina.fr/thesaurus/pp/"); value2 = StringUtils.removeStart(value2, "http://www.ina.fr/thesaurus/pp/"); value1 = StringUtils.removeStart(value1, "http://fr.dbpedia.org/resource/"); // value2 = StringUtils.removeStart(value2, "http://fr.dbpedia.org/resource/"); // value1 = StringUtils.removeEnd(value1, "."); value2 = StringUtils.removeEnd(value2, "."); value1 = StringUtils.removeEnd(value1, ">"); value2 = StringUtils.removeEnd(value2, ">"); if (!distinctURLs.containsKey(value1.hashCode())) distinctURLs.put(value1.hashCode(), new URI(value1)); if (!distinctURLs.containsKey(value2.hashCode())) distinctURLs.put(value2.hashCode(), new URI(value2)); links.add(new SameAsLink(distinctURLs.get(value1.hashCode()), distinctURLs.get(value2.hashCode()))); // adding same as links } for (Integer name : distinctURLs.keySet()) { Instance instance = new Instance(distinctURLs.get(name), null); if (distinctURLs.get(name).toString().contains("dbpedia")) instance.setSource(sources.get("fr.dbpedia.org")); else instance.setSource(sources.get("www.ina.fr")); instances.put(instance.getUri(), instance); } } }
From source file:com.adobe.cq.dialogconversion.impl.rules.NodeBasedRewriteRule.java
/** * Replaces the value of a mapped property with a value from the original tree. * * @param root the root node of the original tree * @param property the (potentially) mapped property in the replacement copy tree * @return the mapped property if there was a successful mapping, null otherwise *//*ww w .jav a 2 s. c om*/ private Property mapProperty(Node root, Property property) throws RepositoryException { if (property.getType() != PropertyType.STRING) { // a mapped property must be of type string return null; } // array containing the expressions: ${<path>} Value[] values; if (property.isMultiple()) { values = property.getValues(); } else { values = new Value[1]; values[0] = property.getValue(); } boolean deleteProperty = false; for (Value value : values) { Matcher matcher = MAPPED_PATTERN.matcher(value.getString()); if (matcher.matches()) { // this is a mapped property, we will delete it if the mapped destination // property doesn't exist deleteProperty = true; String path = matcher.group(2); // unwrap quoted property paths path = StringUtils.removeStart(StringUtils.stripEnd(path, "\'"), "\'"); if (root.hasProperty(path)) { // replace property by mapped value in the original tree Property originalProperty = root.getProperty(path); String name = property.getName(); Node parent = property.getParent(); property.remove(); Property newProperty = JcrUtil.copy(originalProperty, parent, name); // negate boolean properties if negation character has been set String negate = matcher.group(1); if ("!".equals(negate) && originalProperty.getType() == PropertyType.BOOLEAN) { newProperty.setValue(!newProperty.getBoolean()); } // the mapping was successful deleteProperty = false; break; } else { String defaultValue = matcher.group(4); if (defaultValue != null) { if (property.isMultiple()) { // the property is multiple in the replacement, // recreate it so we can set the property to the default String name = property.getName(); Node parent = property.getParent(); property.remove(); parent.setProperty(name, defaultValue); } else { property.setValue(defaultValue); } deleteProperty = false; break; } } } } if (deleteProperty) { // mapped destination does not exist, we don't include the property in replacement tree property.remove(); return null; } return property; }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes a URL-based session id. It removes PHP (PHPSESSID), * ASP (ASPSESSIONID), and Java EE (jsessionid) session ids.</p> * <code>http://www.example.com/servlet;jsessionid=1E6FEC0D14D044541DD84D2D013D29ED?a=b * → http://www.example.com/servlet?a=b</code> * <p><b>Please Note:</b> Removing session IDs from URLs is often * a good way to have the URL return an error once invoked.</p> * @return this instance/*www.j a v a2s . co m*/ */ public URLNormalizer removeSessionIds() { if (StringUtils.containsIgnoreCase(url, ";jsessionid=")) { url = url.replaceFirst("(;jsessionid=[0-9a-fA-F]*)", ""); } else { String u = StringUtils.substringBefore(url, "?"); String q = StringUtils.substringAfter(url, "?"); if (StringUtils.containsIgnoreCase(url, "PHPSESSID=")) { q = q.replaceFirst("(&|^)(PHPSESSID=[0-9a-zA-Z]*)", ""); } else if (StringUtils.containsIgnoreCase(url, "ASPSESSIONID")) { q = q.replaceFirst("(&|^)(ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]*)", ""); } if (!StringUtils.isBlank(q)) { u += "?" + StringUtils.removeStart(q, "&"); } url = u; } return this; }
From source file:com.xpn.xwiki.XWiki.java
/** * Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki. * /*from w ww . jav a 2 s. c o m*/ * @param context the current context * @return an XWiki object configured for the wiki corresponding to the current request * @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the * storage */ public static XWiki getXWiki(XWikiContext context) throws XWikiException { XWiki xwiki = getMainXWiki(context); if (!xwiki.isVirtualMode()) { return xwiki; } // Host is full.host.name in DNS-based multiwiki, and wikiname in path-based multiwiki. String host = ""; // Canonical name of the wiki (database) String wikiName = ""; // wikiDefinition should be the document holding the definition of the virtual wiki, a document in the main // wiki with a XWiki.XWikiServerClass object attached to it DocumentReference wikiDefinition; XWikiRequest request = context.getRequest(); try { URL requestURL = context.getURL(); host = requestURL.getHost(); } catch (Exception e) { } // In path-based multi-wiki, the wiki name is an element of the request path. // The url is in the form /xwiki (app name)/wiki (servlet name)/wikiname/ if ("1".equals(xwiki.Param("xwiki.virtual.usepath", "0"))) { String uri = request.getRequestURI(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Request uri is: " + uri); } // Remove the (eventual) context path from the URI, usually /xwiki uri = stripSegmentFromPath(uri, request.getContextPath()); // Remove the (eventual) servlet path from the URI, usually /wiki String servletPath = request.getServletPath(); uri = stripSegmentFromPath(uri, servletPath); if (servletPath.equals("/" + xwiki.Param("xwiki.virtual.usepath.servletpath", "wiki"))) { // Requested path corresponds to a path-based wiki, now the wiki name is between the first and // second "/" host = StringUtils.substringBefore(StringUtils.removeStart(uri, "/"), "/"); } } if (StringUtils.isEmpty(host) || host.equals(context.getMainXWiki())) { // Can't find any wiki name, return the main wiki return xwiki; } wikiDefinition = xwiki.findWikiServer(host, context); if (wikiDefinition == null) { // No definition found based on the full domain name/path wiki name, try to use the first part of the domain // name as the wiki name String servername = StringUtils.substringBefore(host, "."); // As a convenience, allow sites starting with www, localhost or using an // IP address not to have to create a XWikiServerXwiki page since we consider // in that case that they're pointing to the main wiki. if (!"0".equals(xwiki.Param("xwiki.virtual.autowww")) && (servername.equals("www") || host.equals("localhost") || host.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}"))) { return xwiki; } wikiDefinition = new DocumentReference(DEFAULT_MAIN_WIKI, SYSTEM_SPACE, "XWikiServer" + StringUtils.capitalize(servername)); } // Check if this wiki definition exists in the Database XWikiDocument doc = xwiki.getDocument(wikiDefinition, context); if (doc.isNew()) { throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_DOES_NOT_EXIST, "The wiki " + host + " does not exist"); } // Set the wiki owner String wikiOwner = doc.getStringValue(VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE, "owner"); if (wikiOwner.indexOf(':') == -1) { wikiOwner = xwiki.getDatabase() + ":" + wikiOwner; } context.setWikiOwner(wikiOwner); context.setWikiServer(doc); wikiName = StringUtils.removeStart(wikiDefinition.getName(), "XWikiServer").toLowerCase(); context.setDatabase(wikiName); context.setOriginalDatabase(wikiName); try { // Let's make sure the virtual wikis are upgraded to the latest database version xwiki.updateDatabase(wikiName, false, context); } catch (HibernateException ex) { // Just report it, hopefully the database is in a good enough state LOGGER.error("Failed to upgrade database: " + wikiName, ex); } return xwiki; }
From source file:com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl.java
/** * The authentication library we are using (SecurityFilter) requires that its URLs do not contain the context path, * in order to be usable with <tt>RequestDispatcher.forward</tt>. Since our URL factory include the context path in * the generated URLs, we use this method to remove (if needed) the context path. * /*from w w w. java 2 s. c om*/ * @param url The URL to process. * @param context The ubiquitous XWiki request context. * @return A <code>String</code> representation of the contextpath-free URL. */ protected String stripContextPathFromURL(URL url, XWikiContext context) { String contextPath = context.getWiki().getWebAppPath(context); // XWiki uses contextPath in the wrong way, putting a / at the end, and not at the start. Fix this here. if (contextPath.endsWith("/") && !contextPath.startsWith("/")) { contextPath = "/" + StringUtils.chop(contextPath); } // URLFactory.getURL applies Util.escapeURL, which might convert the contextPath into an %NN escaped string. // Apply the same escape method to compensate this. contextPath = Util.escapeURL(contextPath); String urlPrefix = url.getProtocol() + "://" + url.getAuthority() + contextPath; return StringUtils.removeStart(url.toExternalForm(), urlPrefix); }
From source file:fusion.Fusion.java
private static void parseINAData() throws FileNotFoundException, IOException { try (Scanner scanner = new Scanner(new File("dataINA/dataset_novideoperson.ttl")) .useDelimiter(Pattern.compile("^\\s*$", Pattern.MULTILINE))) { // On parcourt le fichier avec les donnees while (scanner.hasNext()) { String token = scanner.next(); String propName = ""; String propValue = ""; token = new String(token.trim().getBytes(), Charset.forName("UTF-8")); // for (Integer name: distinctURLs.keySet()){ // String value = new String(distinctURLs.get(name).getBytes(), // Charset.forName("UTF-8")); for (URI name : instances.keySet()) { Instance inst = instances.get(name); // Moins optimise que // de parcourir les // distinctURLs ? URI value = inst.getUri(); if (token.contains(value.toString())) { // le scanner lit l'URL try (Scanner scannerToken = new Scanner(token)) { while (scannerToken.hasNextLine()) { String line = scannerToken.nextLine(); line = line.trim(); // properties start with "notice:" if (line.startsWith("notice")) { if (line.contains(" ")) { propName = line.substring(7, line.indexOf(" ")); propValue = line.substring(line.indexOf(" ")).trim().replaceAll("\\s+", " "); // Instance inst = instances.get(value); // add property in map if it doesn't // exist Property prop; if (!inst.containsProperty(propName)) { prop = new Property(propName); inst.addToProperties(prop); } else prop = inst.getProperty(propName); // get datatype values if (propValue.startsWith("\"")) { propValue = StringUtils.removeStart(propValue, "\""); propValue = StringUtils.substringBeforeLast(propValue, "\""); Value val = new Value(propValue); if (value.toString().contains("dbpedia")) { val.setSource(sources.get("fr.dbpedia.org")); } else { val.setSource(sources.get("www.ina.fr")); } if (!prop.containsValue(propValue)) // prop.addToValues(val); }/*from ww w. j a va 2s. c o m*/ } // System.out.println("=== "+line); } // LineStarts(notice) // System.out.println("*** "+line); } } } } } } }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
private String getBackingArrayPathForSegment(int num, String suffix) { String str = Integer.toString(num); ArrayList<String> parts = new ArrayList<String>(); while (str.length() > 2) { String head = StringUtils.left(str, 2); str = StringUtils.removeStart(str, head); parts.add(head);/*from www.j av a2s .co m*/ } return StringUtils.removeEnd(segmentsDirName() + StringUtils.join(parts, "/"), "/") + "/" + Integer.toString(num) + "." + suffix.trim(); }