Example usage for org.apache.commons.lang StringUtils substringBetween

List of usage examples for org.apache.commons.lang StringUtils substringBetween

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBetween.

Prototype

public static String substringBetween(String str, String open, String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:org.beanfuse.utils.multilevelseq.SeqPattern.java

public SeqPattern(SeqNumStyle seqStyle, String pattern) {
    this.seqNumStyle = seqStyle;
    this.pattern = pattern;
    String remainder = pattern;/*from  www. ja v a2 s  .  c o m*/
    while (StringUtils.isNotEmpty(remainder)) {
        String p = StringUtils.substringBetween(remainder, "{", "}");
        if (StringUtils.isEmpty(p)) {
            break;
        }
        if (NumberUtils.isDigits(p)) {
            params.add(new Integer(p));
        }
        remainder = StringUtils.substringAfter(remainder, "{" + p + "}");
    }

    Collections.sort(params);
    this.level = ((Integer) params.get(params.size() - 1)).intValue();
    params.remove(params.size() - 1);
}

From source file:org.beangle.commons.comparators.PropertyComparator.java

/**
 * new OrderedBeanComparator("id") or<br>
 * new OrderedBeanComparator("name desc"); new
 * OrderedBeanComparator("[0].name desc");
 * //from  ww  w  . j a v a  2s  . c om
 * @param cmpStr
 */
public PropertyComparator(final String cmpStr) {
    if (StringUtils.isEmpty(cmpStr)) {
        return;
    }

    if (StringUtils.contains(cmpStr, ',')) {
        throw new RuntimeException(
                "PropertyComparator don't suport comma based order by." + " Use MultiPropertyComparator ");
    }
    cmpWhat = cmpStr.trim();
    // ?[]?
    if ('[' == cmpWhat.charAt(0)) {
        index = NumberUtils.toInt(StringUtils.substringBetween(cmpWhat, "[", "]"));
        cmpWhat = StringUtils.substringAfter(cmpWhat, "]");
        if (cmpWhat.length() > 0 && '.' == cmpWhat.charAt(0)) {
            cmpWhat = cmpWhat.substring(1);
        }
    }
    // ??
    asc = true;
    if (StringUtils.contains(cmpWhat, ' ')) {
        if (StringUtils.contains(cmpWhat, " desc")) {
            asc = false;
        }
        cmpWhat = cmpWhat.substring(0, cmpWhat.indexOf(' '));
    }
    stringComparator = new CollatorStringComparator(asc);
}

From source file:org.beangle.ems.dictionary.service.impl.SeqCodeGenerator.java

/**
 * ???/*from www . j a  v a2  s  .  c om*/
 */
@SuppressWarnings("unchecked")
public String gen(CodeFixture fixture) {
    // ??
    String script = fixture.getScript();
    CodeScript codeScript = null;
    if (null == script) {
        codeScript = getCodeScript(EntityUtils.getEntityClassName(fixture.getEntity().getClass()));
        if (null == codeScript) {
            return null;
        }
        script = codeScript.getScript();
        try {
            String code = (String) PropertyUtils.getProperty(fixture.getEntity(), codeScript.getAttr());
            if (isValidCode(code)) {
                return code;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    int seqLength = -1;
    // ???seq[x]
    if (StringUtils.contains(script, SEQ)) {
        seqLength = NumberUtils.toInt(StringUtils.substringBetween(script, SEQ + "[", "]"));

        script = StringUtils.replace(script,
                SEQ + "[" + StringUtils.substringBetween(script, SEQ + "[", "]") + "]", SEQ);
    }
    fixture.setScript(script);
    String code = super.gen(fixture);
    List<String> seqs = CollectUtils.newArrayList();
    if (-1 != seqLength) {
        try {
            OqlBuilder<?> builder = OqlBuilder.from(Class.forName(codeScript.getCodeClassName()), "entity");
            builder.select("select substr(entity." + codeScript.getAttr() + "," + (code.indexOf(SEQ) + 1) + ","
                    + seqLength + ")");
            builder.where(" entity." + codeScript.getAttr() + " like :codeExample",
                    StringUtils.replace(code, SEQ, "%"));
            builder.where("length(entity." + codeScript.getAttr() + ")="
                    + (code.length() - SEQ.length() + seqLength));
            seqs = (List<String>) entityDao.search(builder);
            Collections.sort(seqs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        synchronized (this) {
            int newSeqNo = 0;
            for (Iterator<String> iter = seqs.iterator(); iter.hasNext();) {
                String seqNo = iter.next();
                if (NumberUtils.toInt(seqNo) - newSeqNo >= 2) {
                    break;
                } else {
                    newSeqNo = NumberUtils.toInt(seqNo);
                }
            }
            newSeqNo++;
            String seqNo = String.valueOf(newSeqNo);
            if (0 != seqLength) {
                seqNo = StringUtils.repeat("0", seqLength - seqNo.length()) + newSeqNo;
            }
            code = StringUtils.replace(code, SEQ, seqNo);
        }
    }
    return code;
}

From source file:org.betaconceptframework.astroboa.model.impl.query.xpath.XPathUtils.java

public static String generateJcrPathForPropertyPath(String propertyPath,
        boolean lastPropertyInPathRepresentsASimpleProperty) {

    if (StringUtils.isNotBlank(propertyPath)) {
        //It is high likely that property may contain function names. In this case
        //remove functions from property, create appropriate xpath for property and then
        //concatenate function again
        String functionName = getFunctionNameFromProperty(propertyPath);

        String tempPropertyPath = propertyPath;

        if (StringUtils.isNotBlank(functionName)) {
            //Remove function name and its parenthesis
            tempPropertyPath = StringUtils.substringBetween(propertyPath,
                    functionName + CmsConstants.LEFT_PARENTHESIS, CmsConstants.RIGHT_PARENTHESIS);
        }/*from   w w  w  .ja va2s.  c  o m*/

        //Property name is *. No extra manipulation 
        if (CmsConstants.ANY_NAME.equals(tempPropertyPath.trim())) {
            return attachFunctionNameToProperty(functionName, tempPropertyPath);
        }

        //Since in astroboa api a property path contains one or more
        //property names delimited with '.', these periods must be replaced
        //by path delimiter recognized by JCR
        if (tempPropertyPath.contains(CmsConstants.PERIOD_DELIM)) {
            tempPropertyPath = StringUtils.replace(tempPropertyPath, CmsConstants.PERIOD_DELIM,
                    CmsConstants.FORWARD_SLASH);
        }

        //Do not add any '@' character in case the property participates in jcr:contains
        //function
        if (!lastPropertyInPathRepresentsASimpleProperty) {
            return attachFunctionNameToProperty(functionName, ISO9075.encodePath(tempPropertyPath));
        }

        //Finally must add "@" character to the last property in path 
        //to denote that this is an attribute
        if (!tempPropertyPath.contains(CmsConstants.AT_CHAR)) {
            //Make sure all property names are valid XML Names
            tempPropertyPath = ISO9075.encodePath(tempPropertyPath);

            if (tempPropertyPath.contains(CmsConstants.FORWARD_SLASH)) {
                //Last property in path is always an attribute
                tempPropertyPath = CmsUtils.replaceLast(CmsConstants.FORWARD_SLASH,
                        CmsConstants.FORWARD_SLASH + CmsConstants.AT_CHAR, tempPropertyPath);
            } else
                //Property path contains one property
                tempPropertyPath = CmsConstants.AT_CHAR + tempPropertyPath;
        }

        //Finally encode any names in property path which start with a digit 
        return attachFunctionNameToProperty(functionName, tempPropertyPath);
    }

    return "";
}

From source file:org.betaconceptframework.astroboa.util.PropertyExtractor.java

private String retrieveIdentifierOrIndexFromPath(String pathPart) {
    if (StringUtils.isBlank(pathPart)) {
        return null;
    }/* w  w  w  .  jav  a 2  s. co m*/

    return StringUtils.substringBetween(pathPart, CmsConstants.LEFT_BRACKET, CmsConstants.RIGHT_BRACKET);
}

From source file:org.cleverbus.admin.web.msg.MessageLogParser.java

@Nullable
private String getRequestId(String line) {
    // 2013-05-23 20:22:36,754 [MACHINE_IS_UNDEFINED, ajp-bio-8009-exec-19, /esb/ws/account/v1, 10.10.0.95:72cab819:13ecdbd371c:-7eff, ] DEBUG

    String logHeader = StringUtils.substringBetween(line, "[", "]");
    if (logHeader == null) {
        // no match - the line doesn't contain []
        return null;
    }// w ww .  j av  a 2 s  .c  o  m
    String[] headerParts = StringUtils.split(logHeader, ",");
    String requestId = StringUtils.trim(headerParts[3]);

    // note: if request starts from scheduled job, then there is request ID information
    // 2013-05-27 16:37:25,633 [MACHINE_IS_UNDEFINED, DefaultQuartzScheduler-camelContext_Worker-8, , , ]
    //  WARN  c.c.c.i.c.a.d.RepairMessageServiceDbImpl$2 - The message (msg_id = 372, correlationId = ...

    return StringUtils.trimToNull(requestId);
}

From source file:org.cleverbus.core.alerts.AlertsPropertiesConfiguration.java

/**
 * Initializes configuration from properties.
 *//*from   ww w.j  av  a  2 s  .  c  o  m*/
private void initProps() {
    // example of alert configuration
    //        alerts.900.id=WAITING_MSG_ALERT
    //        alerts.900.limit=0
    //        alerts.900.sql=SELECT COUNT(*) FROM message WHERE state = 'WAITING_FOR_RES'
    //        alerts.900.enabled=true
    //        alerts.900.mail.subject=There are %d message(s) in WAITING_FOR_RESPONSE state for more then %d seconds.
    //        alerts.900.mail.body=Alert: notification about WAITING messages

    // get relevant properties for alerts
    List<String> propNames = new ArrayList<String>();

    Enumeration<?> propNamesEnum = properties.propertyNames();
    while (propNamesEnum.hasMoreElements()) {
        String propName = (String) propNamesEnum.nextElement();

        if (propName.startsWith(ALERT_PROP_PREFIX)) {
            propNames.add(propName);
        }
    }

    // get alert IDs
    Set<String> orders = new HashSet<String>();

    Pattern pattern = Pattern.compile("alerts\\.(\\d+)\\.id");
    for (String propName : propNames) {
        Matcher matcher = pattern.matcher(propName);

        if (matcher.matches()) {
            String order = StringUtils.substringBetween(propName, ALERT_PROP_PREFIX, ".");

            if (orders.contains(order)) {
                throw new IllegalStateException(
                        "Wrong alert's configuration - alert order '" + order + "' was already used.");
            } else {
                orders.add(order);
            }
        }
    }

    // get property values
    Set<String> ids = new HashSet<String>();
    for (String order : orders) {
        String propPrefix = ALERT_PROP_PREFIX + order + ".";

        String id = properties.getProperty(propPrefix + ID_PROP);

        // check if id is unique
        if (ids.contains(id)) {
            throw new IllegalStateException("Wrong alert's configuration - id '" + id + "' is not unique.");
        } else {
            ids.add(id);
        }

        String limit = properties.getProperty(propPrefix + LIMIT_PROP);
        String sql = properties.getProperty(propPrefix + SQL_PROP);

        // check if sql contains count()
        if (!StringUtils.containsIgnoreCase(sql, "count(")) {
            throw new IllegalStateException(
                    "Wrong alert's configuration - SQL clause for id '" + id + "' doesn't contain count().");
        }

        String enabled = properties.getProperty(propPrefix + ENABLED_PROP);
        enabled = enabled == null ? "true" : enabled;

        String subject = properties.getProperty(propPrefix + MAIL_SBJ_PROP);
        String body = properties.getProperty(propPrefix + MAIL_BODY_PROP);

        // add new alert
        try {
            AlertInfo alertInfo = new AlertInfo(id, Long.valueOf(limit), sql, BooleanUtils.toBoolean(enabled),
                    subject, body);

            addAlert(alertInfo);
        } catch (Exception ex) {
            throw new IllegalStateException("Wrong alert's configuration - conversion error", ex);
        }
    }
}

From source file:org.codice.alliance.catalog.transformer.mgmp.MgmpTransformer.java

private List<String> parseCrsInformationFromWktSpecification(List<String> crsCodes) {
    return crsCodes.stream().map(crsCode -> StringUtils.substringBetween(crsCode, ",ID[", "]"))
            .filter(StringUtils::isNotEmpty).map(inf -> inf.replace("\"", "")).map(inf -> inf.replace(',', ':'))
            .collect(Collectors.toList());
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testPassiveLoginPkiFail()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    SecurityManager securityManager = mock(SecurityManager.class);
    when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test"));
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert//  w  w  w. j a  va 2 s  .c o  m
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);
    String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse=",
            "&RelayState");
    responseStr = URLDecoder.decode(responseStr, "UTF-8");
    responseStr = RestSecurity.inflateBase64(responseStr);

    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:AuthnFailed"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testPassiveLoginPkiUnsupportedPost()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiPost;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    SecurityManager securityManager = mock(SecurityManager.class);

    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getSecurityToken()).thenReturn(securityToken);
    //this mock element is what will cause the signature error
    when(securityToken.getToken()).thenReturn(mock(Element.class));
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert//from   www . j a  v  a 2s.co m
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request);
    String responseStr = StringUtils.substringBetween(response.getEntity().toString(),
            "SAMLResponse\" value=\"", "\" />");
    responseStr = new String(Base64.getDecoder().decode(responseStr));

    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:RequestUnsupported"));
}