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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.opengamma.web.portfolio.WebPortfolioNodePositionsResource.java

@POST
@Produces(MediaType.TEXT_HTML)/*from   ww  w.j  a  va2s.  c  om*/
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response postHTML(@FormParam("positionurl") String positionUrlStr) {
    PortfolioDocument doc = data().getPortfolio();
    if (doc.isLatest() == false) {
        return Response.status(Status.FORBIDDEN).entity(new WebPortfolioNodeResource(this).getHTML()).build();
    }

    positionUrlStr = StringUtils.trimToNull(positionUrlStr);
    if (positionUrlStr == null) {
        FlexiBean out = createRootData();
        out.put("err_positionUrlMissing", true);
        String html = getFreemarker().build(HTML_DIR + "portfolionodepositions-add.ftl", out);
        return Response.ok(html).build();
    }
    UniqueId positionId = null;
    try {
        new URI(positionUrlStr); // validates whole URI
        String uniqueIdStr = StringUtils.substringAfterLast(positionUrlStr, "/positions/");
        uniqueIdStr = StringUtils.substringBefore(uniqueIdStr, "/");
        positionId = UniqueId.parse(uniqueIdStr);
        data().getPositionMaster().get(positionId); // validate position exists
    } catch (Exception ex) {
        FlexiBean out = createRootData();
        out.put("err_positionUrlInvalid", true);
        String html = getFreemarker().build(HTML_DIR + "portfolionodepositions-add.ftl", out);
        return Response.ok(html).build();
    }
    URI uri = addPosition(doc, positionId);
    return Response.seeOther(uri).build();
}

From source file:com.dianping.avatar.cache.util.CacheMonitorUtil.java

/**
 * ?hawk/*from   w  w w  .jav  a2s  .c  o  m*/
 * @param errorMsg
 * @param throwable
 */
public static void logCacheError(String errorMsg, Throwable throwable) {
    try {
        String factorName = StringUtils.substringBefore(errorMsg, "[");
        int logFactorNew = getNewLogFactor(factorName);
        if (logFactorNew % 100 == 0) {
            logger.error("Operate cache error: " + errorMsg, throwable);
        }
        if (hawkClass != null) {
            if (logFactorNew % 300 == 0) {
                Hawk.log(KEY_CACHE, "cache-operate-error", null, null, throwable.getClass().getName(), errorMsg,
                        getErrorString(throwable));
            }
        }
    } catch (Throwable t) {
        if (logFactor3++ % 300 == 0) {
            logger.error("Log cache-error failed.", throwable);
        }
    }
}

From source file:com.opengamma.component.ComponentConfigLoader.java

/**
 * Starts the components defined in the specified resource.
 * <p>/*from ww  w  .ja va 2  s. co m*/
 * The specified properties are simple key=value pairs and must not be surrounded with ${}.
 * 
 * @param resource  the config resource to load, not null
 * @param properties  the default set of replacements, not null
 * @return the config, not null
 */
