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.adobe.acs.commons.httpcache.keys.AbstractCacheKey.java

protected String makeHierarchyResourcePath(String resourcePath) {
    return StringUtils.substringBefore(resourcePath, "/" + JcrConstants.JCR_CONTENT);
}

From source file:com.thinkbiganalytics.util.PartitionKey.java

/**
 * if column in formula has a space, surround it with a tick mark
 *//*from  ww w  .j  av  a 2 s .  c  o m*/
private void surroundFormulaColumnWithTick() {
    int idx = formula.indexOf("(");
    String column = StringUtils.substringBetween(formula, "(", ")");
    if (StringUtils.isNotBlank(column) && column.charAt(0) != '`') {
        column = HiveUtils.quoteIdentifier(column);
        StringBuffer sb = new StringBuffer();
        sb.append(StringUtils.substringBefore(formula, "(")).append("(").append(column).append(")");
        formula = sb.toString();
    }

}

From source file:ambroafb.general.mapeditor.MapEditor.java

public MapEditor() {
    this.setEditable(true);
    itemsMap = new HashMap<>();
    delimiter = " : "; // default value of delimiter
    keyPattern = ""; // (?<![\\d-])\\d+
    valuePattern = ""; // [0-9]{1,13}(\\.[0-9]*)?
    keySpecChars = "";
    valueSpecChars = "";

    this.setCellFactory((ListView<MapEditorElement> param) -> new CustomCell());

    removeElement = (MapEditorElement elem) -> {
        if (itemsMap.containsKey(elem.getKey())) {
            itemsMap.remove(elem.getKey());
            if (getValue() != null && getValue().compare(elem) == 0) {
                getEditor().setText(delimiter);
            }/*from  w  ww .  j a  v a 2s  .c o m*/
            getItems().remove(elem);
        }
    };

    editElement = (MapEditorElement elem) -> {
        getSelectionModel().select(-1);
        getEditor().setText(elem.getKey() + delimiter + elem.getValue());
        itemsMap.remove(elem.getKey());
        getItems().remove(elem);
    };

    // Never hide comboBox items listView:
    this.setSkin(new ComboBoxListViewSkin(this) {
        @Override
        protected boolean isHideOnClickEnabled() {
            return false;
        }
    });

    // Control textField input.
    TextField editor = getEditor();
    editor.setText(delimiter);
    editor.textProperty()
            .addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
                if (newValue == null || newValue.isEmpty() || newValue.equals(delimiter)) {
                    editor.setText(delimiter);
                } else if (!newValue.contains(delimiter)) {
                    editor.setText(oldValue);
                } else {
                    String keyInput = StringUtils.substringBefore(newValue, delimiter).trim();
                    String valueInput = StringUtils.substringAfter(newValue, delimiter).trim();

                    if (!keyInput.isEmpty() && !Pattern.matches(keyPattern, keyInput)) {
                        keyInput = StringUtils.substringBefore(oldValue, delimiter).trim();
                    }
                    if (!valueInput.isEmpty() && !Pattern.matches(valuePattern, valueInput)) {
                        valueInput = StringUtils.substringAfter(oldValue, delimiter).trim();
                    }

                    editor.setText(keyInput + delimiter + valueInput);
                }
            });

    this.setConverter(new StringConverter<MapEditorElement>() {
        @Override
        public String toString(MapEditorElement object) {
            if (object == null) {
                return delimiter;
            }
            return object.getKey() + delimiter + object.getValue();
        }

        @Override
        public MapEditorElement fromString(String input) {
            MapEditorElement result = null;
            if (input != null && input.contains(delimiter)) {
                result = getNewInstance();
                if (result == null)
                    return null;
                String keyInput = StringUtils.substringBefore(input, delimiter).trim();
                String valueInput = StringUtils.substringAfter(input, delimiter).trim();
                if (!keyInput.isEmpty()) {
                    result.setKey(keyInput);
                }
                if (!valueInput.isEmpty()) {
                    result.setValue(valueInput);
                }
                boolean keyOutOfSpec = keySpecChars.isEmpty()
                        || !StringUtils.containsOnly(result.getKey(), keySpecChars);
                boolean valueOutOfSpec = valueSpecChars.isEmpty()
                        || !StringUtils.containsOnly(result.getValue(), valueSpecChars);
                if (!keyInput.isEmpty() && !valueInput.isEmpty() && !itemsMap.containsKey(keyInput)
                        && (keyOutOfSpec && valueOutOfSpec)) {
                    itemsMap.put(keyInput, result);
                    getItems().add(result);
                    return null;
                }
            }
            return result;
        }
    });

    // Control caret position in textField.
    editor.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent event) -> {
        int caretOldPos = editor.getCaretPosition();
        int delimiterIndex = editor.getText().indexOf(delimiter);
        if (event.getCode().equals(KeyCode.RIGHT)) {
            if (caretOldPos + 1 > delimiterIndex && caretOldPos + 1 <= delimiterIndex + delimiter.length()) {
                editor.positionCaret(delimiterIndex + delimiter.length());
                event.consume();
            }
        } else if (event.getCode().equals(KeyCode.LEFT)) {
            if (caretOldPos - 1 >= delimiterIndex && caretOldPos - 1 < delimiterIndex + delimiter.length()) {
                editor.positionCaret(delimiterIndex);
                event.consume();
            }
        }
    });
}

