Java Code Examples for org.apache.commons.lang3.StringUtils#chomp()

The following examples show how to use org.apache.commons.lang3.StringUtils#chomp() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicAuth.java    From apiman with Apache License 2.0 6 votes vote down vote up
private static AuthProvider authenticateBasic(JsonObject apimanConfig) {
    return (authInfo, resultHandler) -> {
        String storedUsername = apimanConfig.getString("username");
        String storedPassword = apimanConfig.getString("password");

        if (storedUsername == null || storedPassword == null) {
            resultHandler.handle(Future.failedFuture("Credentials not set in configuration."));
            return;
        }

        String username = authInfo.getString("username");
        String password = StringUtils.chomp(authInfo.getString("password"));

        if (storedUsername.equals(username) && storedPassword.equals(password)) {
            resultHandler.handle(Future.succeededFuture());
        } else {
            resultHandler.handle(Future.failedFuture("No such user, or password incorrect."));
        }
    };
}
 
Example 2
Source File: ItemAddListener.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private String[] returnMatrixChoices(ItemBean bean,String str){
 String[] result=null,temp=null;
 if ("row".equals(str))
  temp = bean.getRowChoices().split(System.getProperty("line.separator"));
 else 
  temp = bean.getColumnChoices().split(System.getProperty("line.separator"));

 //remove the empty string
 List<String> stringList = new ArrayList<String>();

 for(String string : temp) {
  if(string != null && string.trim().length() > 0) {
	  stringList.add(string);
  }
 }
 temp = stringList.toArray(new String[stringList.size()]);	  
 result = new String[temp.length];
 for (int i=0; i<temp.length;i++){
  //remove new line
  result[i] = StringUtils.chomp(temp[i]);
 }

 return result;

}
 
Example 3
Source File: StringFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(List<Object> strings) {

  if(strings == null || strings.size() == 0 ) {
    throw new IllegalArgumentException("[CHOMP] missing argument: string to be chopped");
  }
  String var = strings.get(0) == null?null: (String) strings.get(0);
  if(var == null) {
    return null;
  }
  else if(var.length() == 0) {
    return var;
  }
  else {
    return StringUtils.chomp(var);
  }
}
 
Example 4
Source File: SolrCommandRunner.java    From owltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Used for reading the lego files to be used for loading complex annotations.
 * 
 * @param opts
 * @throws Exception
 */
@CLIMethod("--read-ca-list")
public void processCAFiles(Opts opts) throws Exception {
	caFiles = new ArrayList<String>();
	List<String> files = opts.nextList();
	for (String fstr : files) {
		LOG.info("Using file for LEGO/CA: " + fstr);
		// Read file line by line, getting the model locations out.
		File file = new File(fstr);
		List<String> lines = FileUtils.readLines(file, "UTF-8");
		for (String line : lines) {
			String caloc = StringUtils.chomp(line);
			LOG.info("\tAdd file: " + caloc);
			caFiles.add(caloc);
		}
	}
}
 
Example 5
Source File: ItemAddListener.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
private String[] returnMatrixChoices(ItemBean bean,String str){
 String[] result=null,temp=null;
 if ("row".equals(str))
  temp = bean.getRowChoices().split(System.getProperty("line.separator"));
 else 
  temp = bean.getColumnChoices().split(System.getProperty("line.separator"));

 //remove the empty string
 List<String> stringList = new ArrayList<String>();

 for(String string : temp) {
  if(string != null && string.trim().length() > 0) {
	  stringList.add(string);
  }
 }
 temp = stringList.toArray(new String[stringList.size()]);	  
 result = new String[temp.length];
 for (int i=0; i<temp.length;i++){
  //remove new line
  result[i] = StringUtils.chomp(temp[i]);
 }

 return result;

}
 
Example 6
Source File: FTPClient.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getModificationTime(final String file) throws IOException {
    final String status = super.getModificationTime(file);
    if(null == status) {
        throw new FTPException(this.getReplyCode(), this.getReplyString());
    }
    return StringUtils.chomp(status.substring(3).trim());
}
 
