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

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

Introduction

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

Prototype

public static boolean endsWith(final CharSequence str, final CharSequence suffix) 

Source Link

Document

Check if a CharSequence ends with a specified suffix.

null s are handled without exceptions.

Usage

From source file:com.ottogroup.bi.asap.repository.CachedComponentClassLoader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder/* w  w w.ja va2 s  .c  o  m*/
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {

                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.byteCode.put(jarEntryName, loadBytes(jarInputStream));
                    } else {
                        // ...and add a mapping for resource to jar file as well
                        this.resources.put(jarEntryName, loadBytes(jarInputStream));
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.byteCode.keySet()) {

        try {
            Class<?> c = loadClass(cjf);
            AsapComponent pc = c.getAnnotation(AsapComponent.class);
            if (pc != null) {
                this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                        new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                pc.description()));
                logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name() + ", version="
                        + pc.version() + "]");
                ;
            }
        } catch (Throwable e) {
            //logger.info("Failed to load class '"+cjf+"'. Error: " + e.getMessage());
        }
    }
}

From source file:com.nridge.ds.solr.SolrSchemaXML.java

private String mapFieldType(DataField aField) {
    String fieldType;/*from  ww  w. ja  v  a 2 s  . com*/

    switch (aField.getType()) {
    case Text:
        if ((StringUtils.endsWith(aField.getName(), "_name"))
                || (StringUtils.endsWith(aField.getName(), "_title"))
                || (StringUtils.endsWith(aField.getName(), "_description"))
                || (StringUtils.endsWith(aField.getName(), "_content")))
            fieldType = SOLR_TEXT_FIELD_TYPE_DEFAULT;
        else
            fieldType = "string";
        break;
    case Integer:
        fieldType = "int";
        break;
    case Long:
        fieldType = "long";
        break;
    case Float:
        fieldType = "float";
        break;
    case Double:
        fieldType = "double";
        break;
    case Boolean:
        fieldType = "boolean";
        break;
    case Date:
    case Time:
    case DateTime:
        fieldType = "date";
        break;
    default:
        fieldType = "string";
        break;
    }

    return fieldType;
}

From source file:io.ecarf.core.term.TermUtils.java

License:asdf

/**
 * Split the provided term into 2 parts using the slash a separator. Uses some rules concerning : and ?
 * Some examples:/*from www.  ja v  a 2s.  co m*/
 * <http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=/netahtml/PTO/srchnum.htm&r=1&f=G&l=50&s1=6348648.PN.&OS=PN/6348648&RS=PN/6348648/>
[patft.uspto.gov/netacgi, nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=/netahtml/PTO/srchnum.htm&r=1&f=G&l=50&s1=6348648.PN.&OS=PN/6348648&RS=PN/6348648/]
        
<http://www.honda.lv/>
[www.honda.lv]
        
<http://gmail.com>
[gmail.com]
        
<http://gmail.com:8080/Test?id=test>
[gmail.com:8080, Test?id=test]
        
<http://web.archive.org/web/20051031200142/http:/www.mkaz.com/ebeab/history/>
[web.archive.org/web/20051031200142, http:/www.mkaz.com/ebeab/history/]
        
<http://web.archive.org/web/20051031200142/?http:/www.mkaz.com/ebeab/history/>
[web.archive.org/web/20051031200142, ?http:/www.mkaz.com/ebeab/history/]
        
<http://web.archive.org/web/20051031200142/http:/www.mkaz.com?id=ebeab/history/>
[web.archive.org/web/20051031200142, http:/www.mkaz.com?id=ebeab/history/]
        
<http://www.hel.fi/wps/portal/Helsinki_en/?WCM_GLOBAL_CONTEXT=/en/Helsinki/>
[www.hel.fi/wps/portal/Helsinki_en, ?WCM_GLOBAL_CONTEXT=/en/Helsinki/]
        
<http://dbpedia.org/resource/Team_handball>
[dbpedia.org/resource, Team_handball]
        
<http://dbpedia.org/ontology/wikiPageExternalLink>
[dbpedia.org/ontology, wikiPageExternalLink]
        
<http://www.nfsa.gov.au/blog/2012/09/28/tasmanian-time-capsule/>
[www.nfsa.gov.au/blog/2012/09/28/tasmanian-time-capsule]
        
<http://www.whereis.com/whereis/mapping/renderMapAddress.do?name=&streetNumber=&street=City%20Center&streetType=&suburb=Hobart&state=Tasmania&latitude=-42.881&longitude=147.3265&navId=$01006046X0OL9$&brandId=1&advertiser
Id=&requiredZoomLevel=3>
[www.whereis.com/whereis/mapping, renderMapAddress.do?name=&streetNumber=&street=City%20Center&streetType=&suburb=Hobart&state=Tasmania&latitude=-42.881&longitude=147.3265&navId=$01006046X0OL9$&brandId=1&advertiserId=&re
quiredZoomLevel=3]
        
 * @param term
 * @param splitLocation - the location of the slash
 * @return
 */
