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

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

Introduction

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

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:com.github.juanmf.java2plant.Parser.java

private static Collection<? extends Class<?>> getPackageTypes(String packageToPase, Collection<URL> urls) {
    Set<Class<?>> classes = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setScanners(new SubTypesScanner(false /* exclude Object.class */), new ResourcesScanner(),
                    new TypeElementsScanner())
            .setUrls(urls).filterInputsBy(
                    new FilterBuilder().include(FilterBuilder.prefix(packageToPase)).exclude("java.*")));

    Set<String> types;
    types = reflections.getStore().get("TypeElementsScanner").keySet();
    for (String type : types) {
        Class<?> aClass = TypesHelper.loadClass(type, CLASS_LOADER);
        boolean wantedElement = StringUtils.startsWith(type, packageToPase);
        if (null != aClass && wantedElement) {
            System.out.println("looking up for type: " + type);
            classes.add(aClass);//from   w w w.  j  ava  2s. c om
        }
    }
    return classes;
}

From source file:gobblin.util.ConfigUtils.java

/**
 * Finds a list of properties whose keys are complete prefix of other keys. This function is
 * meant to be used during conversion from Properties to typesafe Config as the latter does not
 * support this scenario./*from  w ww .j a  v  a 2s .  com*/
 * @param     properties      the Properties collection to inspect
 * @param     keyPrefix       an optional key prefix which limits which properties are inspected.
 * */
public static Set<String> findFullPrefixKeys(Properties properties, Optional<String> keyPrefix) {
    TreeSet<String> propNames = new TreeSet<>();
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String entryKey = entry.getKey().toString();
        if (StringUtils.startsWith(entryKey, keyPrefix.or(StringUtils.EMPTY))) {
            propNames.add(entryKey);
        }
    }

    Set<String> result = new HashSet<>();
    String lastKey = null;
    Iterator<String> sortedKeysIter = propNames.iterator();
    while (sortedKeysIter.hasNext()) {
        String propName = sortedKeysIter.next();
        if (null != lastKey && propName.startsWith(lastKey + ".")) {
            result.add(lastKey);
        }
        lastKey = propName;
    }

    return result;
}

From source file:de.micromata.genome.jpa.impl.JpaWithExtLibrariesScanner.java

URL fixUrlToOpen(URL url) {
    String surl = url.toString();
    String orgurl = surl;/*from w w w .j  a  v  a2s . c o m*/
    if (surl.endsWith("!/") == true) {
        surl = surl.substring(0, surl.length() - 2);
    }
    if (StringUtils.startsWith(surl, "jar:jar:file:") == true) {
        surl = surl.substring("jar:jar:".length());

    }
    if (StringUtils.startsWith(surl, "jar:file:") == true) {
        surl = surl.substring("jar:".length());
    }
    try {
        URL ret = new URL(surl);
        log.info("Patches url from " + orgurl + " to " + surl);
        return ret;
    } catch (MalformedURLException ex) {
        log.warn("Cannot parse patched url: " + surl + "; " + ex.getMessage());
        return url;
    }

}

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * Returns a typed value for the property name identified
 * or the default value (if unmatched).//from   ww  w . j  a  v  a2 s  .  c o  m
 *
 * @param aSuffix Property name suffix.
 * @param aDefaultValue Default value to return if property
 *                      name is not matched.
 *
 * @return Value of the property.
 */
public int getCfgInteger(String aSuffix, int aDefaultValue) {
    String propertyName;

    if (StringUtils.startsWith(aSuffix, "."))
        propertyName = mCfgPropertyPrefix + aSuffix;
    else
        propertyName = mCfgPropertyPrefix + "." + aSuffix;

    return mAppMgr.getInt(propertyName, aDefaultValue);
}

From source file:io.wcm.handler.url.impl.UrlHandlerImpl.java