Example 7
Source File: RemoveCarriageReturnFromString.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void remove_carriage_return_apache() {

	String randomSentence = "The pocket reflects "
			+ "over an intimate. \r";

	String cleanString = StringUtils.chomp(randomSentence);

	assertEquals(
			"The pocket reflects over an intimate. ",
			cleanString);
}
 
Example 8
Source File: BinlogAndOffsetSyncPoint.java    From fountain with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(byte[] buf) {
    String info = new String(buf);
    info = StringUtils.chomp(info);
    String[] array = info.split(";");
    for (String val : array) {
        MysqlSyncPoint pt = new MysqlSyncPoint();
        pt.fromString(val);
        syncPointGroup.add(pt);
    }
}
 
Example 9
Source File: TextMarkupDocumentReader.java    From obevo with Apache License 2.0 5 votes vote down vote up
private MutableList<Pair<String, String>> splitIntoMainSections(String text, ImmutableList<String> elementsToCheck, String elementPrefix) {
    MutableList<Pair<String, String>> outerSections = Lists.mutable.empty();
    String nextSectionName = null;
    boolean startOfSearch = true;

    // here, we go in a loop searching for the next referenc of "[elementPrefix] [sectionName]", e.g. //// CHANGE
    // By each of those points, we split those into separate text sections and return back to the client.
    // We aim to preserve the line breaks found when parsing the sections
    while (text != null) {
        String currentSectionName = nextSectionName;
        String currentSectionText;

        int earliestIndex = Integer.MAX_VALUE;

        for (String firstLevelElement : elementsToCheck) {
            // on the first search, the text may start w/ the section; hence, we set the search fromIndex param to 0.
            // Subsequently, the index picks up at the beginning of the next section; hence, we must start
            // the search at the next character, so the fromIndex param is 1
            int index = text.indexOf(elementPrefix + " " + firstLevelElement, startOfSearch ? 0 : 1);

            if (index != -1 && index < earliestIndex) {
                earliestIndex = index;
                nextSectionName = firstLevelElement;
            }
        }

        startOfSearch = false;

        if (earliestIndex == Integer.MAX_VALUE) {
            currentSectionText = StringUtils.chomp(text);
            text = null;
        } else {
            currentSectionText = StringUtils.chomp(text.substring(0, earliestIndex));
            text = text.substring(earliestIndex);
        }

        outerSections.add(Tuples.pair(currentSectionName, currentSectionText));
    }
    return outerSections;
}
 
Example 10
Source File: LoggingProtocolCommandListener.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void protocolCommandSent(final ProtocolCommandEvent event) {
    final String message = StringUtils.chomp(event.getMessage());
    if(message.startsWith(FTPCmd.PASS.name())) {
        this.log(Type.request, String.format("%s %s", FTPCmd.PASS.name(),
                StringUtils.repeat("*", StringUtils.length(StringUtils.removeStart(message, FTPCmd.PASS.name())))));
    }
    else {
        this.log(Type.request, message);
    }
}
 
Example 11
Source File: BaiduGroupIdSyncPoint.java    From fountain with Apache License 2.0 4 votes vote down vote up
@Override
public void parse(byte[] buf) {
    String value = new String(buf);
    value = StringUtils.chomp(value);
    groupId = new BigInteger(value);
}
 
Example 12
Source File: GtIdSyncPoint.java    From fountain with Apache License 2.0 4 votes vote down vote up
@Override
public void parse(byte[] buf) {
    String value = new String(buf);
    value = StringUtils.chomp(value);
    this.gtIdSet = GtIdSet.buildFromString(value);
}
 