public static List<String> splitIntoTwo(String term, boolean hasProtocol, int splitLocation) {

    String path;

    if (hasProtocol) {
        String url = term.substring(1, term.length() - 1);
        path = StringUtils.removeStart(url, TermUtils.HTTP);

        if (path.length() == url.length()) {
            path = StringUtils.removeStart(path, TermUtils.HTTPS);
        }

    } else {
        path = term;
    }

    // remove trailing slash
    if (StringUtils.endsWith(path, URI_SEP_STR)) {
        path = StringUtils.removeEnd(path, URI_SEP_STR);
    }

    //System.out.println(path);
    List<String> parts = new ArrayList<>();

    int slashIdx = path.indexOf(TermUtils.URI_SEP);
    ;

    switch (splitLocation) {

    case 0:
        // the first slash
        break;

    case 1:
        // the second slash
        slashIdx = path.indexOf(TermUtils.URI_SEP, slashIdx + 1);
        break;

    case -1:
    default:
        // the last slash
        slashIdx = path.lastIndexOf(TermUtils.URI_SEP);

        int colonIdx = path.indexOf(':');
        int questionIdx = path.indexOf('?');

        if (((colonIdx > -1) && (slashIdx > colonIdx)) || ((questionIdx > -1) && (slashIdx > questionIdx))) {

            int idx = -1;

            boolean colonAndQuestion = (colonIdx > -1) && (questionIdx > -1);

            if ((colonAndQuestion && (colonIdx < questionIdx)) || (colonIdx > -1)) {

                idx = getCharIdxBeforeOrAfterIdx(path, colonIdx, TermUtils.URI_SEP);

            } else if ((colonAndQuestion && (colonIdx > questionIdx)) || (questionIdx > -1)) {

                idx = getCharIdxBeforeOrAfterIdx(path, questionIdx, TermUtils.URI_SEP);
            }

            if (idx > -1) {
                slashIdx = idx;
            }
        }
    }

    if (slashIdx > -1) {
        String part = path.substring(0, slashIdx);
        if (part.length() > 0) {
            parts.add(part);
        }
        slashIdx++;

        if (slashIdx < path.length()) {
            parts.add(path.substring(slashIdx));
        }

    } else {
        parts.add(path);
    }

    return parts;
}

From source file:com.ottogroup.bi.streaming.operator.json.statsd.StatsdExtractedMetricsReporter.java

/**
 * Extracts and reports a gauge value/* w  ww. ja va2 s.  c  o m*/
 * @param metricCfg 
 *          The field configuration providing information on how to access and export content from JSON. Value is expected not to be null
 * @param json
 *          The {@link JSONObject} to extract information from. Value is expected not to be null
 */
protected void reportGauge(final StatsdMetricConfig metricCfg, final JSONObject json) {
    String path = null;
    if (metricCfg.getDynamicPathPrefix() != null) {
        try {
            String dynPathPrefix = this.jsonUtils.getTextFieldValue(json,
                    metricCfg.getDynamicPathPrefix().getPath(), false);
            if (StringUtils.isNotBlank(dynPathPrefix))
                path = dynPathPrefix + (!StringUtils.endsWith(dynPathPrefix, ".") ? "." : "")
                        + metricCfg.getPath();
            else
                path = metricCfg.getPath();
        } catch (Exception e) {
            // do nothing
            path = metricCfg.getPath();
        }
    } else {
        path = metricCfg.getPath();
    }

    if (metricCfg.getJsonRef().getContentType() == JsonContentType.INTEGER) {
        try {
            final Integer value = this.jsonUtils.getIntegerFieldValue(json, metricCfg.getJsonRef().getPath());
            if (value != null)
                this.statsdClient.gauge(path,
                        (metricCfg.getScaleFactor() != 1 ? value.longValue() * metricCfg.getScaleFactor()
                                : value.longValue()));
        } catch (Exception e) {
            // do nothing
        }
    } else if (metricCfg.getJsonRef().getContentType() == JsonContentType.DOUBLE) {
        try {
            final Double value = this.jsonUtils.getDoubleFieldValue(json, metricCfg.getJsonRef().getPath());
            if (value != null)
                this.statsdClient.gauge(path,
                        (metricCfg.getScaleFactor() != 1
                                ? (long) (value.doubleValue() * metricCfg.getScaleFactor())
                                : value.longValue()));
        } catch (Exception e) {
            // do nothing
        }
    }
}

From source file:com.nesscomputing.quartz.QuartzJob.java

