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.snp.site.init.SystemInit.java

/**
 * ??? ?????, ? siteStrMap =//from  w  w  w  .jav a 2s  .c  om
 * FileProcessor.getMapFromePropFile(getConfigRoot() + "lang",
 * "properties"); snpStrMap =
 * FileProcessor.getMapFromePropFile(getConfigRoot() + "lang", "txt");
 * ?MAP
 */
public static HashMap getMapFromePropFile(String filepath, String file_dx) throws Exception {
    try {
        HashMap MapData = new HashMap();
        String[] extensions = { file_dx };
        Collection files = FileUtils.listFiles(new File(filepath), extensions, false);
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File element = (File) iter.next();
            String filename = StringUtils.substringBefore(element.getName(), ".").toLowerCase();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(new FileInputStream(element), "utf-8"));
            String strvalue = "";
            while (strvalue != null) {
                strvalue = br.readLine();
                String[] mapValue = StringUtils.split(strvalue, "=");
                if (mapValue != null && mapValue.length > 1) {
                    MapData.put(filename + "_" + mapValue[0].trim(), StringUtils.trim(mapValue[1]));
                }
            }

        }
        return MapData;
    } catch (Exception e) {
        throw e;
    }

}

From source file:de.faustedition.maven.OddSchemaDeployMojo.java

/**
 * <p>//www .j  ava  2s  .c  o m
 * Get the <code>ProxyInfo</code> of the proxy associated with the
 * <code>host</code> and the <code>protocol</code> of the given
 * <code>repository</code>.
 * </p>
 * <p>
 * Extract from <a href=
 * "http://java.sun.com/j2se/1.5.0/docs/guide/net/properties.html"> J2SE
 * Doc : Networking Properties - nonProxyHosts</a> : "The value can be a
 * list of hosts, each separated by a |, and in addition a wildcard
 * character (*) can be used for matching"
 * </p>
 * <p>
 * Defensively support for comma (",") and semi colon (";") in addition
 * to pipe ("|") as separator.
 * </p>
 * 
 * @param repository
 *                the Repository to extract the ProxyInfo from.
 * @param wagonManager
 *                the WagonManager used to connect to the Repository.
 * @return a ProxyInfo object instantiated or <code>null</code> if no
 *         matching proxy is found
 */
public static ProxyInfo getProxyInfo(Repository repository, WagonManager wagonManager) {
    ProxyInfo proxyInfo = wagonManager.getProxy(repository.getProtocol());

    if (proxyInfo == null) {
        return null;
    }

    String host = repository.getHost();
    String nonProxyHostsAsString = proxyInfo.getNonProxyHosts();
    String[] nonProxyHosts = StringUtils.split(nonProxyHostsAsString, ",;|");
    for (int i = 0; i < nonProxyHosts.length; i++) {
        String nonProxyHost = nonProxyHosts[i];
        if (StringUtils.contains(nonProxyHost, "*")) {
            // Handle wildcard at the end, beginning or
            // middle of the nonProxyHost
            String nonProxyHostPrefix = StringUtils.substringBefore(nonProxyHost, "*");
            String nonProxyHostSuffix = StringUtils.substringAfter(nonProxyHost, "*");
            // prefix*
            if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix)
                    && StringUtils.isEmpty(nonProxyHostSuffix)) {
                return null;
            }
            // *suffix
            if (StringUtils.isEmpty(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix)
                    && host.endsWith(nonProxyHostSuffix)) {
                return null;
            }
            // prefix*suffix
            if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix)
                    && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) {
                return null;
            }
        } else if (host.equals(nonProxyHost)) {
            return null;
        }
    }
    return proxyInfo;
}

From source file:com.lll.util.ServletUtils.java

/**
 * ?contentTypeheaders./* w ww  . java 2s .co  m*/
 */
private static void initResponseHeader(HttpServletResponse response, final String contentType,
        final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    //headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setNoCacheHeader(response);
    }

}

From source file:com.evolveum.midpoint.task.quartzimpl.TaskManagerConfiguration.java

private void checkAllowedKeys(Configuration c, List<String> knownKeys)
        throws TaskManagerConfigurationException {
    Set<String> knownKeysSet = new HashSet<String>(knownKeys);

    Iterator<String> keyIterator = c.getKeys();
    while (keyIterator.hasNext()) {
        String keyName = keyIterator.next();
        String normalizedKeyName = StringUtils.substringBefore(keyName, "."); // because of subkeys
        normalizedKeyName = StringUtils.substringBefore(normalizedKeyName, "["); // because of [@xmlns:c]
        int colon = normalizedKeyName.indexOf(':'); // because of c:generalChangeProcessorConfiguration
        if (colon != -1) {
            normalizedKeyName = normalizedKeyName.substring(colon + 1);
        }//from   w w w  .  j  a  v  a 2 s . co  m
        if (!knownKeysSet.contains(keyName) && !knownKeysSet.contains(normalizedKeyName)) { // ...we need to test both because of keys like 'midpoint.home'
            throw new TaskManagerConfigurationException(
                    "Unknown key " + keyName + " in task manager configuration");
        }
    }
}

From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthGitFilter.java

private String getAuthenticatedUserFromGitRequestUsingOAuthToken(HttpServletRequest req,
        HttpServletResponse rsp) throws IOException {
    final String httpBasicAuth = getHttpBasicAuthenticationHeader(req);
    if (httpBasicAuth == null) {
        return null;
    }//w w w  .  ja va 2s .co  m

    if (isInvalidHttpAuthenticationHeader(httpBasicAuth)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return null;
    }

    String oauthToken = StringUtils.substringBefore(httpBasicAuth, ":");
    String oauthKeyword = StringUtils.substringAfter(httpBasicAuth, ":");
    if (Strings.isNullOrEmpty(oauthToken) || Strings.isNullOrEmpty(oauthKeyword)) {
        rsp.sendError(SC_UNAUTHORIZED);
        return null;
    }

    if (!oauthKeyword.equalsIgnoreCase(GITHUB_X_OAUTH_BASIC)) {
        return null;
    }

    boolean loginSuccessful = false;
    String oauthLogin = null;
    try {
        oauthLogin = oauthCache.getLoginByAccessToken(new AccessToken(oauthToken));
        loginSuccessful = !Strings.isNullOrEmpty(oauthLogin);
    } catch (ExecutionException e) {
        log.warn("Login failed for OAuth token " + oauthToken, e);
        loginSuccessful = false;
    }

    if (!loginSuccessful) {
        rsp.sendError(SC_FORBIDDEN);
        return null;
    }

    return oauthLogin;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.MySQLLoginComposite.java

@Override
public boolean connection() {
    if (!isValidate())
        return false;

    String dbUrl = "";
    String locale = comboLocale.getText().trim();
    if (locale.equals("") || DBLocaleUtils.NONE_TXT.equals(locale)) {
        dbUrl = String.format(DBDefine.MYSQL_DEFAULT.getDB_URL_INFO(), textHost.getText(), textPort.getText(),
                textDatabase.getText());
    } else {/*from  www  .  j a  va  2 s .  c  o m*/
        String selectLocale = StringUtils.substringBefore(comboLocale.getText(), "|");

        dbUrl = String.format(DBDefine.MYSQL_DEFAULT.getDB_URL_INFO(), textHost.getText(), textPort.getText(),
                textDatabase.getText() + "?useUnicode=false&characterEncoding=" + selectLocale.trim());
    }
    if (logger.isDebugEnabled())
        logger.debug("[db url]" + dbUrl);

    userDB = new UserDBDAO();
    userDB.setTypes(DBDefine.MYSQL_DEFAULT.getDBToString());
    userDB.setUrl(dbUrl);
    userDB.setDb(textDatabase.getText());
    userDB.setGroup_name(comboGroup.getText().trim());
    userDB.setDisplay_name(textDisplayName.getText());
    userDB.setOperation_type(DBOperationType.getNameToType(comboOperationType.getText()).toString());
    userDB.setHost(textHost.getText());
    userDB.setPasswd(textPassword.getText());
    userDB.setPort(textPort.getText());
    userDB.setLocale(comboLocale.getText());
    userDB.setUsers(textUser.getText());

    //  ?? ??
    if (oldUserDB != null) {
        if (!MessageDialog.openConfirm(null, "Confirm", Messages.SQLiteLoginComposite_13)) //$NON-NLS-1$
            return false;

        if (!checkDatabase(userDB))
            return false;

        try {
            TadpoleSystem_UserDBQuery.updateUserDB(userDB, oldUserDB, SessionManager.getSeq());
        } catch (Exception e) {
            logger.error(Messages.SQLiteLoginComposite_8, e);
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), "Error", Messages.SQLiteLoginComposite_5, //$NON-NLS-1$
                    errStatus);

            return false;
        }

        return true;
        //  ?? .
    } else {
        // ?  ? .
        if (!connectValidate(userDB))
            return false;

        try {
            TadpoleSystem_UserDBQuery.newUserDB(userDB, SessionManager.getSeq());
        } catch (Exception e) {
            logger.error(Messages.MySQLLoginComposite_0, e);
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), "Error", Messages.MySQLLoginComposite_2, //$NON-NLS-1$
                    errStatus);
        }

        return true;
    }
}

