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

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

Introduction

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

Prototype

public static String chop(final String str) 

Source Link

Document

Remove the last character from a String.

If the String ends in \r\n , then remove both of them.

 StringUtils.chop(null)          = null StringUtils.chop("")            = "" StringUtils.chop("abc \r")      = "abc " StringUtils.chop("abc\n")       = "abc" StringUtils.chop("abc\r\n")     = "abc" StringUtils.chop("abc")         = "ab" StringUtils.chop("abc\nabc")    = "abc\nab" StringUtils.chop("a")           = "" StringUtils.chop("\r")          = "" StringUtils.chop("\n")          = "" StringUtils.chop("\r\n")        = "" 

Usage

From source file:kenh.expl.functions.Chop.java

public String process(String str) {
    return StringUtils.chop(str);
}

From source file:com.ibm.watson.developer_cloud.WatsonServiceUnitTest.java

/**
 * Gets the mock web server url.//  w  ww .j a va  2s  .com
 *
 * @return the server url
 */
protected String getMockWebServerUrl() {
    return StringUtils.chop(server.url("/").toString());
}

From source file:de.jcup.egradle.core.util.LinkToTypeConverter.java

private void cleanupSlashes(LinkData data) {
    if (data == null) {
        return;/*  www. ja v  a 2  s .c  o  m*/
    }
    String typeName = data.mainName;
    if (typeName == null) {
        return;
    }
    while (typeName.endsWith("/")) {
        typeName = StringUtils.chop(typeName);
    }
    while (typeName.startsWith("/")) {
        typeName = StringUtils.removeStart(typeName, "/");
    }
    data.mainName = typeName;
}

From source file:com.xpn.xwiki.render.macro.TableBuilder.java

public static Table build(String content) {
    Table table = new Table();
    StringTokenizer tokenizer = new StringTokenizer(content, "|\n", true);
    String lastToken = null;//from  w  w w.jav a 2 s  . co  m
    boolean firstCell = true;
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (token.equals("\r")) {
            continue;
        }
        // If a token contains [, then all tokens up to one containing a ] are concatenated. Kind of a block marker.
        if (token.indexOf('[') != -1 && token.indexOf(']') == -1) {
            String linkToken = "";
            while (token.indexOf(']') == -1 && tokenizer.hasMoreTokens()) {
                linkToken += token;
                token = tokenizer.nextToken();
            }
            token = linkToken + token;
        }
        if ("\n".equals(token)) {
            // New line: either new row, or a literal newline.
            lastToken = (lastToken == null) ? "" : lastToken;
            if (!StringUtils.endsWith(lastToken, "\\")) {
                // A new row, not a literal newline.
                // If the last cell didn't contain any data, then it was skipped. Add a blank cell to compensate.
                if ((StringUtils.isEmpty(lastToken) || "|".equals(lastToken)) && !firstCell) {
                    table.addCell(" ");
                }
                table.newRow();
            } else {
                // A continued row, with a literal newline.
                String cell = lastToken;
                // Keep concatenating while the cell data ends with \\
                while (cell.endsWith("\\") && tokenizer.hasMoreTokens()) {
                    token = tokenizer.nextToken();
                    if (!"|".equals(token)) {
                        cell = cell + token;
                    } else {
                        break;
                    }
                }
                firstCell = false;
                table.addCell(cell.trim());
                if (!tokenizer.hasMoreTokens()) {
                    table.newRow();
                }
            }
        } else if (!"|".equals(token)) {
            // Cell data
            if (!token.endsWith("\\")) {
                // If the cell data ends with \\, then it will be continued. Current data is stored in lastToken.
                table.addCell(token.trim());
                firstCell = false;
            } else if (!tokenizer.hasMoreTokens()) {
                // Remove backslashes from the end
                while (token.endsWith("\\")) {
                    token = StringUtils.chop(token);
                }
                table.addCell(token.trim());
            }
        } else if ("|".equals(token)) {
            // Cell delimiter
            if ((StringUtils.isEmpty(lastToken) && firstCell) || "|".equals(lastToken)) {
                // If the last cell didn't contain any data, then it was skipped. Add a blank cell to compensate.
                table.addCell(" ");
                firstCell = false;
            } else if (StringUtils.endsWith(lastToken, "\\")) {
                // The last cell wasn't added because it ended with a continuation mark (\\). Add it now.
                table.addCell(lastToken.trim());
                firstCell = false;
            }
        }
        lastToken = token;
    }

    return table;
}