Example 13
Source File: AeroRemoteApiController.java    From webanno with Apache License 2.0 4 votes vote down vote up
private CAS createCompatibleCas(long aProjectId, long aDocumentId, MultipartFile aFile,
        Optional<String> aFormatId)
    throws RemoteApiException, ClassNotFoundException, IOException, UIMAException
{
    Project project = getProject(aProjectId);
    SourceDocument document = getDocument(project, aDocumentId);

    // Check if the format is supported
    String format = aFormatId.orElse(FORMAT_DEFAULT);
    if (!importExportService.getReadableFormatById(format).isPresent()) {
        throw new UnsupportedFormatException(
                "Format [%s] not supported. Acceptable formats are %s.", format,
                importExportService.getReadableFormats().stream()
                        .map(FormatSupport::getId).sorted().collect(Collectors.toList()));
    }

    // Convert the uploaded annotation document into a CAS
    File tmpFile = null;
    CAS annotationCas;
    try {
        tmpFile = File.createTempFile("upload", ".bin");
        aFile.transferTo(tmpFile);
        annotationCas = importExportService.importCasFromFile(tmpFile, project, format);
    }
    finally {
        if (tmpFile != null) {
            FileUtils.forceDelete(tmpFile);
        }
    }
    
    // Check if the uploaded file is compatible with the source document. They are compatible
    // if the text is the same and if all the token and sentence annotations have the same
    // offsets.
    CAS initialCas = documentService.createOrReadInitialCas(document);
    String initialText = initialCas.getDocumentText();
    String annotationText = annotationCas.getDocumentText();
    
    // If any of the texts contains tailing line breaks, we ignore that. We assume at the moment
    // that nobody will have created annotations over that trailing line breaks.
    initialText = StringUtils.chomp(initialText);
    annotationText = StringUtils.chomp(annotationText);
    
    if (ObjectUtils.notEqual(initialText, annotationText)) {
        int diffIndex = StringUtils.indexOfDifference(initialText, annotationText);
        String expected = initialText.substring(diffIndex,
                Math.min(initialText.length(), diffIndex + 20));
        String actual = annotationText.substring(diffIndex,
                Math.min(annotationText.length(), diffIndex + 20));
        throw new IncompatibleDocumentException(
                "Text of annotation document does not match text of source document at offset "
                        + "[%d]. Expected [%s] but found [%s].",
                diffIndex, expected, actual);
    }
    
    // Just in case we really had to chomp off a trailing line break from the annotation CAS,
    // make sure we copy over the proper text from the initial CAS
    // NOT AT HOME THIS YOU SHOULD TRY
    // SETTING THE SOFA STRING FORCEFULLY FOLLOWING THE DARK SIDE IS!
    forceOverwriteSofa(annotationCas, initialCas.getDocumentText());
    
    Collection<AnnotationFS> annotationSentences = selectSentences(annotationCas);
    Collection<AnnotationFS> initialSentences = selectSentences(initialCas);
    if (annotationSentences.size() != initialSentences.size()) {
        throw new IncompatibleDocumentException(
                "Expected [%d] sentences, but annotation document contains [%d] sentences.",
                initialSentences.size(), annotationSentences.size());
    }
    assertCompatibleOffsets(initialSentences, annotationSentences);
    
    Collection<AnnotationFS> annotationTokens = selectTokens(annotationCas);
    Collection<AnnotationFS> initialTokens = selectTokens(initialCas);
    if (annotationTokens.size() != initialTokens.size()) {
        throw new IncompatibleDocumentException(
                "Expected [%d] sentences, but annotation document contains [%d] sentences.",
                initialSentences.size(), annotationSentences.size());
    }
    assertCompatibleOffsets(initialTokens, annotationTokens);
    
    return annotationCas;
}
 
Example 14
Source File: SiteSettings.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * @param path path relative to the root of webapp
 * @return Full absolute path including protocol, domain and webapp prefix
 */
public String composeFullAbsolutePath(String path) {
    String webAppUrl = configuration.getConfig(GlobalConfig.class).getWebAppUrl();
    webAppUrl = StringUtils.chomp(webAppUrl, "/"); //remove last slash
    return path.startsWith("/") ? webAppUrl.concat(path) : webAppUrl.concat("/").concat(path);
}
 