@SuppressWarnings("PMD.UseStringBufferForStringAppends")
public void submitConditional(final Scheduler scheduler,
        @Named(NESS_JOB_NAME) final Configuration nessJobConfiguration) throws SchedulerException {
    String conditionalKey = null;
    final boolean enableJob;

    if (enabled != null) {
        enableJob = enabled;//from   ww w .  java2 s  .c  om
    } else {
        if (conditional == null) {
            enableJob = true;
            LOG.warn("Neither enable nor conditional was set for %s, enabling unconditionally!", name);
        } else {
            conditionalKey = StringUtils.removeStart(conditional, NESS_JOB_NAME + ".");
            conditionalKey = StringUtils.endsWith(conditionalKey, ".enabled") ? conditionalKey
                    : conditionalKey + ".enabled";
            enableJob = nessJobConfiguration.getBoolean(conditionalKey, false);
        }
    }

    if (enableJob) {
        submit(scheduler);
    } else {
        scheduler.addJob(getJobDetail(), false);
        LOG.info("Job '%s is not scheduled (enabled: %s / conditional: %s)", name,
                enabled == null ? "<unset>" : enabled.toString(),
                conditional == null ? "<unset>" : conditionalKey);
    }
}

From source file:io.kahu.hawaii.util.call.sql.DbRequestBuilderRepository.java

private void load(final String resourcePath) {
    String directory = resourcePath;
    if (!StringUtils.startsWith(directory, "/")) {
        directory = "/" + directory;
    }/*from w  w  w.  jav a 2s.  com*/
    if (!StringUtils.endsWith(directory, "/")) {
        directory += "/";
    }
    walkDirectory(directory);
}

From source file:com.pidoco.juri.JURI.java

@Nullable
private CharSequence buildHostString() {
    String decodedHost = this.host;
    if (decodedHost == null) {
        decodedHost = prototype.getHost();
    }/*  w  w  w .  j a va2s.  c  o  m*/
    if (StringUtils.startsWith(decodedHost, "[") && StringUtils.endsWith(decodedHost, "]")) {
        return decodedHost; // ipv6 and other address literal that is not encoded (at least currently)
    }
    return urlEncode(decodedHost);
}

From source file:com.khs.sherpa.SherpaSettings.java

public String serverUrl() {
    String value = properties.getProperty("server.url");
    if (!StringUtils.isEmpty(value)) {
        // always remove the ending /
        if (StringUtils.endsWith(value, "/")) {
            value = StringUtils.removeEnd(value, "/");
        }//from   w w w  .  ja v  a 2 s  .  co  m
        return value;
    }
    return null;
}

From source file:com.bekwam.resignator.commands.UnsignCommand.java

private void removeSigs(File metaInfDir) {
    File[] sfFiles = metaInfDir.listFiles(pathname -> StringUtils.endsWith(pathname.getName(), ".SF"));
    for (File sf : sfFiles) {
        File[] dsfFiles = metaInfDir.listFiles(
                pathname -> StringUtils.startsWith(pathname.getName(), FilenameUtils.getBaseName(sf.getName()))
                        && !StringUtils.endsWith(pathname.getName(), ".SF"));
        for (File dsf : dsfFiles) {
            if (logger.isDebugEnabled()) {
                logger.debug("[UNSIGN] deleting dsf={}", dsf.getName());
            }//  w  w w.ja  v  a  2  s . c  o  m
            dsf.delete();
        }
        if (logger.isDebugEnabled()) {
            logger.debug("[UNSIGN] deleting sf={}", sf.getName());
        }
        sf.delete();
    }
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

/**
 * Support data structures where link metadata is stored in mutliple HTML5 data-* attributes.
 * @param pResourceProps Valuemap to write link metadata to
 * @param element Link element//ww  w  .ja v a2 s.  co m
 * @return true if any metadata attribute was found
 */
private boolean getAnchorMetadataFromData(ValueMap pResourceProps, Element element) {
    boolean foundAny = false;

    List<Attribute> attributes = element.getAttributes();
    for (Attribute attribute : attributes) {
        if (DataPropertyUtil.isHtml5DataName(attribute.getName())) {
            String value = attribute.getValue();
            if (StringUtils.isNotEmpty(value)) {
                String property = DataPropertyUtil.toHeadlessCamelCaseName(attribute.getName());
                if (StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) {
                    try {
                        JSONArray jsonArray = new JSONArray(value);
                        String[] values = new String[jsonArray.length()];
                        for (int i = 0; i < jsonArray.length(); i++) {
                            values[i] = jsonArray.optString(i);
                        }
                        pResourceProps.put(property, values);
                    } catch (JSONException ex) {
                        // ignore
                    }
                } else {
                    // decode if required
                    value = decodeIfEncoded(value);
                    pResourceProps.put(property, value);
                }
                foundAny = true;
            }
        }
    }

    return foundAny;
}