Example usage for org.apache.commons.lang3 StringUtils substringBefore

List of usage examples for org.apache.commons.lang3 StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils substringBefore.

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:io.wcm.handler.url.suffix.impl.UrlSuffixUtil.java

/**
 * Decode key//from ww w .ja  v a2s  .c  o m
 * @param suffixPart Suffix part
 * @return Decoded key
 */
public static String decodeKey(String suffixPart) {
    // key is the part *before* KEY_VALUE_DELIMITER
    String key = StringUtils.substringBefore(suffixPart, Character.toString(KEY_VALUE_DELIMITER));

    // un-escape special chars
    for (Map.Entry<String, String> entry : SPECIAL_CHARS_ESCAPEMAP.entrySet()) {
        key = StringUtils.replace(key, entry.getValue(), entry.getKey());
    }

    return key;
}

From source file:com.neatresults.mgnltweaks.ui.action.SaveConfigAddNodeDialogAction.java

@Override
public void execute() throws ActionExecutionException {
    // First Validate
    validator.showValidation(true);// w w  w  .  ja  v  a  2 s .com
    if (validator.isValid()) {

        // we support only JCR item adapters
        if (!(item instanceof JcrItemAdapter)) {
            return;
        }

        // don't save if no value changes occurred on adapter
        if (!((JcrItemAdapter) item).hasChangedProperties()) {
            return;
        }

        if (item instanceof AbstractJcrNodeAdapter) {
            // Saving JCR Node, getting updated node first
            AbstractJcrNodeAdapter nodeAdapter = (AbstractJcrNodeAdapter) item;
            try {
                String nodePath = ((String) nodeAdapter.getItemProperty("path").getValue()).trim();
                String nodeType = NodeTypes.ContentNode.NAME;
                if (nodeAdapter.getItemProperty("nodeType") != null) {
                    nodeType = ((String) nodeAdapter.getItemProperty("nodeType").getValue()).trim();
                }
                String parentNodeType = NodeTypes.Content.NAME;
                if (nodeAdapter.getItemProperty("parentNodeType") != null) {
                    parentNodeType = ((String) nodeAdapter.getItemProperty("parentNodeType").getValue()).trim();
                }
                Node node = nodeAdapter.getJcrItem();
                String propertyName = null;
                if (nodePath.contains("@")) {
                    propertyName = StringUtils.substringAfter(nodePath, "@").trim();
                    if (StringUtils.isEmpty(propertyName)) {
                        propertyName = null;
                    }
                    nodePath = StringUtils.substringBefore(nodePath, "@");
                }
                String nodeName = nodePath;
                if (nodePath.contains("/")) {
                    nodeName = StringUtils.substringAfterLast(nodePath, "/");
                    String parentPath = StringUtils.substringBeforeLast(nodePath, "/");
                    for (String parentName : parentPath.split("/")) {
                        node = JcrUtils.getOrAddNode(node, parentName, parentNodeType);
                    }
                }
                node = node.addNode(nodeName, nodeType);
                if (propertyName != null) {
                    String value = "";
                    if (nodeAdapter.getItemProperty("value") != null) {
                        value = ((String) nodeAdapter.getItemProperty("value").getValue());
                    }
                    node.setProperty(propertyName, value == null ? "" : value);
                }
                node.getSession().save();
                Location location = subAppContext.getLocation();
                String param = location.getParameter();
                param = node.getPath() + (propertyName != null ? ("@" + propertyName) : "") + ":"
                        + StringUtils.substringAfter(param, ":");
                location = new DefaultLocation(location.getAppType(), location.getAppName(),
                        location.getSubAppId(), param);
                adminEventBus.fireEvent(new LocationChangedEvent(location));
            } catch (RepositoryException e) {
                log.error("Could not save changes to node", e);
            }
            callback.onSuccess(getDefinition().getName());
        } else if (item instanceof JcrPropertyAdapter) {
            super.execute();
        }
    } else {
        log.debug("Validation error(s) occurred. No save performed.");
    }
}

From source file:com.bellman.bible.service.common.CommonUtils.java

public static String limitTextLength(String text, int maxLength, boolean singleLine) {
    if (text != null) {
        int origLength = text.length();

        if (singleLine) {
            // get first line but limit length in case there are no line breaks
            text = StringUtils.substringBefore(text, "\n");
        }/*www.j a va2s  .  c  om*/

        if (text.length() > maxLength) {
            // break on a space rather than mid-word
            int cutPoint = text.indexOf(" ", maxLength);
            if (cutPoint >= maxLength) {
                text = text.substring(0, cutPoint + 1);
            }
        }

        if (text.length() != origLength) {
            text += ELLIPSIS;
        }
    }
    return text;
}