From source file:com.cognifide.qa.bb.test.actions.BobcatActionsTest.java

@Test
public void whenIPressBackSpaceLastLetterIsRemoved() {
    //when//from  w  ww  .ja va2  s .  com
    actions.sendKeys(inputElement, TEXT_TO_SEND, StringUtils.SPACE, TEXT_TO_SEND, Keys.BACK_SPACE).perform();

    //then
    assertThat(getTextFromInputElement()).endsWith(StringUtils.chop(TEXT_TO_SEND));
}

From source file:com.ibm.watson.apis.conversation_with_discovery.rest.ProxyResourceTest.java

/**
 * Test send message.//from  w w  w  . j  av a 2 s  .  c om
 *
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws InterruptedException the 4interrupted exception
 */
@Test
public void testSendMessage() throws IOException, InterruptedException {

    String text = "I'd like to get a quote to replace my windows";

    MessageResponse mockResponse = loadFixture(FIXTURE, MessageResponse.class);
    ProxyResource proxy = new ProxyResource();

    proxy.setCredentials("dummy", "dummy", StringUtils.chop(server.url("/").toString()));

    server.enqueue(jsonResponse(mockResponse));

    MessageRequest request = new MessageRequest.Builder().inputText(text).build();
    String payload = GsonSingleton.getGsonWithoutPrettyPrinting().toJson(request, MessageRequest.class);

    InputStream inputStream = new ByteArrayInputStream(payload.getBytes("UTF-8"));

    Response jaxResponse = proxy.postMessage(WORKSPACE_ID, inputStream);
    MessageResponse serviceResponse = GsonSingleton.getGsonWithoutPrettyPrinting()
            .fromJson(jaxResponse.getEntity().toString(), MessageResponse.class);

    RecordedRequest mockRequest = server.takeRequest();
    List<String> serviceText = serviceResponse.getText();
    List<String> mockText = serviceResponse.getText();
    assertNotNull(serviceText);
    assertNotNull(mockText);
    assertTrue(serviceText.containsAll(mockText) && mockText.containsAll(serviceText));
    assertEquals(serviceResponse, mockResponse);
    assertEquals(serviceResponse.getTextConcatenated(" "), mockResponse.getTextConcatenated(" "));

    assertEquals(mockRequest.getMethod(), "POST");
    assertNotNull(mockRequest.getHeader(HttpHeaders.AUTHORIZATION));
}

From source file:de.uni.bremen.monty.moco.CompileTestProgramsTest.java

@Test
public void compileProgramTest() throws IOException, InterruptedException {
    final PrintStream bufferOut = System.out;
    final PrintStream bufferErr = System.err;
    final ByteArrayOutputStream outStream = setStdout();
    final ByteArrayOutputStream errorStream = setStdErr(file);

    if (inputFileExists(file)) {
        System.setProperty("testrun.readFromFile", changeFileExtension(file, ".input"));
    }/*from   w w w  .  j a  va 2s.c om*/
    Main.main(new String[] { "-e", file.getAbsolutePath() });

    if (outputFileExists(file)) {
        assertThat(getOutput(errorStream), is(isEmptyString()));
        assertThat(getOutput(outStream), is(expectedResultFromFile(file)));
    } else {
        // chop the last char to not contain /n in the string
        assertThat(StringUtils.chop(getOutput(errorStream)), is(expectedErrorFromFile(file)));
        assertThat(getOutput(outStream), is(isEmptyString()));
    }
    System.clearProperty("testrun.readFromFile");
    System.setOut(bufferOut);
    System.setErr(bufferErr);
}

From source file:kenh.expl.impl.BaseFunction.java

/**
 * Find the method with name <code>process</code> or <code>@Processing</code>
 *///  w  ww .ja  va 2  s.  c o  m