From source file:com.nesscomputing.service.discovery.server.announce.ConfigStaticAnnouncer.java

private Map<UUID, Map<String, String>> getAnnouncements() {
    final AbstractConfiguration subconfig = config.getConfiguration(CONFIG_ROOT);

    final Iterator<String> keys = subconfig.getKeys();

    final Map<UUID, Map<String, String>> configTree = Maps.newHashMap();

    while (keys.hasNext()) {
        final String key = keys.next();

        final String id = StringUtils.substringBefore(key, ".");

        UUID serviceId;/*from  w w w  . j  av  a2  s. c  o m*/

        try {
            serviceId = UUID.fromString(id);
        } catch (final IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format("Invalid serviceId \"%s\"", id), e);
        }

        Map<String, String> configMap = configTree.get(serviceId);
        if (configMap == null) {
            configTree.put(serviceId, configMap = Maps.newHashMap());
        }

        configMap.put(StringUtils.substringAfter(key, "."), subconfig.getString(key));
    }
    return configTree;
}

From source file:com.adobe.acs.commons.mcp.form.RadioComponent.java

@Override
public Resource buildComponentResource() {
    AbstractResourceImpl component = (AbstractResourceImpl) super.buildComponentResource();
    AbstractResourceImpl options = new AbstractResourceImpl("items", null, null, new ResourceMetadata());
    component.addChild(options);/*  w w w  .j  a  v a 2 s.  co m*/

    String defaultValue = getOption("default").orElse(null);

    getOptions().forEach((value, name) -> {
        final ResourceMetadata meta = new ResourceMetadata();
        final String nodeName = JcrUtil.escapeIllegalJcrChars(value);

        if (value.equals(defaultValue)) {
            meta.put("checked", true);
        }
        meta.put("name", getName());
        meta.put("value", value);
        if (name.contains("::")) {
            String description = StringUtils.substringAfter(name, DESCRIPTION_DELIMITER);
            meta.put("title", description);
            name = StringUtils.substringBefore(name, DESCRIPTION_DELIMITER);
        }
        meta.put("text", name);
        AbstractResourceImpl option = new AbstractResourceImpl("option_" + nodeName,
                "granite/ui/components/foundation/form/radio", "granite/ui/components/foundation/form/field",
                meta);
        options.addChild(option);
    });
    return component;
}

From source file:ch.cyberduck.core.importer.FlashFxpBookmarkCollection.java

