Example usage for org.apache.commons.lang StringUtils chomp

List of usage examples for org.apache.commons.lang StringUtils chomp

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils chomp.

Prototype

public static String chomp(String str) 

Source Link

Document

Removes one newline from end of a String if it's there, otherwise leave it alone.

Usage

From source file:org.archive.io.hdfs.HDFSWriterDocument.java

public String getResponseString() throws UnsupportedEncodingException {
    return StringUtils
            .chomp(new String(getResponseBytes(), getResponseOffset(), getResponseLength(), getValidCharset()));
}

From source file:org.codesearch.commons.plugins.vcs.GitLocalPlugin.java

/**
 * {@inheritDoc}/*ww  w.j a  va2s. c  o m*/
 */
@Override
public FileDto getFile(FileIdentifier fileIdentifier, String revision)
        throws VersionControlPluginException, VcsFileNotFoundException {
    revision = parseRevision(revision);
    String gitIdentifier = revision + ":" + fileIdentifier.getFilePath();
    //Check if file exists
    if (!checkFile(gitIdentifier)) {
        throw new VcsFileNotFoundException(
                "File " + fileIdentifier + "@" + revision + " does not exist. Try pulling new changes.");
    }

    byte[] fileContent = executeGitCommand("show", gitIdentifier);
    String lastRevision = StringUtils.chomp(
            new String(executeGitCommand("log", revision, "-n1", "--pretty=%H", fileIdentifier.getFilePath())));
    String lastAuthor = StringUtils.chomp(new String(
            executeGitCommand("log", revision, "-n1", "--pretty=%an", fileIdentifier.getFilePath())));

    FileDto file = new FileDto();
    file.setContent(fileContent);
    file.setRepository(currentRepository);
    file.setFilePath(fileIdentifier.getFilePath());
    file.setLastAlteration(lastRevision);
    file.setLastAuthor(lastAuthor);
    return file;
}

From source file:org.codesearch.commons.plugins.vcs.GitLocalPlugin.java

/**
 * {@inheritDoc}/*from  w ww .  j a  v  a  2 s.co m*/
 */
@Override
public String getRepositoryRevision() throws VersionControlPluginException {
    return StringUtils.chomp(new String(executeGitCommand("rev-parse", "HEAD")));
}

From source file:org.eclipse.jubula.client.cmd.AbstractCmdlineClient.java

/**
 * writes an output to console//from   w ww.  j  ava 2s  .c o m
 * @param text
 *      Message
 *      @param printTimestamp should a timestamp be printed
 */
public static void printConsoleLn(String text, boolean printTimestamp) {
    if (printTimestamp) {
        Date now = new Date();
        String time = now.toString();
        printConsole(time);
        printConsole(StringConstants.TAB);
    }
    printConsole(StringUtils.chomp(text));
    printConsole(StringConstants.NEWLINE);
}

From source file:org.eclipse.smarthome.io.net.exec.ExecUtil.java

/**
 * <p>/*from  w ww.ja  v  a2 s . c  o  m*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}

From source file:org.eclipse.wb.tests.designer.core.model.util.FactoryCreateActionTest.java

/**
 * Simplest test for preview.// ww w .  j av a 2 s . c  o m
 */
public void test_preview() throws Exception {
    ContainerInfo panel = parseContainer("public class Test extends JPanel {", "  public Test() {",
            "    JButton button = new JButton('text');", "    add(button);", "  }", "}");
    String unitSource = m_lastEditor.getSource();
    ComponentInfo button = panel.getChildrenComponents().get(0);
    // prepare action
    action = new FactoryCreateAction(button);
    generate_configureDefaultTarget();
    // check preview
    generate_configureInvocations(button, new int[] {}, new String[] {}, new int[][] {});
    m_getSource_ignoreSpacesCheck = true;
    String expectedSource = getSourceDQ("  /**", "   * @wbp.factory", "   */",
            "  public static JButton createComponent() {", "    JButton button = new JButton('text');",
            "    return button;", "  }");
    String previewSource = (String) ReflectionUtils.invokeMethod2(action, "getFactoryPreviewSource");
    assertEquals(StringUtils.chomp(expectedSource), previewSource);
    // no changes in parsed unit expected
    assertEditor(unitSource, m_lastEditor);
}

From source file:org.eclipse.wb.tests.designer.core.util.xml.XmlDocumentTest.java

