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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.oneops.controller.jms.InductorPublisher.java

String getQueue(CmsWorkOrderSimpleBase wo) {
    String queueName = null;//from w  w w  . j  a  v  a  2s. c  o  m
    String location = wo.getCloud().getCiAttributes().get("location");
    if ("true".equals(System.getProperty(USE_SHARED_FLAG))) {
        String cloudName = StringUtils.substringAfterLast(location, "/");
        if (StringUtils.isNotBlank(cloudName)) {
            String prefix = StringUtils.substringBefore(cloudName, "-");
            String queuePrefix = System.getProperty(SHARED_QUEUE_PREFIX + prefix);
            if (StringUtils.isNotBlank(queuePrefix)) {
                queueName = queuePrefix + "." + SHARED_QUEUE;
            }
        }
        if (queueName == null)
            queueName = SHARED_QUEUE;
    } else {
        queueName = (location.replaceAll("/", ".") + QUEUE_SUFFIX).substring(1);
    }
    return queueName;
}

From source file:de.jcup.egradle.codeassist.dsl.MethodUtils.java

/**
 * Calculates method identification in percentage (100= 100%).<br>
 * <br>/*  ww  w . j a v a2s.c  om*/
 * <ul>
 * <li>If a method is exact same 100% is returned</li>
 * <li>If a method is has same name, same param size, but x parameters of n
 * are not equal 50%-100% is returned</li>
 * <li>If a method is has same name, but param size is not equal 50% is
 * returned</li>
 * </ul>
 * 
 * @param method
 * @param itemIdentifier
 * @param itemParameters
 * @return percentage
 */
public static int calculateMethodIdentificationPercentage(Method method, String itemIdentifier,
        String... itemParameters) {
    if (method == null) {
        return 0;
    }
    if (itemIdentifier == null) {
        return 0;
    }
    String methodName = method.getName();
    if (methodName == null) {
        return 0;
    }
    if (itemParameters == null) {
        itemParameters = new String[] {};
    }
    int percentage;
    if (itemIdentifier.equals(methodName)) {
        percentage = 50;// 50% reached because name is equal
    } else {
        if (!methodName.startsWith("get") && !methodName.startsWith("set")) {
            return 0;
        }
        if (methodName.length() == 3) {
            return 0;
        }
        String methodPartName = StringUtils.substring(methodName, 3);
        String buildMethodPartName = StringUtils.capitalize(itemIdentifier);
        if (!methodPartName.equals(buildMethodPartName)) {
            return 0;
        }
        percentage = 49;// 49% reached because name is not equal but it
        // seems groovy magic for get/set,
        // 49% because if there would exists a method with
        // absolute same name this should matter more!
    }
    /* -------------------------------- */
    /* - start percentage calculation - */
    /* -------------------------------- */

    /* name okay, could be ... */

    List<Parameter> parameters = method.getParameters();
    /* check size same */
    int paramSize = parameters.size();
    if (paramSize != itemParameters.length) {
        return percentage;
    }

    if (paramSize == 0) {
        /* speed up and avoid failures on percentage calculation */
        return percentage + 50;
    }

    /* okay at least same size */
    int pos = 0;
    int percentPerCorrectParam = 50 / paramSize;

    int paramPercents = 0;
    boolean allParamsSame = true;
    for (Parameter p : parameters) {
        String itemParam = itemParameters[pos++];
        if (p == null) {
            /* should never happen */
            continue;
        }
        if (itemParam == null) {
            continue;
        }
        /*
         * if item parameter is with color we remove this meta information
         */
        itemParam = StringUtils.substringBefore(itemParam, ":");

        String typeAsString = p.getTypeAsString();
        if (!typeAsString.equals(itemParam)) {
            allParamsSame = false;
        } else {
            paramPercents += percentPerCorrectParam;
        }
    }
    if (allParamsSame) {
        percentage += 50;
    } else {
        if (paramPercents >= 50) {
            /* should never happen but... */
            paramPercents = 49;
        }
        percentage += paramPercents;
    }
    return percentage;
}

From source file:com.epam.dlab.backendapi.core.commands.CommandExecutorMockAsync.java