@Override
public Object invoke(Object... params) throws UnsupportedExpressionException {
    Method[] methods = this.getClass().getMethods();

    for (Method method : methods) {
        String name = method.getName();
        Class[] classes = method.getParameterTypes();
        Annotation a = method.getAnnotation(Processing.class);

        if ((name.equals(METHOD) || a != null) && params.length == classes.length) {

            logger.trace("Method: " + method.toGenericString());
            boolean find = true;
            Object[] objs = new Object[params.length];
            for (int i = 0; i < params.length; i++) {
                Class class1 = params[i].getClass();
                Class class2 = classes[i];

                if (class2.isAssignableFrom(class1) || class2 == Object.class) {
                    objs[i] = params[i];

                } else if (class1 == String.class) {
                    try {
                        Object obj = Environment.convert((String) params[i], class2);
                        if (obj == null) {
                            logger.trace("Failure(Convert failure[" + (i + 1) + "-" + class1 + "," + class2
                                    + "]): " + method.toGenericString());
                            find = false;
                            break;
                        } else {
                            objs[i] = obj;
                        }
                    } catch (Exception e) {
                        logger.trace("Failure(Convert exception[" + (i + 1) + "-" + e.getMessage() + "]): "
                                + method.toGenericString());
                        find = false;
                        break;
                        //UnsupportedExpressionException ex = new UnsupportedExpressionException(e);
                        //throw ex;
                    }
                } else {
                    logger.trace("Failure(Class unmatched[" + (i + 1) + "]): " + method.toGenericString());
                    find = false;
                    break;
                }
            }
            if (find) {
                try {
                    return method.invoke(this, objs);
                } catch (Exception e) {
                    if (e instanceof UnsupportedExpressionException)
                        throw (UnsupportedExpressionException) e;
                    else
                        throw new UnsupportedExpressionException(e);
                }
            }
        }
    }

    String paramStr = "";
    for (Object param : params) {
        paramStr += param.getClass().getCanonicalName() + ", ";
    }
    paramStr = StringUtils.defaultIfBlank(StringUtils.chop(StringUtils.trimToEmpty(paramStr)), "<NO PARAM>");

    UnsupportedExpressionException e = new UnsupportedExpressionException(
            "Can't find the method to process.[" + paramStr + "]");
    throw e;
}

From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java

/**
 * /*from w  w  w  .  j  ava 2 s .co  m*/
 * This method is used to rename the classes which names are ending with the
 * letter 's'
 * 
 * @param className-
 *            This parameter having class names to check which are ending
 *            with 's' or not.
 * @return String this returns modified class name
 * 
 */
private String modifyClassName(String className) {
    String newClassName = className;
    if (className.endsWith("s")) {
        if (className.equals(EiffelConstants.DEPENDENCIES)) {
            newClassName = EiffelConstants.DEPENDENCY;
        } else if (className.equals(EiffelConstants.BATCHES)) {
            newClassName = EiffelConstants.BATCH;
        } else if (className.equals(EiffelConstants.PROPERTIES)) {
            newClassName = EiffelConstants.PROPERTY;
        } else {
            newClassName = StringUtils.chop(className);
        }
    }
    return newClassName;
}

From source file:com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl.java

/**
 * The authentication library we are using (SecurityFilter) requires that its URLs do not contain the context path,
 * in order to be usable with <tt>RequestDispatcher.forward</tt>. Since our URL factory include the context path in
 * the generated URLs, we use this method to remove (if needed) the context path.
 * // w w  w .  jav a 2  s.  co  m
 * @param url The URL to process.
 * @param context The ubiquitous XWiki request context.
 * @return A <code>String</code> representation of the contextpath-free URL.
 */
protected String stripContextPathFromURL(URL url, XWikiContext context) {
    String contextPath = context.getWiki().getWebAppPath(context);
    // XWiki uses contextPath in the wrong way, putting a / at the end, and not at the start. Fix this here.
    if (contextPath.endsWith("/") && !contextPath.startsWith("/")) {
        contextPath = "/" + StringUtils.chop(contextPath);
    }

    // URLFactory.getURL applies Util.escapeURL, which might convert the contextPath into an %NN escaped string.
    // Apply the same escape method to compensate this.
    contextPath = Util.escapeURL(contextPath);

    String urlPrefix = url.getProtocol() + "://" + url.getAuthority() + contextPath;
    return StringUtils.removeStart(url.toExternalForm(), urlPrefix);
}