/**
 * @return the XML source for given lines.
 *///  w  w  w . j  a  v a  2  s .c  o m
private String getXMLSource(String... lines) {
    String source = getSourceDQ(lines);
    if (m_removeTrailingEOL) {
        source = StringUtils.chomp(source);
    }
    return source;
}

From source file:org.jahia.services.usermanager.JahiaUserManagerService.java

private String getNewRootUserPwd() throws MalformedURLException, IOException {

    String pwd = null;//from ww w  . ja v a  2  s.  com
    File pwdFile = null;

    if (servletContext.getResource(ROOT_PWD_RESET_FILE_PATH) != null) {
        String path = servletContext.getRealPath(ROOT_PWD_RESET_FILE_PATH);
        pwdFile = path != null ? new File(path) : null;
    } else {
        pwdFile = new File(settingsBean.getJahiaVarDiskPath(), ROOT_PWD_RESET_FILE);
    }
    if (pwdFile != null && pwdFile.exists()) {
        pwd = FileUtils.readFileToString(pwdFile);
        try {
            pwdFile.delete();
        } catch (Exception e) {
            logger.warn("Unable to delete " + pwdFile + " file after resetting root password", e);
        }
    }

    return pwd != null ? StringUtils.chomp(pwd).trim() : null;
}

From source file:org.jahia.services.usermanager.jcr.JCRUserManagerProvider.java

private void checkRootUserPwd() {
    try {//  ww  w.  jav a2  s. c o m
        if (servletContext.getResource(ROOT_PWD_RESET_FILE) != null) {
            InputStream is = servletContext.getResourceAsStream(ROOT_PWD_RESET_FILE);
            try {
                String newPwd = IOUtils.toString(is);
                logger.info("Resetting root user password");
                lookupRootUser().setPassword(StringUtils.chomp(newPwd).trim());
                logger.info("New root user password set.");
            } finally {
                IOUtils.closeQuietly(is);
                try {
                    new File(servletContext.getRealPath(ROOT_PWD_RESET_FILE)).delete();
                } catch (Exception e) {
                    logger.warn(
                            "Unable to delete " + ROOT_PWD_RESET_FILE + " file after resetting root password",
                            e);
                }
            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }
}

From source file:org.jasig.schedassist.impl.oraclecalendar.AbstractOracleCalendarDao.java

/**
 * This function encapsulates the processing of the output from Oracle Calendar
 * by iCal4j./*w  w w.j  av a  2 s .c  o  m*/
 * 
 * This method currently inspects the end of the agenda argument for the presence
 * of the complete string "END:VCALENDAR" (a known bug with the Oracle Calendar APIs presents
 * itself in this fashion) and attempts to repair the agenda before sending to iCal4J.
 * 
 * {@link CalendarBuilder#build(java.io.Reader)} can throw an {@link IOException}; this method wraps the call
 * in try-catch and throws any caught {@link IOException}s wrapped in a {@link ParseException} instead.
 * 
 * @param agenda
 * @return
 * @throws ParserException
 */
protected Calendar parseAgenda(String agenda) throws ParserException {
    final String chomped = StringUtils.chomp(agenda);
    if (!StringUtils.endsWith(chomped, "END:VCALENDAR")) {
        // Oracle for an unknown reason sometimes does not properly end the iCalendar
        LOG.warn("agenda does not end in END:VCALENDAR");
        // find out how much is missing from the end
        int indexOfLastNewline = StringUtils.lastIndexOf(chomped, CRLF);
        if (indexOfLastNewline == -1) {
            throw new ParserException("oracle calendar data is malformed ", -1);
        }
        String agendaWithoutLastLine = agenda.substring(0, indexOfLastNewline);
        StringBuilder agendaBuilder = new StringBuilder();
        agendaBuilder.append(agendaWithoutLastLine);
        agendaBuilder.append(CRLF);
        agendaBuilder.append("END:VCALENDAR");

        agenda = agendaBuilder.toString();
    }

    StringReader reader = new StringReader(agenda);
    CalendarBuilder builder = new CalendarBuilder();
    try {
        Calendar result = builder.build(reader);
        if (LOG.isTraceEnabled()) {
            LOG.trace(result.toString());
        }
        return result;
    } catch (IOException e) {
        LOG.error("ical4j threw IOException attempting to build Calendar; rethrowing as ParserException", e);
        throw new ParserException(e.getMessage(), -1, e);
    }
}