public ComponentConfig load(Resource resource, ConcurrentMap<String, String> properties) {
    Map<String, String> iniProperties = extractIniProperties(properties);
    properties = adjustProperties(properties);

    List<String> lines = readLines(resource);
    ComponentConfig config = new ComponentConfig();
    String group = "global";
    int lineNum = 0;
    for (String line : lines) {
        lineNum++;
        line = line.trim();
        if (line.length() == 0 || line.startsWith("#") || line.startsWith(";")) {
            continue;
        }
        if (line.startsWith("${") && line.substring(2).contains("=")
                && StringUtils.substringBefore(line, "=").trim().endsWith("}")) {
            parseReplacement(line, properties);

        } else {
            line = applyReplacements(line, properties);

            if (line.startsWith("[") && line.endsWith("]")) {
                group = line.substring(1, line.length() - 1);

            } else {
                String key = StringUtils.substringBefore(line, "=").trim();
                String value = StringUtils.substringAfter(line, "=").trim();
                if (key.length() == 0) {
                    throw new IllegalArgumentException("Invalid key, line " + lineNum);
                }
                config.add(group, key, value);
            }
        }
    }

    // override config with properties prefixed by INI
    for (Entry<String, String> entry : iniProperties.entrySet()) {
        String iniGroup = StringUtils.substringBefore(entry.getKey(), ".");
        String iniKey = StringUtils.substringAfter(entry.getKey(), ".");
        config.getGroup(iniGroup).put(iniKey, entry.getValue()); // throws exception if iniGroup not found
    }
    return config;
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.InclusionsCreator.java

private String stripPlusXml(String aStr) {
    return StringUtils.substringBefore(aStr, ".") + ".xml";
}

From source file:com.careerly.common.support.resolver.ControllerExceptionResolver.java

@Override
public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {// w  ww  .  j  a v a 2s .  c o m

    ControllerExceptionResolver.logger
            .error(String.format("ERROR ## [%s] happend error,the trace is ", request.getServletPath()), ex);

    String fullClazzName = StringUtils.substringAfterLast(handler.getClass().getName(), ".");
    String clazzName = StringUtils.substringBefore(fullClazzName, "$");

    if (clazzName.endsWith(ControllerExceptionResolver.DATA_CONTROLLER) || clazzName
            .endsWith(ControllerExceptionResolver.API_CONTROLLER)) /** ??DataAPI **/
    {
        if (ex instanceof BusinessException) /** BusinessException?message?ErrorJsonObject **/
        {
            BusinessException be = (BusinessException) ex;
            resolveDataException(request, response, handler,
                    StandardJsonObject.newErrorJsonObject(be.getErrorCode(), be.getLocalizedMessage()));
        } else/** ?BusinessExceptionException"api error"ErrorJsonObject **/
        {
            resolveDataException(request, response, handler,
                    StandardJsonObject.newErrorJsonObject("?!"));
        }

        return null;
    } else /** ?Page **/
    {
        if (ex instanceof BusinessException)/** BusinessException?error? **/
        {
            ModelAndView mv = new ModelAndView();
            mv.addObject("errMsg", ex.getLocalizedMessage());
            mv.setViewName("views/error");
            return mv;
        } else /** ?BusinessExceptionExceptionerror? **/
        {
            return super.doResolveException(request, response, handler, ex);
        }
    }

}

From source file:com.hangum.tadpole.db.metadata.MakeContentAssistUtil.java

/**
 *    ? ? ??     .. //from   w w w .j  a va  2s .  co  m
 *   content assist   tester.tablename   ?  ?? . ?   ? ? ? ?. 
 * 
 * @param userDB
 * @param strArryCursor
 * @return
 */
protected String getSchemaOrTableContentAssist(UserDBDAO userDB, String[] strArryCursor) {
    String strCntAsstList = getContentAssist(userDB);
    String strCursorText = strArryCursor[0] + strArryCursor[1];

    if (StringUtils.contains(strCursorText, '.')) {
        String strSchemaName = StringUtils.substringBefore(strCursorText, ".") + ".";
        //         String strTableName       = StringUtils.substringAfter(strCursorText, ".");
        int intSep = StringUtils.indexOf(strCursorText, ".");

        if (logger.isDebugEnabled()) {
            logger.debug("[0]" + strArryCursor[0]);
            logger.debug("[1]" + strArryCursor[1]);
            logger.debug("[1][intSep]" + intSep);
            logger.debug("[1][strArryCursor[0].length()]" + strArryCursor[0].length());
            logger.debug("==> [Return table list]" + (strArryCursor[0].length() >= intSep));
        }

        // ?  ?  ?  .
        if (strArryCursor[0].length() >= intSep) {
            String strNewCntAsstList = "";

            String[] listGroup = StringUtils.splitByWholeSeparator(strCntAsstList, _PRE_GROUP);
            if (listGroup == null)
                return strNewCntAsstList;

            for (String strDefault : listGroup) {
                String[] listDefault = StringUtils.split(strDefault, _PRE_DEFAULT);
                if (listDefault != null & listDefault.length == 2) {
                    if (StringUtils.startsWithIgnoreCase(listDefault[0], strSchemaName))
                        strNewCntAsstList += makeObjectPattern("",
                                StringUtils.removeStartIgnoreCase(listDefault[0], strSchemaName),
                                listDefault[1]);
                } // 
            }

            return strNewCntAsstList;
        }
    }

    return strCntAsstList;
}

From source file:com.comcast.cats.SnmpUtil.java

/**
 * Returns the Formatted time in day:HH:mm:ss format. The input time is in
 * seconds. Returns empty string if input is negative.
 * //w w w . j av  a 2s .  co  m
 * @param upTimeInSec
 * @return
 */
public static String getFormattedTime(final long upTimeInSec) {
    String timeTicksString = getFormattedTimeForTimeTicks(upTimeInSec * 100);
    return StringUtils.substringBefore(timeTicksString, CONST_DOT);
}

From source file:com.dianping.lion.util.UrlUtils.java

public static List<String> getParameterNames(String url) {
    if (url == null) {
        throw new NullPointerException("Param[url] cannot be null.");
    }/*  www  . ja v a2 s. co  m*/
    List<String> parameterNames = new ArrayList<String>();
    String queryString = StringUtils.substringAfter(url, "?");
    if (queryString != null) {
        String[] segments = StringUtils.split(queryString, "&");
        for (String segment : segments) {
            String param = StringUtils.substringBefore(segment, "=");
            if (!parameterNames.contains(param)) {
                parameterNames.add(param);
            }
        }
    }
    return parameterNames;
}

From source file:ddf.mime.mapper.MockMimeTypeResolver.java

public void setCustomMimeTypes(String[] customMimeTypes) {
    //        this.customMimeTypes = customMimeTypes.clone();
    this.customFileExtensionsToMimeTypesMap = new HashMap<String, String>();
    this.customMimeTypesToFileExtensionsMap = new HashMap<String, List<String>>();

    for (String mimeTypeMapping : customMimeTypes) {

        // mimeTypeMapping is of the form <file extension>=<mime type>
        // Examples:
        // nitf=image/nitf

        String fileExtension = StringUtils.substringBefore(mimeTypeMapping, "=");
        String mimeType = StringUtils.substringAfter(mimeTypeMapping, "=");

        customFileExtensionsToMimeTypesMap.put(fileExtension, mimeType);
        List<String> fileExtensions = (List<String>) customMimeTypesToFileExtensionsMap.get(mimeType);
        if (fileExtensions == null) {
            fileExtensions = new ArrayList<String>();
        }//from  ww w  .j a  va 2s  . co m
        fileExtensions.add(fileExtension);
        customMimeTypesToFileExtensionsMap.put(mimeType, fileExtensions);
    }
}

From source file:com.intuit.tank.http.multipart.MultiPartRequest.java

@Override
public void setBody(String bodyEncoded) {
    String s = new String(Base64.decodeBase64(bodyEncoded));
    String boundary = StringUtils.substringBefore(s, "\r\n").substring(2);
    super.setBody(s);
    try {//w  ww .  j  a  v a 2 s. co  m
        // s = getBody();
        @SuppressWarnings("deprecation")
        MultipartStream multipartStream = new MultipartStream(
                new ByteArrayInputStream(Base64.decodeBase64(bodyEncoded)), boundary.getBytes());
        boolean nextPart = multipartStream.skipPreamble();
        while (nextPart) {
            String header = multipartStream.readHeaders();
            // process headers
            // create some output stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multipartStream.readBodyData(bos);
            PartHolder p = new PartHolder(bos.toByteArray(), header);
            parameters.add(p);
            nextPart = multipartStream.readBoundary();
        }
    } catch (MultipartStream.MalformedStreamException e) {
        LOG.error(e.toString(), e);
        // the stream failed to follow required syntax
    } catch (IOException e) {
        LOG.error(e.toString(), e);
        // a read or write error occurred
    }
}