From source file:com.erudika.para.rest.Signer.java

/**
 * Validates the signature of the request.
 * @param incoming the incoming HTTP request containing a signature
 * @param secretKey the app's secret key
 * @return true if the signature is valid
 *//*from   w w w  .jav a  2s  .  c  o m*/
public boolean isValidSignature(HttpServletRequest incoming, String secretKey) {
    if (incoming == null || StringUtils.isBlank(secretKey)) {
        return false;
    }
    String auth = incoming.getHeader(HttpHeaders.AUTHORIZATION);
    String givenSig = StringUtils.substringAfter(auth, "Signature=");
    String sigHeaders = StringUtils.substringBetween(auth, "SignedHeaders=", ",");
    String credential = StringUtils.substringBetween(auth, "Credential=", ",");
    String accessKey = StringUtils.substringBefore(credential, "/");

    if (StringUtils.isBlank(auth)) {
        givenSig = incoming.getParameter("X-Amz-Signature");
        sigHeaders = incoming.getParameter("X-Amz-SignedHeaders");
        credential = incoming.getParameter("X-Amz-Credential");
        accessKey = StringUtils.substringBefore(credential, "/");
    }

    Request<?> awsReq = buildAWSRequest(incoming, new HashSet<String>(Arrays.asList(sigHeaders.split(";"))));
    sign(awsReq, accessKey, secretKey);

    String auth2 = awsReq.getHeaders().get(HttpHeaders.AUTHORIZATION);
    String recreatedSig = StringUtils.substringAfter(auth2, "Signature=");

    return StringUtils.equals(givenSig, recreatedSig);
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

protected Credentials buildNTCredentials(final String userPart, final String password)
        throws InitializationException {
    final String domain = StringUtils.substringBefore(userPart, "\\");
    final String username = StringUtils.substringAfter(userPart, "\\");
    return new NTCredentials(username, password, getLocalHostName(), domain);
}

From source file:net.sf.jabb.util.text.MatchingDefinition.java

/**
 * Loads definitions from properties. For example:
 * <br>name1.expression=.../*  w w w .ja va  2s.  c  o  m*/
 * <br>name1.example.1=...
 * <br>name1.example.2=...
 * <br>...
 * <br>name1.attachment=...
 * <br>
 * <br>name2.expression=...
 * <br>name2.example.1=...
 * <br>name2.example.2=...
 * <br>...
 * <br>name2.attachment=...
 * <br>...
 * @param props
 * @return
 */
static public List<MatchingDefinition> load(Map<? extends Object, ? extends Object> props) {
    List<MatchingDefinition> result = new LinkedList<MatchingDefinition>();

    Map<String, Map<String, Object>> defs = new PutIfAbsentMap<String, Map<String, Object>>(
            new HashMap<String, Map<String, Object>>(), new MapValueFactory<String, Map<String, Object>>() {
                @Override
                public Map<String, Object> createValue(String key) {
                    return new HashMap<String, Object>();
                }
            });

    // classify
    for (Map.Entry<? extends Object, ? extends Object> entry : props.entrySet()) {
        String key = (String) entry.getKey();
        String name = StringUtils.substringBefore(key, ".");
        String postfix = StringUtils.substringAfter(key, ".");
        defs.get(name).put(postfix, entry.getValue());
    }

    // process
    for (Map.Entry<String, Map<String, Object>> entry : defs.entrySet()) {
        Map<String, Object> def = entry.getValue();
        String expression = null;
        Object attachment = null;
        List<String> examples = new LinkedList<String>();
        for (Map.Entry<String, Object> defEntry : def.entrySet()) {
            String key = defEntry.getKey();
            Object value = defEntry.getValue();
            if (key != null) {
                if (key.equalsIgnoreCase("expression")) {
                    expression = (String) value;
                } else if (key.startsWith("example")) {
                    examples.add((String) value);
                } else if (key.equalsIgnoreCase("attachment")) {
                    attachment = value;
                } else {
                    // ignore
                }
            }
        }
        if (expression != null) {
            MatchingDefinition mDef = new MatchingDefinition();
            mDef.setRegularExpression(expression);
            mDef.setExactMatchExamples(examples);
            mDef.setAttachment(attachment);
            result.add(mDef);
        }
    }

    return result;
}

From source file:fi.csc.kapaVirtaAS.WSDLManipulator.java

public void generateVirtaKapaWSDL() throws Exception {
    // Fetch current WSDL-file
    File inputFile = new File("opiskelijatiedot.wsdl");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(inputFile);
    doc.setXmlVersion("1.0");
    doc.getDocumentElement().normalize();

    // Manipulate WSDL to meet the requirements of xroad

    // Root element <wsdl:definitions> attribute manipulations
    Element root = doc.getDocumentElement();
    root.setAttribute("xmlns:" + conf.getXroadSchemaPrefixForWSDL(), conf.getXroadSchema());
    root.setAttribute("xmlns:" + conf.getXroadIdSchemaPrefixForWSDL(), conf.getXroadIdSchema());

    root = replaceAttribute(root, "xmlns:tns", conf.getAdapterServiceSchema());
    root = replaceAttribute(root, "targetNamespace", conf.getAdapterServiceSchema());

    // Schema elements <xs:schema> attribute manipulations
    NodeList schemas = root.getElementsByTagName("xs:schema");

    for (int i = 0; i < schemas.getLength(); ++i) {
        Node schema = schemas.item(i);
        if (schema != null) {
            NamedNodeMap schemaAttributes = schema.getAttributes();
            if (schemaAttributes != null && schemaAttributes.getNamedItem("xmlns:virtaluku") != null) {
                schemaAttributes.getNamedItem("xmlns:virtaluku").setTextContent(conf.getAdapterServiceSchema());

                if (schemaAttributes != null && schemaAttributes.getNamedItem("targetNamespace") != null) {
                    schemaAttributes.getNamedItem("targetNamespace")
                            .setTextContent(conf.getAdapterServiceSchema());
                }//from w ww  . j  av  a 2 s . co m

                Element el = (Element) schema.appendChild(doc.createElement("xs:import"));
                el.setAttribute("id", conf.getXroadSchemaPrefixForWSDL());
                el.setAttribute("namespace", conf.getXroadSchema());
                el.setAttribute("schemaLocation", conf.getXroadSchema());

                // Remove Request part from xs:element -elements
                NodeList elementsInSchema = schema.getChildNodes();
                for (int j = 0; j < elementsInSchema.getLength(); ++j) {
                    Element el1 = (Element) elementsInSchema.item(j);
                    if (el1.getNodeName() == "xs:element") {
                        replaceAttribute(el1, "name",
                                StringUtils.substringBefore(el1.getAttribute("name"), "Request"));
                    }
                }
            }

        }
    }

    // Append xroad request headers
    Element xroadReqHeadersElement = doc.createElement("wsdl:message");
    xroadReqHeadersElement.setAttribute("name", "requestheader");

    for (String xroadHeader : conf.getXroadHeaders()) {
        Element reqHeader = doc.createElement("wsdl:part");
        reqHeader.setAttribute("name", xroadHeader);
        reqHeader.setAttribute("element", conf.getXroadSchemaPrefixForWSDL() + ":" + xroadHeader);
        xroadReqHeadersElement.appendChild(reqHeader);
    }

    root.appendChild(xroadReqHeadersElement);

    NodeList childrenList = root.getChildNodes();
    for (int i = 0; i < childrenList.getLength(); ++i) {

        if (childrenList.item(i).getNodeName().contains(":binding")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    Element el1 = (Element) binding.item(j)
                            .appendChild(doc.createElement(conf.getXroadIdSchemaPrefixForWSDL() + ":version"));
                    el1.setTextContent(conf.getVirtaVersionForXRoad());

                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {

                        // Append xroad wsdl:binding operation headers
                        if (child.getNodeName().contains(":input") || child.getNodeName().contains(":output")) {
                            Element el = (Element) child;
                            for (String xroadHeader : conf.getXroadHeaders()) {
                                el.appendChild(soapHeader(doc.createElement("soap:header"), "tns:requestheader",
                                        xroadHeader, "literal"));
                            }
                        }

                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
            // Remove Request from wsdl:message > wsdl:part element so that can see element
        } else if (childrenList.item(i).getNodeName().contains(":message") && childrenList.item(i)
                .getAttributes().getNamedItem("name").getNodeValue().contains("Request")) {
            Element part = (Element) childrenList.item(i).getFirstChild().getNextSibling();
            replaceAttribute(part, "element",
                    StringUtils.substringBefore(part.getAttribute("element"), "Request"));
        }

        // Change wsdl input names to meet XRoad standard
        if (childrenList.item(i).getNodeName().contains(":portType")) {
            NodeList binding = childrenList.item(i).getChildNodes();
            for (int j = 0; j < binding.getLength(); ++j) {
                if (binding.item(j).getNodeName().contains(":operation")) {
                    for (Node child = binding.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":input")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "name",
                                    StringUtils.substringBefore(el.getAttribute("name"), "Request"));
                        }
                    }
                }
            }
        }

        // Append kapaVirtaAS service address
        if (childrenList.item(i).getNodeName().contains(":service")) {
            NodeList service = childrenList.item(i).getChildNodes();
            for (int j = 0; j < service.getLength(); ++j) {
                if (service.item(j).getNodeName().contains(":port")) {
                    for (Node child = service.item(j).getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeName().contains(":address")) {
                            Element el = (Element) child;
                            replaceAttribute(el, "location", conf.getAdapterServiceSOAPURL());
                        }
                    }
                }
            }
        }
    }

    // Write manipulated WSDL to file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(conf.getAdapterServiceWSDLPath() + "/kapavirta_as.wsdl"));
    transformer.transform(source, result);
}