public void run() {
    log.debug("Run OS command for user {} with UUID {}: {}", user, uuid, SecurityUtils.hideCreds(command));

    responseFileName = null;//from  w  w  w . ja v  a  2 s  .c o  m
    parser = new CommandParserMock(command, uuid);
    log.debug("Parser is {}", SecurityUtils.hideCreds(parser.toString()));
    DockerAction action = DockerAction.of(parser.getAction());
    log.debug("Action is {}", action);

    if (parser.isDockerCommand()) {
        if (action == null) {
            throw new DlabException("Docker action not defined");
        }

        sleep(500);

        try {
            switch (action) {
            case DESCRIBE:
                describe();
                break;
            case CREATE:
            case START:
            case STOP:
            case TERMINATE:
            case GIT_CREDS:
            case CREATE_IMAGE:
                action(user, action);
                break;
            case CONFIGURE:
            case REUPLOAD_KEY:
                sleep(1000);
                action(user, action);
                break;
            case STATUS:
                parser.getVariables().put("list_resources", getResponseStatus(true));
                action(user, action);
                break;
            case LIB_LIST:
                action(user, action);
                copyFile(String.format("mock_response/%s/notebook_lib_list_pkgs.json", cloudProvider.getName()),
                        String.join("_", "notebook", uuid, "all_pkgs") + JSON_FILE_ENDING,
                        parser.getResponsePath());
                break;
            case LIB_INSTALL:
                parser.getVariables().put("lib_install", getResponseLibInstall(true));
                action(user, action);
                break;
            default:
                break;
            }
        } catch (Exception e) {
            String msg = "Cannot execute command for user " + user + " with UUID " + uuid + ". "
                    + e.getLocalizedMessage();
            log.error(msg, e);
            throw new DlabException(msg, e);
        }
    } else {
        final String scriptName = StringUtils
                .substringBefore(Paths.get(parser.getCommand()).getFileName().toString(), ".");
        String templateFileName = "mock_response/" + cloudProvider.getName() + '/' + scriptName
                + JSON_FILE_ENDING;
        responseFileName = getAbsolutePath(parser.getResponsePath(),
                scriptName + user + "_" + parser.getRequestId() + JSON_FILE_ENDING);
        setResponse(templateFileName, responseFileName);
    }

}

From source file:com.norconex.collector.http.url.impl.DefaultURLExtractor.java

private String extractURL(final UrlParts urlParts, final String rawURL) {
    if (rawURL == null) {
        return null;
    }//from ww  w  .  j  ava2  s .  co  m
    String url = rawURL;
    if (url.startsWith("//")) {
        // this is URL relative to protocol
        url = urlParts.protocol + StringUtils.substringAfter(url, "//");
    } else if (url.startsWith("/")) {
        // this is a URL relative to domain name
        url = urlParts.absoluteBase + url;
    } else if (url.startsWith("?") || url.startsWith("#")) {
        // this is a relative url and should have the full page base
        url = urlParts.documentBase + url;
    } else if (!url.contains("://")) {
        if (urlParts.relativeBase.endsWith("/")) {
            // This is a URL relative to the last URL segment
            url = urlParts.relativeBase + url;
        } else {
            url = urlParts.relativeBase + "/" + url;
        }
    }
    //TODO have configurable whether to strip anchors.
    url = StringUtils.substringBefore(url, "#");
    return url;
}

From source file:com.zc.orm.hibernate.HibernateDao.java