Example 15
Source File: MultiLineStringSplitter.java    From obevo with Apache License 2.0 4 votes vote down vote up
@Override
public MutableList<String> valueOf(String inputString) {
    inputString += "\n";  // add sentinel to facilitate line split

    MutableList<SqlToken> sqlTokens = this.tokenParser.parseTokens(inputString);
    sqlTokens = this.collapseWhiteSpaceAndTokens(sqlTokens);

    MutableList<String> finalSplitStrings = Lists.mutable.empty();
    String currentSql = "";

    for (SqlToken sqlToken : sqlTokens) {
        if (sqlToken.getTokenType() == SqlTokenType.COMMENT || sqlToken.getTokenType() == SqlTokenType.STRING) {
            currentSql += sqlToken.getText();
        } else {
            String pattern = splitOnWholeLine ? "(?i)^" + this.splitToken + "$" : this.splitToken;
            MutableList<String> splitStrings =
                    Lists.mutable.with(Pattern.compile(pattern, Pattern.MULTILINE).split(sqlToken.getText()));
            if (splitStrings.isEmpty()) {
                // means that we exactly match
                finalSplitStrings.add(currentSql);
                currentSql = "";
            } else if (splitStrings.size() == 1) {
                currentSql += sqlToken.getText();
            } else {
                splitStrings.set(0, currentSql + splitStrings.get(0));

                if (splitOnWholeLine) {
                    if (splitStrings.size() > 1) {
                        splitStrings.set(0, StringUtils.chomp(splitStrings.get(0)));
                        for (int i = 1; i < splitStrings.size(); i++) {
                            String newSql = splitStrings.get(i);
                            if (newSql.startsWith("\n")) {
                                newSql = newSql.replaceFirst("^\n", "");
                            } else if (newSql.startsWith("\r\n")) {
                                newSql = newSql.replaceFirst("^\r\n", "");
                            }

                            // Chomping the end of each sql due to the split of the GO statement
                            if (i < splitStrings.size() - 1) {
                                newSql = StringUtils.chomp(newSql);
                            }
                            splitStrings.set(i, newSql);
                        }
                    }
                }

                finalSplitStrings.addAll(splitStrings.subList(0, splitStrings.size() - 1));
                currentSql = splitStrings.getLast();
            }
        }
    }

    if (!currentSql.isEmpty()) {
        finalSplitStrings.add(currentSql);
    }

    // accounting for the sentinel
    if (finalSplitStrings.getLast().isEmpty()) {
        finalSplitStrings.remove(finalSplitStrings.size() - 1);
    } else {
        finalSplitStrings.set(finalSplitStrings.size() - 1, StringUtils.chomp(finalSplitStrings.getLast()));
    }

    return finalSplitStrings;
}
 
Example 16
Source File: ScriptBuilder.java    From james-project with Apache License 2.0 4 votes vote down vote up
public void lineEnd() {
    lineBuffer.flip();
    final String text = lineBuffer.toString();
    String[] lines = text.split("\r\n");
    for (String line : lines) {
        String chompedLine = StringUtils.chomp(line);
        if (!ignoreLine(chompedLine)) {
            final String[] words = StringUtils.split(chompedLine);
            if (words.length > 3 && "S:".equalsIgnoreCase(words[0]) && "OK".equalsIgnoreCase(words[2])) {
                final int commandWordIndex;
                if (words[3] == null || !words[3].startsWith("\\[")) {
                    commandWordIndex = 3;
                } else {
                    int wordsCount = 3;
                    while (wordsCount < words.length) {
                        if (words[wordsCount++].endsWith("]")) {
                            break;
                        }
                    }
                    commandWordIndex = wordsCount;
                }
                final String command = words[commandWordIndex];
                final String commandOkPhrase;
                if ("CREATE".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK CREATE completed.";
                } else if ("FETCH".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK FETCH completed.";
                } else if ("APPEND".equalsIgnoreCase(command)) {
                    commandOkPhrase = OK_APPEND_COMPLETED;
                } else if ("DELETE".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK DELETE completed.";
                } else if ("STORE".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK STORE completed.";
                } else if ("RENAME".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK RENAME completed.";
                } else if ("EXPUNGE".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK EXPUNGE completed.";
                } else if ("LIST".equalsIgnoreCase(command)) {
                    commandOkPhrase = "OK LIST completed.";
                } else if ("SELECT".equalsIgnoreCase(command)) {
                    if (commandWordIndex == 3) {
                        commandOkPhrase = "OK SELECT completed.";
                    } else {
                        commandOkPhrase = "OK " + words[3].toUpperCase(Locale.US) + " SELECT completed.";
                    }
                } else {
                    commandOkPhrase = null;
                }
                if (commandOkPhrase != null) {
                    chompedLine = words[0] + " " + words[1] + " " + commandOkPhrase;
                }
            }
            chompedLine = StringUtils.replace(chompedLine, "\\\\Seen \\\\Draft",
                "\\\\Draft \\\\Seen");
            chompedLine = StringUtils.replace(chompedLine, "\\\\Flagged \\\\Deleted",
                "\\\\Deleted \\\\Flagged");
            chompedLine = StringUtils.replace(chompedLine, "\\\\Flagged \\\\Draft",
                "\\\\Draft \\\\Flagged");
            chompedLine = StringUtils.replace(chompedLine, "\\\\Seen \\\\Recent",
                "\\\\Recent \\\\Seen");
            chompedLine = StringUtils.replace(chompedLine, "\\] First unseen\\.",
                "\\](.)*");
            if (chompedLine.startsWith("S: \\* OK \\[UIDVALIDITY ")) {
                chompedLine = "S: \\* OK \\[UIDVALIDITY \\d+\\]";
            } else if (chompedLine.startsWith("S: \\* OK \\[UIDNEXT")) {
                chompedLine = "S: \\* OK \\[PERMANENTFLAGS \\(\\\\Answered \\\\Deleted \\\\Draft \\\\Flagged \\\\Seen\\)\\]";
            }

            System.out.println(chompedLine);
        }
    }
    lineBuffer.clear();
}
 