@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
    try {/*www.  ja va  2s.com*/
        final BufferedReader in = new BufferedReader(
                new InputStreamReader(file.getInputStream(), Charset.forName("UTF-8")));
        try {
            Host current = null;
            String line;
            while ((line = in.readLine()) != null) {
                if (line.startsWith("[")) {
                    current = new Host(protocols.forScheme(Scheme.ftp));
                    current.getCredentials()
                            .setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
                    Pattern pattern = Pattern.compile("\\[(.*)\\]");
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.matches()) {
                        current.setNickname(matcher.group(1));
                    }
                } else if (StringUtils.isBlank(line)) {
                    this.add(current);
                    current = null;
                } else {
                    if (null == current) {
                        log.warn("Failed to detect start of bookmark");
                        continue;
                    }
                    Scanner scanner = new Scanner(line);
                    scanner.useDelimiter("=");
                    if (!scanner.hasNext()) {
                        log.warn("Missing key in line:" + line);
                        continue;
                    }
                    String name = scanner.next().toLowerCase(Locale.ROOT);
                    if (!scanner.hasNext()) {
                        log.warn("Missing value in line:" + line);
                        continue;
                    }
                    String value = scanner.next();
                    if ("ip".equals(name)) {
                        current.setHostname(StringUtils.substringBefore(value, "\u0001"));
                    } else if ("port".equals(name)) {
                        try {
                            current.setPort(Integer.parseInt(value));
                        } catch (NumberFormatException e) {
                            log.warn("Invalid Port:" + e.getMessage());
                        }
                    } else if ("path".equals(name)) {
                        current.setDefaultPath(value);
                    } else if ("notes".equals(name)) {
                        current.setComment(value);
                    } else if ("user".equals(name)) {
                        current.getCredentials().setUsername(value);
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(in);
        }
    } catch (IOException e) {
        throw new AccessDeniedException(e.getMessage(), e);
    }
}

From source file:com.google.dart.java2dart.processor.JUnitSemanticProcessorTest.java

public void test_assertX() throws Exception {
    translateSingleFile("// filler filler filler filler filler filler filler filler filler filler",
            "package test;", "import junit.framework.TestCase;", "public class Test extends TestCase {",
            "  public void test_x() {", "    Object v;", "    assertNull(v);", "    assertNotNull(v);",
            "    assertEquals(1, v);", "    assertEquals(\"msg\", 1, v);", "    assertSame(2, v);",
            "    assertNotSame(3, v);", "  }", "}");
    runProcessor();//ww  w . jav  a  2 s  .c o  m
    String resultSource = getFormattedSource(unit);
    resultSource = StringUtils.substringBefore(resultSource, "static dartSuite() {");
    assertEquals(toString("class Test extends JUnitTestCase {", "  void test_x() {", "    Object v;",
            "    JUnitTestCase.assertNull(v);", "    JUnitTestCase.assertNotNull(v);",
            "    JUnitTestCase.assertEquals(1, v);", "    JUnitTestCase.assertEqualsMsg(\"msg\", 1, v);",
            "    JUnitTestCase.assertSame(2, v);", "    JUnitTestCase.assertNotSame(3, v);", "  }", "  "),
            resultSource);
}

From source file:com.thinkbiganalytics.ui.service.StandardUiTemplateService.java

public List<AngularModule> loadAngularModuleDefinitionFiles() {
    List<AngularModule> modules = new ArrayList<>();
    fileResourceService.loadResources("classpath*:**/*module-definition.json", (resource) -> {
        try {//from   w w  w. ja va 2 s  .c  o m
            final String json = fileResourceService.resourceAsString(resource);
            DefaultAngularModule module = (json != null)
                    ? ObjectMapperSerializer.deserialize(json, DefaultAngularModule.class)
                    : null;
            String moduleJsUrl = "";
            if (module != null) {
                if (StringUtils.isBlank(module.getModuleJsUrl())) {
                    //attempt to derive it
                    try {
                        String url = resource.getURL().getPath().toString();
                        String modulePath = "";
                        int idx = url.indexOf("/static/js/");
                        if (idx >= 0) {
                            modulePath = url.substring(idx + ("/static/js/".length()));
                        }
                        if (StringUtils.isNotBlank(modulePath)) {
                            moduleJsUrl = StringUtils.substringBefore(modulePath, resource.getFilename())
                                    + "module";
                            modulePath = moduleJsUrl;
                            module.setModuleJsUrl(modulePath);
                        } else {
                            log.error(
                                    "Unable to load Angular Extension Module {}.  Please ensure you have a module.js file located in the same directory as the {} definition file",
                                    resource.getFilename(), resource.getFilename());
                        }

                    } catch (Exception e) {
                        log.error("Unable to load Angular Extension Module ", resource.getFilename(), e);
                    }

                }
                if (StringUtils.isNotBlank(module.getModuleJsUrl())) {
                    modules.add(module);
                }
            }

        } catch (final RuntimeException e) {
            log.error("Failed to parse Angular Extension Module: {}", resource.getFilename(), e);
        }

    });
    return modules;
}

From source file:com.norconex.commons.lang.url.QueryString.java

/**
 * Constructor.  /*www  . j  a va2  s.  c o  m*/
 * It is possible to only supply a query string as opposed to an
 * entire URL.
 * Key and values making up a query string are assumed to be URL-encoded.
 * Will throw a {@link URLException} if the supplied encoding is 
 * unsupported or invalid.
 * @param urlWithQueryString a URL from which to extract a query string.
 * @param encoding character encoding
 */
public QueryString(String urlWithQueryString, String encoding) {
    super(new ListOrderedMap<String, List<String>>());
    if (StringUtils.isBlank(encoding)) {
        this.encoding = CharEncoding.UTF_8;
    } else {
        this.encoding = encoding;
    }
    String paramString = urlWithQueryString;
    if (StringUtils.contains(paramString, "?")) {
        paramString = paramString.replaceAll("(.*?)(\\?)(.*)", "$3");
    }
    String[] paramParts = paramString.split("\\&");
    for (int i = 0; i < paramParts.length; i++) {
        String paramPart = paramParts[i];
        if (StringUtils.contains(paramPart, "=")) {
            String key = StringUtils.substringBefore(paramPart, "=");
            String value = StringUtils.substringAfter(paramPart, "=");
            try {
                addString(URLDecoder.decode(key, this.encoding), URLDecoder.decode(value, this.encoding));
            } catch (UnsupportedEncodingException e) {
                throw new URLException("Cannot URL-decode query string (key=" + key + "; value=" + value + ").",
                        e);
            }
        }
    }
}

From source file:cool.pandora.modeller.DocManifestBuilder.java

/**
 * getBboxForId./*w  w  w  .  j ava2s. c  o m*/
 *
 * @param hocr hOCRData
 * @param id   String
 * @return TitleForId
 */
public static String getBboxForId(final hOCRData hocr, final String id) {
    return StringUtils.substringBefore(StringUtils.substringAfter(hocr.getTitleForId(id), "bbox "), ";");
}