String externalizeResourceUrl(final String url, final Resource targetResource, final UrlMode urlMode) {

    // check for empty path
    if (StringUtils.isEmpty(url)) {
        return null;
    }// w w w. j av  a2s.c o m

    // do not externalize urls again that are already externalized
    if (Externalizer.isExternalized(url)) {
        return url;
    }

    // try to resolve the target resource from url/path if it was not given initially (only below /content)
    Resource resource = targetResource;
    if (resource == null && StringUtils.startsWith(url, "/content/")) {
        resource = resolver.resolve(url); // accept NonExistingResource as well
    }

    // apply sling mapping when externalizing URLs
    String externalizedUrl = Externalizer.externalizeUrl(url, resolver, request);

    // add resource URL prefix (scheme/hostname or integrator placeholder) if required
    String resourceUrlPrefix = getResourceUrlPrefix(urlMode, resource);
    externalizedUrl = StringUtils.defaultString(resourceUrlPrefix) + externalizedUrl; //NOPMD

    return externalizedUrl;
}

From source file:com.ottogroup.bi.streaming.operator.json.decode.Base64ContentDecoder.java

/**
 * Decodes the provided {@link Base64} encoded string. Prior decoding a possibly existing prefix is removed from the encoded string.
 * The result which is received from {@link Decoder#decode(byte[])} as array of bytes is converted into a string representation which
 * follows the given encoding //from   ww w  .  ja va  2s .  c o m
 * @param base64EncodedString
 *          The {@link Base64} encoded string
 * @param noValuePrefix
 *          An optional prefix attached to string after encoding (eg to mark it as base64 value) which must be removed prior decoding
 * @param encoding
 *          The encoding applied on converting the resulting byte array into a string representation  
 * @return
 */
protected String decodeBase64(final String base64EncodedString, final String noValuePrefix,
        final String encoding) throws UnsupportedEncodingException {

    // if the base64 encoded string is either empty or holds only the prefix that must be removed before decoding, the method returns an empty string
    if (StringUtils.isBlank(base64EncodedString)
            || StringUtils.equalsIgnoreCase(base64EncodedString, noValuePrefix))
        return "";

    // remove optional prefix and decode - if the prefix does not exist, simply decode the input
    byte[] result = null;
    if (StringUtils.startsWith(base64EncodedString, noValuePrefix))
        result = Base64.getDecoder().decode(StringUtils.substring(base64EncodedString, noValuePrefix.length()));
    else
        result = Base64.getDecoder().decode(base64EncodedString);

    // if the result array is either null or empty the method returns an empty string
    if (result == null || result.length < 1)
        return "";

    // otherwise: the method tries to convert the array into a proper string representation following the given encoding
    return new String(result, (StringUtils.isNotBlank(encoding) ? encoding : "UTF-8"));
}

From source file:ke.co.tawi.babblesms.server.servlet.sms.callback.Callback.java

/**     
 * @param request //www.  jav  a2  s .c  om
 * @param response 
 * @throws ServletException, IOException     
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DateTimeFormatter timeFormatter = ISODateTimeFormat.dateTimeNoMillis();

    String callbackType = request.getParameter("callbackType");
    String messageId;
    LocalDateTime datetime;

    switch (callbackType) {

    case "status": // A notification of an SMS Status change
        messageId = request.getParameter("messageId");

        datetime = timeFormatter.parseLocalDateTime(request.getParameter("datetime"));
        String status = request.getParameter("status");

        OutgoingLog log = outgoingLogDAO.get(messageId);
        log.setLogTime(datetime.toDate());
        log.setMessagestatusuuid(dlrstatusMap.get(status));

        outgoingLogDAO.put(log);

        break;

    case "incomingSms":
        String network = request.getParameter("network").toLowerCase();
        datetime = timeFormatter.parseLocalDateTime(request.getParameter("datetime"));

        IncomingLog incomingLog = new IncomingLog();
        incomingLog.setDestination(request.getParameter("destination"));
        incomingLog.setUuid(request.getParameter("messageId"));
        incomingLog.setMessage(request.getParameter("message"));
        incomingLog.setLogTime(datetime.toDate());
        incomingLog.setNetworkUuid(networkMap.get(network));

        // The source saved in the address book may begin with "07"
        // but the one received for Kenya would begin with "254"
        // We have to reconcile the two
        String source = request.getParameter("source");

        String phoneNum = "";
        if (StringUtils.startsWith(source, "254")) {
            phoneNum = "07" + StringUtils.substring(source, 4);
        }

        if (phoneDAO.getPhones(phoneNum).size() > 0) {
            incomingLog.setOrigin(phoneNum);

        } else {
            incomingLog.setOrigin(source);
        }

        // Determine the account that it is destined for
        // This assumes that the same shortcode number cannot
        // be owned by multiple accounts
        for (Shortcode shortcode : shortcodeList) {
            if (shortcode.getCodenumber().equals(incomingLog.getDestination())) {
                incomingLog.setRecipientUuid(shortcode.getAccountuuid());
                break;
            }
        }

        incomingLogDAO.putIncomingLog(incomingLog);
        break;
    }

}

From source file:com.nridge.connector.common.con_com.publish.PSolr.java

/**
 * Returns a typed value for the property name identified
 * or the default value (if unmatched).//from ww  w. java  2 s. co m
 *
 * @param aSuffix Property name suffix.
 * @param aDefaultValue Default value to return if property
 *                      name is not matched.
 *
 * @return Value of the property.
 */
