List of usage examples for org.apache.commons.lang3 StringUtils substringAfter
public static String substringAfter(final String str, final String separator)
Gets the substring after the first occurrence of a separator.
From source file:net.eledge.android.europeana.search.SearchController.java
public String getSearchTitle(Context context) { String title = GuiUtils.getString(context, R.string.app_name); if (!terms.isEmpty()) { title = terms.get(0);//from w w w .j ava 2s.c o m if (StringUtils.contains(title, ":")) { title = StringUtils.substringAfter(title, ":"); } title = WordUtils.capitalizeFully(title); } return title; }
From source file:com.mgmtp.jfunk.core.mail.MailAccountManager.java
private MailAccount reserveAvailableMailAccount(final String accountReservationKey, final List<MailAccount> addressPool) { checkNotNull(accountReservationKey, "'accountReservationKey' must not be null"); checkNotNull(addressPool, "'addressPool' must not be null"); checkState(emailAddressPools.keySet().size() > 0, "'addressPool' must not be empty."); lock.lock();/*from w ww. j av a 2 s . c o m*/ try { while (true) { String fixedAccountId = config.get("mail." + accountReservationKey + ".accountId"); MailAccount account = lookupUsedMailAccountForCurrentThread(accountReservationKey); if (!isNullOrEmpty(fixedAccountId)) { if (account != null) { checkState(account.getAccountId().equals(fixedAccountId), "Fixed configured mail account does not match that already reserved (configured=%s, reserved=%s)", fixedAccountId, account.getAccountId()); } else { account = lookupMailAccount(fixedAccountId); if (isReserved(account)) { // Already reserved by another thread, so we cannot use it. // Set it to null in order to trigger the wait below. account = null; } } } else { checkState(!addressPool.isEmpty(), "No fixed e-mail account configured and specified pool is empty."); boolean subaddressing = config.getBoolean(EmailConstants.MAIL_SUBADDRESSING); if (subaddressing) { checkState(addressPool.size() == 1, "Mail subaddressing is active, specified pool must contain only one e-mail account."); } if (account != null) { checkState(addressPool.contains(account), "Account '%s' is already reserved under key: %s", account, accountReservationKey); log.info("Using already reserved e-mail account: {}", account.getAccountId()); return account; } if (subaddressing) { MailAccount acc = addressPool.get(0); MailAuthenticator auth = (MailAuthenticator) acc.getAuthenticator(); StringBuilder uniqueAddress = new StringBuilder(); uniqueAddress.append(StringUtils.substringBefore(acc.getAddress(), "@")); uniqueAddress.append("+"); uniqueAddress.append(UUID.randomUUID()); uniqueAddress.append("@"); uniqueAddress.append(StringUtils.substringAfter(acc.getAddress(), "@")); account = new MailAccount(acc.getAccountId(), uniqueAddress.toString(), auth.getUser(), auth.getPassword()); } else { // Try to find a free account. for (MailAccount acc : addressPool) { ThreadReservationKeyWrapper wrapper = usedAccounts.get(acc); if (wrapper == null) { account = acc; break; } } } } if (account == null) { // No free account available. We wait and then start over with the loop. log.info("No free e-mail account available. Waiting..."); condition.await(); } else { // We've found a free account and return it. String accountId = account.getAccountId(); log.info("Found free e-mail account={} with address={}", accountId, account.getAddress()); usedAccounts.put(account, new ThreadReservationKeyWrapper(Thread.currentThread(), accountReservationKey)); // post account reservation eventBusProvider.get().post(new MailAccountReservationEvent(accountReservationKey, account)); return account; } } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new JFunkException(ex.getMessage(), ex); } finally { lock.unlock(); } }
From source file:de.blizzy.documentr.markdown.MarkdownProcessor.java
public String processNonCacheableMacros(String html, String projectName, String branchName, String path, Authentication authentication, String contextPath) { HtmlSerializerContext context = new HtmlSerializerContext(projectName, branchName, path, this, authentication, pageStore, systemSettingsStore, contextPath); String startMarkerPrefix = "__" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String endMarkerPrefix = "__/" + NON_CACHEABLE_MACRO_MARKER + "_"; //$NON-NLS-1$ //$NON-NLS-2$ String bodyMarker = "__" + NON_CACHEABLE_MACRO_BODY_MARKER + "__"; //$NON-NLS-1$ //$NON-NLS-2$ for (;;) {/*from ww w. j a v a 2 s . c o m*/ int start = html.indexOf(startMarkerPrefix); if (start < 0) { break; } start += startMarkerPrefix.length(); int end = html.indexOf('_', start); if (end < 0) { break; } String idx = html.substring(start, end); start = html.indexOf("__", start); //$NON-NLS-1$ if (start < 0) { break; } start += 2; end = html.indexOf(endMarkerPrefix + idx + "__", start); //$NON-NLS-1$ if (end < 0) { break; } String macroCallWithBody = html.substring(start, end); String macroCall = StringUtils.substringBefore(macroCallWithBody, bodyMarker); String body = StringUtils.substringAfter(macroCallWithBody, bodyMarker); String macroName = StringUtils.substringBefore(macroCall, " "); //$NON-NLS-1$ String params = StringUtils.substringAfter(macroCall, " "); //$NON-NLS-1$ IMacro macro = macroFactory.get(macroName); MacroContext macroContext = MacroContext.create(macroName, params, body, context, beanFactory); IMacroRunnable macroRunnable = macro.createRunnable(); html = StringUtils.replace(html, startMarkerPrefix + idx + "__" + macroCallWithBody + endMarkerPrefix + idx + "__", //$NON-NLS-1$ //$NON-NLS-2$ StringUtils.defaultString(macroRunnable.getHtml(macroContext))); MacroInvocation invocation = new MacroInvocation(macroName, params); html = cleanupHtml(html, Collections.singletonList(invocation), false); } return html; }
From source file:ch.cyberduck.core.ftp.FTPMlsdListResponseReader.java
/** * The "facts" for a file in a reply to a MLSx command consist of * information about that file. The facts are a series of keyword=value * pairs each followed by semi-colon (";") characters. An individual * fact may not contain a semi-colon in its name or value. The complete * series of facts may not contain the space character. See the * definition or "RCHAR" in section 2.1 for a list of the characters * that can occur in a fact value. Not all are applicable to all facts. * <p/>/*from w w w . j a va 2 s . c o m*/ * A sample of a typical series of facts would be: (spread over two * lines for presentation here only) * <p/> * size=4161;lang=en-US;modify=19970214165800;create=19961001124534; * type=file;x.myfact=foo,bar; * <p/> * This document defines a standard set of facts as follows: * <p/> * size -- Size in octets * modify -- Last modification time * create -- Creation time * type -- Entry type * unique -- Unique id of file/directory * perm -- File permissions, whether read, write, execute is * allowed for the login id. * lang -- Language of the file name per IANA [11] registry. * media-type -- MIME media-type of file contents per IANA registry. * charset -- Character set per IANA registry (if not UTF-8) * * @param line The "facts" for a file in a reply to a MLSx command * @return Parsed keys and values */ protected Map<String, Map<String, String>> parseFacts(final String line) { final Pattern p = Pattern.compile("\\s?(\\S+\\=\\S+;)*\\s(.*)"); final Matcher result = p.matcher(line); final Map<String, Map<String, String>> file = new HashMap<String, Map<String, String>>(); if (result.matches()) { final String filename = result.group(2); final Map<String, String> facts = new HashMap<String, String>(); for (String fact : result.group(1).split(";")) { String key = StringUtils.substringBefore(fact, "="); if (StringUtils.isBlank(key)) { continue; } String value = StringUtils.substringAfter(fact, "="); if (StringUtils.isBlank(value)) { continue; } facts.put(key.toLowerCase(Locale.ROOT), value); } file.put(filename, facts); return file; } log.warn(String.format("No match for %s", line)); return null; }
From source file:kenh.expl.impl.ExpLParser.java
/** * Invoke functioin, support name space. For example, expl:contains(...). * @param function/*from ww w .j ava 2 s. co m*/ * @return Return string or non-string object. Return empty string instead of null. */ private Object executeFunction(String function) throws UnsupportedExpressionException { // function should return a string object; if (StringUtils.isBlank(function)) { UnsupportedExpressionException e = new UnsupportedExpressionException("Function is null."); throw e; } logger.trace("Func: " + function); String parameter = StringUtils.substringBeforeLast(StringUtils.substringAfter(function, "("), ")"); String[] parts = splitParameter(parameter); String funcName = StringUtils.substringBetween(function, "#", "("); String nameSpace = null; if (StringUtils.contains(funcName, ":")) { nameSpace = StringUtils.substringBefore(funcName, ":"); funcName = StringUtils.substringAfter(funcName, ":"); } if (StringUtils.isBlank(funcName)) { UnsupportedExpressionException e = new UnsupportedExpressionException("Failure to get function name"); e.push(function); throw e; } Object[] objs = new Object[parts.length]; int i = 0; for (String part : parts) { if (part.indexOf('{') != -1) { Object obj = this.parseExpress(part); objs[i++] = obj; } else { objs[i++] = part; } } try { // instantiate it, and create the parameters Function func = this.getEnvironment().getFunction(nameSpace, funcName); if (func == null) throw new UnsupportedExpressionException("Can't find the function. [" + (StringUtils.isBlank(nameSpace) ? funcName : nameSpace + ":" + funcName) + "]"); func.setEnvironment(this.getEnvironment()); // invoke return func.invoke(objs); } catch (UnsupportedExpressionException e) { e.push(function); throw e; } catch (Exception ex) { UnsupportedExpressionException e = new UnsupportedExpressionException(ex); e.push(function); throw e; } }
From source file:info.magnolia.ui.vaadin.integration.jcr.AbstractJcrNodeAdapterTest.java
@Test public void testUpdatePropertiesNameToAlreadyExisting() throws Exception { // MockSession doesn't support move so we use a spy final MockSession session = spy(this.session); final Node root = new MockNode(session); MockContext ctx = (MockContext) MgnlContext.getInstance(); ctx.addSession(WORKSPACE_NAME, session); // mocking rename operation doAnswer(new Answer<Void>() { @Override//from w w w . j av a2 s . c o m public Void answer(InvocationOnMock invocation) throws Throwable { String srcAbsPath = (String) invocation.getArguments()[0]; String dstAbsPath = (String) invocation.getArguments()[1]; session.removeItem(srcAbsPath); String dstRelPath = StringUtils.substringAfter(dstAbsPath, root.getPath()); root.addNode(dstRelPath); return null; } }).when(session).move(anyString(), anyString()); // GIVEN String existingName = "existingName"; String subNodeName = "subNode"; root.setProperty(existingName, "42"); Node subNode = root.addNode(subNodeName); long nodeCount = root.getNodes().getSize(); long propertyCount = root.getProperties().getSize(); DummyJcrNodeAdapter adapter = new DummyJcrNodeAdapter(subNode); // WHEN adapter.getItemProperty(ModelConstants.JCR_NAME).setValue(existingName); adapter.applyChanges(); // THEN assertTrue(root.hasProperty(existingName)); assertFalse(root.hasNode(existingName)); assertFalse(root.hasNode(subNodeName)); assertEquals(nodeCount, root.getNodes().getSize()); assertEquals(propertyCount, root.getProperties().getSize()); }
From source file:fi.csc.kapaVirtaAS.MessageTransformer.java
private String stripXmlDefinition(String message) { String sub = StringUtils.substringAfter(message, "?>"); if (sub != null && sub != "") { return sub; }/*ww w. ja va 2 s . c om*/ return message; }
From source file:jp.mathes.databaseWiki.web.DbwServlet.java
private void handleHttp(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); String user = null;/*ww w .j a v a 2 s .c om*/ String password = null; if (req.getHeader("Authorization") != null) { String[] split = req.getHeader("Authorization").split(" "); String userpw = ""; if (split.length > 1) { userpw = new String(Base64.decodeBase64(split[1])); } user = StringUtils.substringBefore(userpw, ":"); password = StringUtils.substringAfter(userpw, ":"); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("application/xhtml+xml; charset=UTF-8"); try { this.handleAction(req, resp, user, password); } catch (InstantiationException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not instantiate database backend: " + e.getMessage()); } catch (IllegalAccessException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Illegal Access: " + e.getMessage()); } catch (ClassNotFoundException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find database backend: " + e.getMessage()); } catch (TemplateException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Template error: " + e.getMessage()); } catch (BackendException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error: " + e.getMessage()); } catch (PluginException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Rendering error: " + e.getMessage()); } } else { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); resp.setHeader("WWW-Authenticate", "Basic realm=\"databaseWiki\""); } }
From source file:io.wcm.testing.mock.aem.builder.ContentBuilder.java
/** * Adds a tag definition./*from w ww .j av a2 s . c o m*/ * @param tagId Tag ID. May include namespace (separated by ":"). May include nested levels (separated by "/"). * @return Tag */ public Tag tag(String tagId) { TagManager tagManager = resourceResolver.adaptTo(TagManager.class); String tagTitle = ResourceUtil.getName(StringUtils.substringAfter(tagId, ":")); try { return tagManager.createTag(tagId, tagTitle, null, true); } catch (AccessControlException | InvalidTagFormatException ex) { throw new RuntimeException("Unable to create tag: " + tagId, ex); } }
From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java
private LookupResult lookupDomainImage(HttpServletRequest request, URL targetUrl, String domainId) { String targetPath = targetUrl.getPath(); URL fileUrl = null;//from w ww.j ava 2 s .com try { WebTopApp wta = WebTopApp.get(request); String remainingPath = StringUtils.substringAfter(targetPath, "images/"); if (StringUtils.isBlank(remainingPath)) throw new NotFoundException(); String imagesPath = wta.getImagesPath(domainId); File file = new File(imagesPath + remainingPath); if (!file.exists()) throw new NotFoundException(); fileUrl = file.toURI().toURL(); Resource resFile = getFile(wta, fileUrl); return new StaticFile(fileUrl.toString(), getMimeType(targetPath), ClientCaching.NO, resFile); } catch (ForbiddenException ex) { return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); } catch (MalformedURLException | NotFoundException ex) { return new Error(HttpServletResponse.SC_NOT_FOUND, "Not Found"); } catch (InternalServerException ex) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } catch (ServletException ex) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } }