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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:org.lockss.plugin.FormUrlHelper.java

/**
 * convert from a unencoded string url This routine should almost never be
 * called because  it is impossible to tell whether equal signs and ampersands
 * are part of the form parameters or being used as separators. Use
 * convertFromEncodedString instead./*from www .  ja va 2s. c om*/
 *
 * @param url
 * @return true if the url is valid
 */
public boolean convertFromString(String url) {
    // an invalid url if starts with ?, doesn't contain ?
    if (StringUtils.indexOf(url, "?") == -1 || StringUtils.indexOf(url, "?") == 0) {
        m_valid = false;
        return m_valid;
    }

    String prefix = StringUtils.substringBefore(url, "?");
    setBaseUrl(prefix);
    String rest = StringUtils.substringAfter(url, "?");
    String key;
    String value;
    if (logger.isDebug3())
        logger.debug3("rest=" + rest);
    while (rest != null && rest.length() > 0) {
        if (logger.isDebug3())
            logger.debug3("rest2=" + rest);

        if (StringUtils.indexOf(rest, "=") > 0) {
            key = StringUtils.substringBefore(rest, "=");
            rest = StringUtils.substringAfter(rest, "=");
            if (logger.isDebug3())
                logger.debug3("rest3=" + rest);
            if (rest != null && StringUtils.indexOf(rest, "&") != -1) {
                value = StringUtils.substringBefore(rest, "&");
                add(key, value);
                rest = StringUtils.substringAfter(rest, "&");
            } else {
                // last value
                value = rest;
                add(key, value);
                rest = "";
            }
        } else {
            //This indicates a form url missing the equals  sign,
            // stop processing at this point
            m_valid = false;
            rest = "";
        }
    }
    return m_valid;
}

From source file:org.mayocat.addons.EntityListAddonTransformer.java

public Optional<AddonFieldValueWebObject> toWebView(EntityData<?> entityData, AddonFieldDefinition definition,
        Object storedValue) {/*  ww  w.  java  2s .  c o  m*/
    List<String> slugs = (List) storedValue;
    if (!definition.getProperties().containsKey("entityList.entityType")) {
        logger.warn("entityList.entityType property is mandatory for addon type entityList");
        return Optional.absent();
    }

    String type = (String) definition.getProperties().get("entityList.entityType");

    if (!entityLoader.containsKey(type)) {
        logger.warn("No loader for entity type " + type);
        return Optional.absent();
    }

    String builderHint = null;
    if (webContext.getTenant() == null) {
        builderHint = "global/" + type;
    } else {
        builderHint = type;
    }

    if (!getBuilders().containsKey(builderHint)) {
        logger.warn("No entity list addon web object buider for hint " + builderHint);
        return Optional.absent();
    }

    EntityListAddonWebObjectBuilder builder = getBuilders().get(builderHint);
    EntityLoader loader = entityLoader.get(type);

    List<Entity> entities = Lists.newArrayList();

    try {
        for (String slug : slugs) {
            Entity e;
            if (slug.indexOf('@') > 0 && webContext.getTenant() == null) {
                String tenantSlug = StringUtils.substringAfter(slug, "@");
                String entitySlug = StringUtils.substringBefore(slug, "@");
                e = loader.load(entitySlug, tenantSlug);
            } else {
                e = loader.load(slug);
            }
            entities.add(e);
        }

        List<EntityData<Entity>> data = dataLoader.load(entities, StandardOptions.LOCALIZE,
                AttachmentLoadingOptions.FEATURED_IMAGE_ONLY);

        List<Object> result = Lists.newArrayList();

        for (EntityData<Entity> e : data) {
            result.add(builder.build(e));
        }

        return Optional.of(new AddonFieldValueWebObject(result, buildDisplay(data)));
    } catch (Exception e) {
        logger.warn("Exception while trying to load entity", e.getMessage());
        throw e;
        //return Optional.absent();
    }
}

From source file:org.mayocat.context.RequestContextInitializer.java

public void requestInitialized(ServletRequestEvent servletRequestEvent) {
    if (isStaticPath(this.getRequestURI(servletRequestEvent))) {
        return;/*from www.  ja va2  s.  c  o  m*/
    }

    DefaultWebRequestBuilder requestBuilder = new DefaultWebRequestBuilder();

    // 1. Tenant

    String host = getHost(servletRequestEvent);
    String path = getPath(servletRequestEvent);

    Tenant tenant = this.tenantResolver.get().resolve(host, path);
    DefaultWebContext context = new DefaultWebContext(tenant, null);

    // Set the context in the context already, even if we haven't figured out if there is a valid user yet.
    // The context tenant is actually needed to find out the context user and to initialize tenant configurations
    ((ThreadLocalWebContext) this.context).setContext(context);

    if (tenant != null) {
        requestBuilder.tenantRequest(true);
        if (path.indexOf("/tenant/" + tenant.getSlug()) == 0) {
            path = StringUtils.substringAfter(path, "/tenant/" + tenant.getSlug());
            requestBuilder.tenantPrefix("/tenant/" + tenant.getSlug());
        }
    } else {
        requestBuilder.tenantRequest(false);
    }

    requestBuilder.apiRequest(path.indexOf("/api/") == 0);

    // 2. Configurations

    Map<Class, Serializable> configurations = configurationService.getSettings();
    context.setSettings(configurations);

    // 3. User

    Optional<User> user = Optional.absent();
    for (String headerName : Lists.newArrayList("Authorization", "Cookie")) {
        final String headerValue = Strings.nullToEmpty(this.getHeaderValue(servletRequestEvent, headerName));
        for (Authenticator authenticator : this.authenticators.values()) {
            if (authenticator.respondTo(headerName, headerValue)) {
                user = authenticator.verify(headerValue, tenant);
            }
        }
    }

    context.setUser(user.orNull());

    if (tenant != null) {
        // 4. ThemeDefinition
        context.setTheme(themeManager.getTheme());
    }
    // 5. Locale
    LocalesSettings localesSettings = configurationService.getSettings(GeneralSettings.class).getLocales();
    boolean localeSet = false;
    List<Locale> alternativeLocales = FluentIterable.from(localesSettings.getOtherLocales().getValue())
            .filter(Predicates.notNull()).toList();

    String canonicalPath = path;
    if (!alternativeLocales.isEmpty()) {
        for (Locale locale : alternativeLocales) {
            List<String> fragments = ImmutableList.copyOf(
                    Collections2.filter(Arrays.asList(path.split("/")), Predicates.not(IS_NULL_OR_BLANK)));
            if (fragments.size() > 0 && fragments.get(0).equals(locale.toLanguageTag())) {
                context.setLocale(locale);
                context.setAlternativeLocale(true);
                canonicalPath = StringUtils.substringAfter(canonicalPath, "/" + locale);
                localeSet = true;
                break;
            }
        }
    }
    if (!localeSet) {
        context.setLocale(localesSettings.getMainLocale().getValue());
        context.setAlternativeLocale(false);
    }

    if (context.isAlternativeLocale()) {
        path = StringUtils.substringAfter(path, context.getLocale().toLanguageTag());
    }

    // 6. Request
    Optional<Breakpoint> breakpoint = this.breakpointDetector.getBreakpoint(getUserAgent(servletRequestEvent));

    requestBuilder.baseURI(getBaseURI(servletRequestEvent)).canonicalPath(canonicalPath).path(path)
            .breakpoint(breakpoint);

    requestBuilder.secure(isSecure(servletRequestEvent));

    context.setRequest(requestBuilder.build());
}

From source file:org.mayocat.multitenancy.DefaultTenantResolver.java

@Override
public Tenant resolve(String host, String path) {
    if (this.resolved.get() == null) {
        this.resolved.set(new HashMap<String, Tenant>());
    }//from   w  ww  .  j av  a  2 s .  co  m
    if (!this.resolved.get().containsKey(host)) {
        Tenant tenant = null;
        try {
            if (!this.configuration.isActivated()) {
                // Mono-tenant

                tenant = this.accountsService.findTenant(this.configuration.getDefaultTenantSlug());
                if (tenant == null) {
                    tenant = this.accountsService.createDefaultTenant();
                }
                this.resolved.get().put(host, tenant);
            } else {
                // Multi-tenant

                if (path != null && path.startsWith("/tenant/")) {
                    String tmp = StringUtils.substringAfter(path, "/tenant/");
                    String slug = StringUtils.substringBefore(tmp, "/");
                    tenant = this.accountsService.findTenant(slug);
                }

                if (tenant == null) {
                    tenant = this.accountsService.findTenantByDefaultHost(host);
                    if (tenant == null) {
                        tenant = this.accountsService.findTenant(this.extractSlugFromHost(host));
                        if (tenant == null) {
                            return null;
                        }
                    }
                }
                this.resolved.get().put(host, tenant);
            }
        } catch (EntityAlreadyExistsException e) {
            // Has been created in between ?
            this.logger.warn("Failed attempt at creating a tenant that already exists for host {}", host);
        }
    }
    logger.debug("Resolved tenant [{}] ", this.resolved.get().get(host));
    return this.resolved.get().get(host);
}

From source file:org.mayocat.rest.Reference.java

public static Reference valueOf(String serialized) {
    if (serialized.indexOf('@') < 1 || serialized.indexOf('@') >= (serialized.length() - 1)) {
        throw new WebApplicationException(
                Response.status(Response.Status.BAD_REQUEST).entity("Invalid reference").build());
    }/*w ww .  j  av a  2 s  .c  om*/

    String entitySlug = StringUtils.substringBefore(serialized, "@");
    String tenantSlug = StringUtils.substringAfter(serialized, "@");

    return new Reference(entitySlug, tenantSlug);
}