Example 17
Source File: TextMarkupDocumentReaderOld.java    From obevo with Apache License 2.0 4 votes vote down vote up
private ImmutableList<TextMarkupDocumentSection> parseString(String text, MutableList<String> elementsToCheck, boolean recurse,
        String elementPrefix) {
    MutableList<TextMarkupDocumentSection> sections = Lists.mutable.empty();
    while (true) {
        int earliestIndex = Integer.MAX_VALUE;

        for (String firstLevelElement : elementsToCheck) {
            int index = text.indexOf(elementPrefix + " " + firstLevelElement, 1);
            if (index != -1 && index < earliestIndex) {
                earliestIndex = index;
            }
        }

        if (earliestIndex == Integer.MAX_VALUE) {
            sections.add(new TextMarkupDocumentSection(null, text));
            break;
        } else {
            sections.add(new TextMarkupDocumentSection(null, text.substring(0, earliestIndex)));
            text = text.substring(earliestIndex);
        }
    }
    for (TextMarkupDocumentSection section : sections) {
        MutableMap<String, String> attrs = Maps.mutable.empty();
        MutableSet<String> toggles = Sets.mutable.empty();
        String content = StringUtils.chomp(section.getContent());

        String[] contents = content.split("\\r?\\n", 2);
        String firstLine = contents[0];

        for (String elementToCheck : elementsToCheck) {
            if (firstLine.startsWith(elementPrefix + " " + elementToCheck)) {
                section.setName(elementToCheck);
                String[] args = StringUtils.splitByWholeSeparator(firstLine, " ");
                for (String arg : args) {
                    if (arg.contains("=")) {
                        String[] attr = arg.split("=");
                        if (attr.length > 2) {
                            throw new IllegalArgumentException("Cannot mark = multiple times in a parameter - "
                                    + firstLine);
                        }
                        String attrVal = attr[1];
                        if (attrVal.startsWith("\"") && attrVal.endsWith("\"")) {
                            attrVal = attrVal.substring(1, attrVal.length() - 1);
                        }
                        attrs.put(attr[0], attrVal);
                    } else {
                        toggles.add(arg);
                    }
                }
                if (contents.length > 1) {
                    content = contents[1];
                } else {
                    content = null;
                }
            }
        }
        section.setAttrs(attrs.toImmutable());
        section.setToggles(toggles.toImmutable());

        if (!recurse) {
            section.setContent(content);
        } else if (content != null) {
            ImmutableList<TextMarkupDocumentSection> subsections = this.parseString(content, this.secondLevelElements, false, "//");
            if (subsections.size() == 1) {
                section.setContent(content);
            } else {
                section.setContent(subsections.get(0).getContent());
                section.setSubsections(subsections.subList(1, subsections.size()));
            }
        } else {
            section.setContent(null);
        }
    }

    return sections.toImmutable();
}