private long getCfgLong(String aSuffix, long aDefaultValue) {
    String propertyName;

    if (StringUtils.startsWith(aSuffix, "."))
        propertyName = mCfgPropertyPrefix + aSuffix;
    else
        propertyName = mCfgPropertyPrefix + "." + aSuffix;

    return mAppMgr.getLong(propertyName, aDefaultValue);
}

From source file:com.glaf.dts.bean.TransformBean.java

public boolean transformQueryToTable(String queryId) {
    logger.debug("----------------------transformQueryToTable---------");
    boolean result = true;
    QueryDefinition queryDefinition = getQueryDefinitionService().getQueryDefinition(queryId);
    String tableName = queryDefinition.getTargetTableName();
    if (StringUtils.isNotEmpty(tableName)) {
        tableName = tableName.toLowerCase();
        if (StringUtils.startsWith(tableName, "mx_") || StringUtils.startsWith(tableName, "sys_")
                || StringUtils.startsWith(tableName, "act_") || StringUtils.startsWith(tableName, "jbpm_")) {
            return false;
        }// w  ww  .j  a  v  a2s  .  co  m
        MxTransformManager manager = new MxTransformManager();
        TableDefinition tableDefinition = null;
        if (!StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")) {
            try {
                tableDefinition = manager.toTableDefinition(queryDefinition);
                tableDefinition.setTableName(tableName);
                tableDefinition.setType("DTS");
                tableDefinition.setNodeId(queryDefinition.getNodeId());
                TransformTable tbl = new TransformTable();
                tbl.createOrAlterTable(tableDefinition);
            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error(ex);
            }
        }

        Long databaseId = queryDefinition.getDatabaseId();
        TransformTable transformTable = new TransformTable();
        try {
            Database db = getDatabaseService().getDatabaseById(databaseId);
            if (db != null) {
                transformTable.transformQueryToTable(tableName, queryDefinition.getId(), db.getName());
            } else {
                transformTable.transformQueryToTable(tableName, queryDefinition.getId(),
                        Environment.DEFAULT_SYSTEM_NAME);
            }
        } catch (Exception ex) {
            result = false;
            ex.printStackTrace();
            logger.error(ex);
        }
    }

    return result;
}

From source file:com.glaf.dts.web.rest.MxTableResource.java

@POST
@Path("/deleteTable")
@ResponseBody/*from ww w.ja  va  2  s  .  c  o  m*/
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public byte[] deleteTable(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    String tableName = request.getParameter("tableName");
    String tableName_enc = request.getParameter("tableName_enc");
    if (StringUtils.isNotEmpty(tableName_enc)) {
        tableName = RequestUtils.decodeString(tableName_enc);
    }
    if (StringUtils.isNotEmpty(tableName)) {
        tableName = tableName.toLowerCase();
        if (StringUtils.startsWith(tableName, "mx_") || StringUtils.startsWith(tableName, "sys_")
                || StringUtils.startsWith(tableName, "jbpm_") || StringUtils.startsWith(tableName, "act_")) {
            return ResponseUtils.responseJsonResult(false);
        }
        tableDefinitionService.deleteTable(tableName);
        return ResponseUtils.responseJsonResult(true);
    }
    return ResponseUtils.responseJsonResult(false);
}