From source file:com.xpn.xwiki.web.XWikiServletURLFactory.java

/**
 * @param context the XWiki context used to access the request object
 * @return the proxy host, if we are behind one, otherwise the host of the URL used to make the current request
 *//*from   w  w w . j  av  a 2s  .c  om*/
private String getHost(XWikiContext context) {
    URL url = context.getURL();

    // Check reverse-proxy mode (e.g. Apache's mod_proxy_http).
    String proxyHost = StringUtils.substringBefore(context.getRequest().getHeader("x-forwarded-host"), ",");
    if (!StringUtils.isEmpty(proxyHost)) {
        return proxyHost;
    }
    // If the reverse proxy does not support the x-forwarded-host parameter
    // we allow the user to force the the host name by using the xwiki.home param.
    final URL homeParam = getXWikiHomeParameter(context);
    if (homeParam != null && context.isMainWiki()) {
        url = homeParam;
    }

    return url.getHost() + (url.getPort() < 0 ? "" : (":" + url.getPort()));
}

From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java

private void deregisterScalableTargets(Set<String> resources, String account, String region) {
    NetflixAmazonCredentials credentials = (NetflixAmazonCredentials) accountCredentialsProvider
            .getCredentials(account);/*from  w  w  w.java 2 s .  c  o m*/
    AWSApplicationAutoScaling autoScaling = amazonClientProvider.getAmazonApplicationAutoScaling(credentials,
            region, false);

    Map<String, Set<String>> resourceMap = new HashMap<>();
    for (String resource : resources) {
        String namespace = StringUtils.substringBefore(resource, "/");
        String service = StringUtils.substringAfter(resource, "/");
        if (resourceMap.containsKey(namespace)) {
            resourceMap.get(namespace).add(service);
        } else {
            Set<String> serviceSet = new HashSet<>();
            serviceSet.add(service);
            resourceMap.put(namespace, serviceSet);
        }
    }

    Set<DeregisterScalableTargetRequest> deregisterRequests = new HashSet<>();
    for (String namespace : resourceMap.keySet()) {
        String nextToken = null;
        do {
            DescribeScalableTargetsRequest request = new DescribeScalableTargetsRequest()
                    .withServiceNamespace(namespace).withResourceIds(resourceMap.get(namespace));

            if (nextToken != null) {
                request.setNextToken(nextToken);
            }

            DescribeScalableTargetsResult result = autoScaling.describeScalableTargets(request);

            deregisterRequests.addAll(result.getScalableTargets().stream()
                    .map(scalableTarget -> new DeregisterScalableTargetRequest()
                            .withResourceId(scalableTarget.getResourceId())
                            .withScalableDimension(scalableTarget.getScalableDimension())
                            .withServiceNamespace(scalableTarget.getServiceNamespace()))
                    .collect(Collectors.toSet()));

            nextToken = result.getNextToken();
        } while (nextToken != null && nextToken.length() != 0);
    }

    for (DeregisterScalableTargetRequest request : deregisterRequests) {
        autoScaling.deregisterScalableTarget(request);
    }
}

From source file:com.thruzero.common.core.utils.ExceptionUtilsExt.java

public static String findMethodAfterClassFromTrace(final Class<?> clazz) {
    String result = findTraceAfter(clazz);
    result = StringUtils.substringBefore(result, "(");
    return StringUtils.substringAfterLast(result, ".");
}