From source file:org.mayocat.shop.front.views.WebViewMessageBodyWriter.java

private String cleanErrorMessageForDisplay(String errorMessage) {
    String clean = StringUtils.substringAfter(errorMessage,
            "org.mozilla.javascript.JavaScriptException: Error:");
    clean = clean.replaceAll("\\(handlebars\\.js#\\d+\\)", "");
    return clean;
}

From source file:org.noroomattheinn.tesla.Tesla.java

private JSONObject call(String command, Content payload) {
    JSONObject rawResponse = null;/*from w  w  w .  j  ava  2s  .  c  o m*/
    try {
        if (payload == null)
            rawResponse = api.json(command).object();
        else
            rawResponse = api.json(command, payload).object();
        if (rawResponse == null)
            return new JSONObject();
        return rawResponse.getJSONObject("response");
    } catch (IOException | JSONException ex) {
        String error = ex.toString().replace("\n", " -- ");
        Tesla.logger.finer("Failed invoking (" + StringUtils.substringAfterLast(command, "/") + "): ["
                + StringUtils.substringAfter(error, "["));
        return (rawResponse == null) ? new JSONObject() : rawResponse;
    }
}

From source file:org.opendaylight.controller.config.persist.storage.file.FileStorageAdapter.java

@Override
public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
    Preconditions.checkNotNull(storage, "Storage file is null");

    String content = Files.toString(storage, ENCODING);
    if (numberOfStoredBackups == Integer.MAX_VALUE) {
        resetLastConfig(content);//from  w  w  w . j a  v  a 2  s  . c om
        persistLastConfig(holder);
    } else {
        if (numberOfStoredBackups == 1) {
            Files.write("", storage, ENCODING);
            persistLastConfig(holder);
        } else {
            int count = StringUtils.countMatches(content, SEPARATOR_S);
            if ((count + 1) < numberOfStoredBackups) {
                resetLastConfig(content);
                persistLastConfig(holder);
            } else {
                String contentSubString = StringUtils.substringBefore(content, SEPARATOR_E);
                contentSubString = contentSubString.concat(SEPARATOR_E_PURE);
                content = StringUtils.substringAfter(content, contentSubString);
                resetLastConfig(content);
                persistLastConfig(holder);
            }
        }
    }
}

From source file:org.openhab.binding.ACDBCommon.db.DBManager.java

/**
 * update//from   ww  w  . j  a v a2s.c  om
 *
 * @param updateSql
 * @param value
 * @throws Exception
 */
public static void update(String updateSql, String dateValue) throws Exception {
    SqlResult sqlResult = sqlParse(updateSql);
    String sql = sqlResult.getSql();
    ServerInfo server = sqlResult.getServer();

    Pattern STATE_CONFIG_PATTERN = Pattern.compile("(.*?)\\=(.*?)\\&(.*?)\\=(.*?)");
    Matcher matcher = STATE_CONFIG_PATTERN.matcher(dateValue);

    if (matcher.find()) {
        String[] values = StringUtils.split(dateValue, "&");
        HashMap<String, String> sqlParam = new HashMap<>();
        for (String subValue : values) {
            sqlParam.put(StringUtils.substringBefore(subValue, "="), StringUtils.substringAfter(subValue, "="));
        }
        update(server, sql, sqlParam);

    } else {
        try (PreparedStatement stmt = server.getConnection().prepareStatement(sql)) {
            logger.debug("DB update with:{} ", dateValue);
            stmt.setString(1, dateValue);
            stmt.executeUpdate();
        }
    }
}

From source file:org.openhab.binding.ACDBCommon.db.DBManager.java

/**
 * insert data/*from   w ww .ja v  a 2  s.  c o m*/
 *
 * @param insertSql
 * @param cmdParam
 * @throws Exception
 */
public static void insert(String insertSql, String dateValue) throws Exception {
    SqlResult sqlResult = sqlParse(insertSql);
    String sql = sqlResult.getSql();
    ServerInfo server = sqlResult.getServer();

    Pattern STATE_CONFIG_PATTERN = Pattern.compile("(.*?)\\=(.*?)\\&(.*?)\\=(.*?)");
    Matcher matcher = STATE_CONFIG_PATTERN.matcher(dateValue);

    if (matcher.find()) {
        String[] values = StringUtils.split(dateValue, "&");
        HashMap<String, String> sqlParam = new HashMap<>();
        for (String subValue : values) {
            sqlParam.put(StringUtils.substringBefore(subValue, "="), StringUtils.substringAfter(subValue, "="));
        }
        insert(server, sql, sqlParam);

    } else {
        try (PreparedStatement stmt = server.getConnection().prepareStatement(sql)) {
            stmt.setString(1, dateValue);
            stmt.executeUpdate();
        }
    }
}