private String prepareCountHql(String orgHql) {
    String fromHql = orgHql;//from   w ww . java2 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:com.neatresults.mgnltweaks.neatu2b.ui.form.field.U2BField.java

/**
 * Initialize the field. <br>/*from   w w  w.j  a v a2 s. c  o m*/
 * Create as many configured Field as we have related values already stored.
 */
@Override
protected void initFields(final PropertysetItem newValue) {
    root.removeAllComponents();
    final TextField id = createTextField("Id", newValue);
    root.addComponent(id);
    final TextField title = createTextField("Title", newValue);
    root.addComponent(title);

    final TextFieldDefinition def = new TextFieldBuilder("description").label("Description").rows(3)
            .definition();
    final TextArea description = (TextArea) createLocalField(def, newValue.getItemProperty(def.getName()),
            false);
    newValue.addItemProperty(def.getName(), description.getPropertyDataSource());
    description.setNullRepresentation("");
    description.setWidth("100%");
    description.setNullSettingAllowed(true);
    root.addComponent(description);

    HorizontalLayout ddLine = new HorizontalLayout();
    final TextField publishedAt = createTextField("Published", newValue);
    ddLine.addComponent(publishedAt);
    final TextField duration = createTextField("Duration", newValue);
    ddLine.addComponent(duration);
    ddLine.addComponent(createTextField("Definition", newValue));

    Button fetchButton = new Button("Fetch metadata");
    fetchButton.addStyleName("magnoliabutton");
    fetchButton.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(ClickEvent event) {

            String idStr = id.getValue();
            // extract id from url when whole url is passed
            if (idStr.startsWith("http")) {
                idStr = StringUtils.substringBefore(StringUtils.substringAfter(idStr, "?v="), "&");
            }

            U2BService service = null;
            try {
                RestEasyClient client = (RestEasyClient) restClientRegistry.getRestClient("youtube");
                service = client.getClientService(U2BService.class);
            } catch (RegistrationException e) {
                log.error("Failed to get a client for [" + U2BService.class.getName() + "] with: "
                        + e.getMessage(), e);
            }
            if (service != null) {
                String key = u2bModule.getGoogleKey();
                JsonNode response = service.meta(idStr, "snippet", key);
                try {
                    if (response.get("items").getElements().hasNext()) {
                        JsonNode videoItem = response.get("items").getElements().next();
                        String descriptionStr = videoItem.get("snippet").get("description").getTextValue();
                        newValue.getItemProperty("description").setValue(descriptionStr);
                        String titleStr = videoItem.get("snippet").get("title").getTextValue();
                        newValue.getItemProperty("title").setValue(titleStr);
                        Iterator<Entry<String, JsonNode>> thumbs = videoItem.get("snippet").get("thumbnails")
                                .getFields();
                        while (thumbs.hasNext()) {
                            Entry<String, JsonNode> entry = thumbs.next();
                            newValue.getItemProperty(entry.getKey() + "Url")
                                    .setValue(entry.getValue().get("url").getTextValue());
                            newValue.getItemProperty(entry.getKey() + "Width")
                                    .setValue("" + entry.getValue().get("width").getLongValue());
                            newValue.getItemProperty(entry.getKey() + "Height")
                                    .setValue("" + entry.getValue().get("height").getLongValue());
                        }
                        String publishedAtStr = videoItem.get("snippet").get("publishedAt").getTextValue();
                        newValue.getItemProperty("published").setValue(publishedAtStr);
                    }
                } catch (Exception e) {
                    log.error("Failed to parse the video metadata.", e);
                }

                response = service.meta(idStr, "contentDetails", key);
                try {
                    if (response.get("items").getElements().hasNext()) {
                        JsonNode videoItem = response.get("items").getElements().next();
                        String durationStr = videoItem.get("contentDetails").get("duration").getTextValue();
                        newValue.getItemProperty("duration").setValue(durationStr);
                        String definition = videoItem.get("contentDetails").get("definition").getTextValue();
                        newValue.getItemProperty("definition").setValue(definition);
                    }
                } catch (Exception e) {
                    log.error("Failed to parse the video duration.", e);
                }
            }
        }
    });

    ddLine.addComponent(fetchButton);
    ddLine.setWidth(100, Unit.PERCENTAGE);
    ddLine.setHeight(-1, Unit.PIXELS);
    ddLine.setComponentAlignment(fetchButton, Alignment.BOTTOM_RIGHT);
    root.addComponent(ddLine);

    PropertysetItem item = (PropertysetItem) getPropertyDataSource().getValue();
    root.addComponent(createEntryComponent("default", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("standard", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("medium", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("high", item), root.getComponentCount() - 1);
    root.addComponent(createEntryComponent("maxres", item), root.getComponentCount() - 1);
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.deck.DeckProfileFactory.java

@Override
protected void setProfile(Profile profile, DeploymentConfiguration deploymentConfiguration,
        SpinnakerRuntimeSettings endpoints) {
    StringResource configTemplate = new StringResource(profile.getBaseContents());
    UiSecurity uiSecurity = deploymentConfiguration.getSecurity().getUiSecurity();
    profile.setUser(ApacheSettings.APACHE_USER);

    Features features = deploymentConfiguration.getFeatures();
    Map<String, String> bindings = new HashMap<>();
    String version = deploymentConfiguration.getVersion();

    // Configure global settings
    bindings.put("gate.baseUrl", endpoints.getServices().getGate().getBaseUrl());
    bindings.put("timezone", deploymentConfiguration.getTimezone());
    bindings.put("version", deploymentConfiguration.getVersion());

    Optional<Versions.Version> validatedVersion = versionsService.getVersions().getVersion(version);

    validatedVersion.ifPresent(v -> {
        String changelog = v.getChangelog();
        bindings.put("changelog.gist.id", changelog.substring(changelog.lastIndexOf("/") + 1));
        bindings.put("changelog.gist.name", "changelog.md");
    });/*  ww w.  j  a v  a2  s. co  m*/

    // Configure feature-flags
    bindings.put("features.auth", Boolean.toString(features.isAuth(deploymentConfiguration)));
    bindings.put("features.chaos", Boolean.toString(features.isChaos()));
    bindings.put("features.jobs", Boolean.toString(features.isJobs()));
    bindings.put("features.fiat",
            Boolean.toString(deploymentConfiguration.getSecurity().getAuthz().isEnabled()));

    // Configure Kubernetes
    KubernetesProvider kubernetesProvider = deploymentConfiguration.getProviders().getKubernetes();
    bindings.put("kubernetes.default.account", kubernetesProvider.getPrimaryAccount());
    bindings.put("kubernetes.default.namespace", "default");
    bindings.put("kubernetes.default.proxy", "localhost:8001");

    // Configure GCE
    GoogleProvider googleProvider = deploymentConfiguration.getProviders().getGoogle();
    bindings.put("google.default.account", googleProvider.getPrimaryAccount());
    bindings.put("google.default.region", "us-central1");
    bindings.put("google.default.zone", "us-central1-f");

    // Configure Azure
    AzureProvider azureProvider = deploymentConfiguration.getProviders().getAzure();
    bindings.put("azure.default.account", azureProvider.getPrimaryAccount());
    bindings.put("azure.default.region", "westus");

    // Configure Appengine
    AppengineProvider appengineProvider = deploymentConfiguration.getProviders().getAppengine();
    bindings.put("appengine.default.account", appengineProvider.getPrimaryAccount());
    bindings.put("appengine.enabled", Boolean.toString(appengineProvider.getPrimaryAccount() != null));

    // Configure DC/OS
    final DCOSProvider dcosProvider = deploymentConfiguration.getProviders().getDcos();
    bindings.put("dcos.default.account", dcosProvider.getPrimaryAccount());
    //TODO(willgorman) need to set the proxy url somehow

    // Configure Openstack
    OpenstackProvider openstackProvider = deploymentConfiguration.getProviders().getOpenstack();
    bindings.put("openstack.default.account", openstackProvider.getPrimaryAccount());
    if (openstackProvider.getPrimaryAccount() != null) {
        OpenstackAccount openstackAccount = (OpenstackAccount) accountService.getProviderAccount(
                deploymentConfiguration.getName(), "openstack", openstackProvider.getPrimaryAccount());
        //Regions in openstack are a comma separated list. Use the first as primary.
        String firstRegion = StringUtils.substringBefore(openstackAccount.getRegions(), ",");
        bindings.put("openstack.default.region", firstRegion);
    }

    profile.appendContents(configTemplate.setBindings(bindings).toString())
            .setRequiredFiles(backupRequiredFiles(uiSecurity, deploymentConfiguration.getName()));
}

From source file:net.eledge.android.europeana.search.SearchController.java

public List<FacetItem> getBreadcrumbs(Context context) {
    List<FacetItem> breadcrumbs = new ArrayList<>();
    FacetItem crumb;//from  ww w.  j a v  a2s.c o m
    for (String term : terms) {
        crumb = new FacetItem();
        crumb.itemType = FacetItemType.BREADCRUMB;
        crumb.facetType = FacetType.TEXT;
        crumb.description = term;
        crumb.facet = term;
        if (StringUtils.contains(term, ":")) {
            FacetType type = FacetType.safeValueOf(StringUtils.substringBefore(term, ":"));
            if (type != null) {
                crumb.facetType = type;
                crumb.description = StringUtils
                        .capitalize(StringUtils.lowerCase(GuiUtils.getString(context, type.resId))) + ":"
                        + type.createFacetLabel(context, StringUtils.substringAfter(term, ":"));
            }
        }
        breadcrumbs.add(crumb);
    }
    return breadcrumbs;
}

From source file:com.opensymphony.xwork2.util.finder.UrlSet.java

/**
 * Try to find a classes directory inside a war file add its normalized url to this set
 *///from   w w w.ja va  2 s.c  om
public UrlSet includeClassesUrl(ClassLoaderInterface classLoaderInterface, FileProtocolNormalizer normalizer)
        throws IOException {
    Enumeration<URL> rootUrlEnumeration = classLoaderInterface.getResources("");
    while (rootUrlEnumeration.hasMoreElements()) {
        URL url = rootUrlEnumeration.nextElement();
        String externalForm = StringUtils.removeEnd(url.toExternalForm(), "/");
        if (externalForm.endsWith(".war/WEB-INF/classes")) {
            //if it is inside a war file, get the url to the file
            externalForm = StringUtils.substringBefore(externalForm, "/WEB-INF/classes");
            URL warUrl = new URL(externalForm);
            URL normalizedUrl = normalizer.normalizeToFileProtocol(warUrl);
            URL finalUrl = ObjectUtils.defaultIfNull(normalizedUrl, warUrl);

            Map<String, URL> newUrls = new HashMap<String, URL>(this.urls);
            if ("jar".equals(finalUrl.getProtocol()) || "file".equals(finalUrl.getProtocol())) {
                newUrls.put(finalUrl.toExternalForm(), finalUrl);
            }
            return new UrlSet(newUrls);
        }
    }

    return this;
}

From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImpl.java

@Override
public void addAuthToHttpRequest(HttpRequestBase httpRequestBase, Map<Object, Object> context) {

    String uri = httpRequestBase.getURI().toString();

    String instance = null;//  ww  w.j  a v a  2 s  .  c o  m
    String envelope = null;
    String requestURLHost = null;
    Integer fileId = null;
    String authentication = null;
    String sessionId = null;

    if (uri == null) {
        return;
    }

    // load bf context attributes
    if (context.get("instance") != null) {
        instance = (String) context.get("instance");
    }
    if (context.get("envelope") != null) {
        envelope = (String) context.get("envelope");
    }
    if (context.get(BF_REQUEST_URL_ATTRIBUTE) != null) {
        try {
            URI requestURI = new URI((String) context.get(BF_REQUEST_URL_ATTRIBUTE));
            requestURLHost = StringUtils.substringBefore(requestURI.toString(), requestURI.getHost())
                    + requestURI.getHost();
            LOGGER.info("bF requestURLHost= " + requestURLHost);
        } catch (URISyntaxException e) {
            LOGGER.warn("requestURL is not valid URL: " + context.get(BF_REQUEST_URL_ATTRIBUTE));
        }
    }
    if (context.get("fileId") != null) {
        fileId = Integer.valueOf((String) context.get("fileId"));
    }
    // http session attribute stored in betterform context
    if (context.get(BF_HTTP_SESSION_ATTRIBUTE) != null) {
        sessionId = (String) context.get(BF_HTTP_SESSION_ATTRIBUTE);
    }

    LOGGER.info("Get resource from XForm: " + uri);

    if (uri.startsWith(requestURLHost)) {
        // check if the request on the same (webq) host is done in the same session. Fix session id if required.
        if (sessionId != null) {
            validateSessionIdInRequestHeader(context, sessionId);
            LOGGER.info("Get resource from: " + uri);
        }
    } else {
        // add auth info only for URIs that are not on the same host.
        if (fileId != null && sessionId != null) {
            LOGGER.debug("Check if user is logged in to get resource for fileId=" + fileId);
            if (!context.containsKey(WEBQ_AUTH_ATTRIBUTE)) {
                // check if user is logged in - ask auth info from user_xml file table
                UserFile userFile = userFileService.getById(fileId);
                if (userFile.isAuthorized()) {
                    String authorizationInfo = userFile.getAuthorization();
                    String cookiesInfo = userFile.getCookies();
                    if (StringUtils.isNotEmpty(authorizationInfo)) {
                        authentication = "Authorization=" + authorizationInfo;
                    } else if (StringUtils.isNotEmpty(cookiesInfo)) {
                        authentication = "Cookie=" + cookiesInfo;
                    }
                }
                context.put(WEBQ_AUTH_ATTRIBUTE, authentication);
                LOGGER.debug("Store basic auth info in context for fileId=" + fileId);
            } else {
                // auth info stored in context
                authentication = context.get(WEBQ_AUTH_ATTRIBUTE) != null
                        ? (String) context.get(WEBQ_AUTH_ATTRIBUTE)
                        : null;
            }
            // add auth info only if user is logged in
            if (StringUtils.isNotEmpty(authentication)) {
                LOGGER.debug("User is logged in to get resource for fileId=" + fileId);

                String authAttribute = StringUtils.substringBefore(authentication, "=");

                // if the URI starts with instance or envelope URI, then we can use the basic auth retrieved from CDR.
                if (!"Cookie".equals(authAttribute)
                        && ((StringUtils.isNotBlank(instance) && uri.startsWith(instance))
                                || (StringUtils.isNotBlank(envelope) && uri.startsWith(envelope)))) {

                    String authAttributeValues = StringUtils.substringAfter(authentication, "=");
                    // prevent betterForm to overwrite cookies
                    /* Fall back to KnownHosts authorisation (qaaccount) if cookie auth mode is used.
                    // cookie mode does not work on test server.
                    if ("Cookie".equals(authAttribute)) {
                    if (context.containsKey(AbstractHTTPConnector.REQUEST_COOKIE)) {
                        context.remove(AbstractHTTPConnector.REQUEST_COOKIE);
                    }
                    }
                    */
                    httpRequestBase.addHeader(authAttribute, authAttributeValues);
                    LOGGER.info("Add " + authAttribute + " from session to URL: " + uri);
                } else {
                    // check if we have known host in db
                    KnownHost knownHost = knownHostsService.getKnownHost(uri);
                    if (knownHost != null) {
                        // add ticket parameter to request URI if needed
                        if (knownHost
                                .getAuthenticationMethod() == KnownHostAuthenticationMethod.REQUEST_PARAMETER) {
                            LOGGER.info("Add ticket parameter from known hosts to URL: " + uri);
                            uri = getUrlWithAuthParam(uri, knownHost);
                            if (!uri.equals(httpRequestBase.getURI().toString())) {
                                try {
                                    httpRequestBase.setURI(new URI(uri));
                                } catch (URISyntaxException e) {
                                    LOGGER.error("Unable to add known host ticket parameter for URI:" + uri);
                                    e.printStackTrace();
                                }
                            }
                        } else if (knownHost.getAuthenticationMethod() == KnownHostAuthenticationMethod.BASIC) {
                            // Add basic authorisation if needed
                            try {
                                LOGGER.info("Add basic auth from known hosts to URL: " + uri);
                                httpRequestBase.addHeader("Authorization", "Basic " + Base64.encodeBase64String(
                                        (knownHost.getKey() + ":" + knownHost.getTicket()).getBytes("utf-8"))
                                        .replaceAll("\n", ""));
                            } catch (UnsupportedEncodingException e) {
                                LOGGER.warn("UnsupportedEncodingException: utf-8");
                            }
                        }
                    }
                }
            }
        }
    }
}