From source file:com.wwinsoft.modules.orm.hibernate.HibernateDao.java

private String prepareCountSql(String orgHql) {
    String fromHql = orgHql;/*from www . j  a v  a  2  s .  c  o m*/
    //select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    fromHql = StringUtils.substringBefore(fromHql, "order by");

    String countHql = "select count(*) " + fromHql;
    return countHql;
}

From source file:eionet.meta.service.EmailServiceImpl.java

/**
 * Parse LDAP role e-mail addresses and replace country code and member/collaborative country abbreviations.
 *
 * @param country//from   w  w w  .  j av a2  s .  c  om
 * @return
 * @throws DirServiceException
 */
private String[] parseRoleAddresses(String country) throws DirServiceException {
    String recipients = Props.getRequiredProperty(PropsIF.SITE_CODE_ALLOCATE_NOTIFICATION_TO);
    recipients = StringUtils.replace(recipients, COUNTRY_CODE_PLACEHOLDER, country.toLowerCase());
    String[] to = StringUtils.split(recipients, ",");

    for (int i = 0; i < to.length; i++) {
        if (to[i].contains(MC_CC_PLACEHOLDER)) {
            // test if it is member country
            String roleId = StringUtils.substringBefore(to[i], "@");
            String mcRoleId = StringUtils.replace(roleId, MC_CC_PLACEHOLDER, MC);
            if (roleExists(mcRoleId)) {
                to[i] = StringUtils.replace(to[i], MC_CC_PLACEHOLDER, MC);
                continue;
            }
            // test if it is collaborative country country
            String ccRoleId = StringUtils.replace(roleId, MC_CC_PLACEHOLDER, CC);
            if (roleExists(ccRoleId)) {
                to[i] = StringUtils.replace(to[i], MC_CC_PLACEHOLDER, CC);
            }
            // could not
            if (to[i].contains(MC_CC_PLACEHOLDER)) {
                if (ArrayUtils.contains(MC_COUNTRIES, country.toLowerCase())) {
                    StringUtils.replace(to[i], MC_CC_PLACEHOLDER, MC);
                } else {
                    StringUtils.replace(to[i], MC_CC_PLACEHOLDER, CC);
                }
            }
        }
    }

    return to;
}

From source file:com.intuit.tank.harness.functions.JexlStringFunctions.java

private String[] internalSubstringsBetween(String subject, String open, String close) {
    String[] ret = null;//  www  .  j  av  a  2  s. c o  m
    if (subject != null && open == null && close != null) {
        ret = new String[] { StringUtils.substringBefore(subject, close) };
    } else if (subject != null && open != null && close == null) {
        ret = new String[] { StringUtils.substringAfterLast(subject, open) };
    } else {
        ret = StringUtils.substringsBetween(subject, open, close);
    }
    return ret != null ? ret : new String[0];
}

From source file:edu.mayo.cts2.framework.plugin.service.bprdf.dao.id.DefaultIdService.java

@Override
public String getAcronymForUri(String uri) {
    // try adding a '/' if we don't find it
    for (String addition : Arrays.asList("", "/")) {
        String acronym = this.getFromCache(this.uriToAcronym, uri + addition);
        if (acronym != null) {
            return acronym;
        }/*w  ww  .  ja v  a2s  . c om*/
    }

    if (uri.startsWith(BIOPORTAL_PURL_URI)) {
        uri = StringUtils.removeStart(uri, BIOPORTAL_PURL_URI);
        uri = StringUtils.removeEnd(uri, "/");
        uri = StringUtils.substringBefore(uri, "/");

        uri = StringUtils.removeEnd(uri, ":");
        uri = StringUtils.removeEnd(uri, "#");

        return uri;
    }
    if (uri.startsWith(PURL_OBO_OWL_URI)) {
        uri = StringUtils.removeStart(uri, PURL_OBO_OWL_URI);
        uri = StringUtils.removeEnd(uri, "/");
        uri = StringUtils.substringBefore(uri, "/");

        uri = StringUtils.removeEnd(uri, ":");
        uri = StringUtils.removeEnd(uri, "#");

        return uri;
    } else {
        return null;
    }
}