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

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

Introduction

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

Prototype

public static String reverse(final String str) 

Source Link

Document

Reverses a String as per StringBuilder#reverse() .

A null String returns null .

 StringUtils.reverse(null)  = null StringUtils.reverse("")    = "" StringUtils.reverse("bat") = "tab" 

Usage

From source file:com.norconex.commons.lang.file.FileUtil.java

/**
 * Returns the specified number of lines starting from the end
 * of a text file.//from   w  ww.  j av a  2s .  c  om
 * @param file the file to read lines from
 * @param encoding the file encoding
 * @param numberOfLinesToRead the number of lines to read
 * @param stripBlankLines whether to return blank lines or not
 * @param filter InputStream filter
 * @return array of file lines
 * @throws IOException i/o problem
 */
public static String[] tail(File file, String encoding, final int numberOfLinesToRead, boolean stripBlankLines,
        IInputStreamFilter filter) throws IOException {
    assertFile(file);
    assertNumOfLinesToRead(numberOfLinesToRead);
    LinkedList<String> lines = new LinkedList<String>();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ReverseFileInputStream(file), encoding));
    int remainingLinesToRead = numberOfLinesToRead;

    String line;
    while ((line = reader.readLine()) != null) {
        if (remainingLinesToRead-- <= 0) {
            break;
        }
        String newLine = StringUtils.reverse(line);
        if (!stripBlankLines || StringUtils.isNotBlank(line)) {
            if (filter != null && filter.accept(newLine)) {
                lines.addFirst(newLine);
            } else {
                remainingLinesToRead++;
            }
        } else {
            remainingLinesToRead++;
        }
    }
    reader.close();
    return lines.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}

From source file:org.ensembl.hive.longmult.AddTogether.java

private Object add_together(String b_multiplier, Map<String, Object> partialProduct) {

    // create accu to write digits to (work out potential length
    int accuLen = 1 + b_multiplier.length() + numericParamToStr(partialProduct.get("1")).length();
    getLog().debug("Adding " + b_multiplier + " to " + partialProduct + ": expected " + accuLen);
    int[] accu = new int[accuLen];
    for (int i = 0; i < accuLen; i++) {
        accu[i] = 0;//from w w w . j a  v a 2  s  .  c o  m
    }

    // split and reverse the digits in b_multiplier
    char[] b_digits = StringUtils.reverse(b_multiplier).toCharArray();

    // iterate over each digit in b_digits
    for (int i = 0; i < b_digits.length; i++) {
        // for each digit
        char b_digit = b_digits[i];
        getLog().debug("i=" + i + ", b_digit=" + b_digit);

        // get the corresponding partial product for that digit
        char[] p_digits = StringUtils.reverse(numericParamToStr(partialProduct.get(String.valueOf(b_digit))))
                .toCharArray();
        // iterate over digits in the product
        for (int j = 0; j < p_digits.length; j++) {
            char p_digit = p_digits[j];
            getLog().debug("j=" + j + ", p_digit=" + Character.getNumericValue(p_digit) + ", i+j=" + (i + j));
            // add to accumulator
            getLog().debug("[" + i + "+" + j + "] before=" + accu[i + j]);
            accu[i + j] = accu[i + j] + Character.getNumericValue(p_digit);
            getLog().debug("[" + i + "+" + j + "] after=" + accu[i + j]);
        }
    }
    // do the carrying
    int carry = 0;
    for (int i = 0; i < accu.length; i++) {
        getLog().debug("Dealing with digit " + i + " of " + accu.length + ": " + accu[i] + ", carry=" + carry);
        int val = carry + accu[i];
        accu[i] = val % 10;
        carry = val / 10;
        getLog().debug("Finished dealing with digit " + i + " of " + accu.length + ": " + accu[i] + ", carry="
                + carry);
    }

    getLog().debug("result=" + Arrays.toString(accu));
    // turn accumulator array back into a string and reversing it
    StringBuilder sb = new StringBuilder();
    for (int i = accu.length - 1; i >= 0; i--) {
        sb.append(accu[i]);
    }

    return Long.parseLong(sb.toString());
}

From source file:org.kie.appformer.flow.unit.FlowDescriptorConverterTest.java

@Test
public void flowWithUIComponentAndCombinedShowAndHide() throws Exception {
    final SimpleType string = typeFactory.simpleType(String.class);
    final SimpleType object = typeFactory.simpleType(Object.class);
    final UIComponentDescriptor componentDescriptor = descriptorFactory
            .createUIComponentDescriptor("StringEditor", string, string, object);
    final Object viewObj = new Object();
    final UIComponent<String, String, Object> component = new UIComponent<String, String, Object>() {

        @Override//  w ww .j a v  a2  s  .  c o  m
        public void start(final String input, final Consumer<String> callback) {
            final String reversed = StringUtils.reverse(input);
            callback.accept(reversed);
        }

        @Override
        public void onHide() {
        }

        @Override
        public Object asComponent() {
            return viewObj;
        }

        @Override
        public String getName() {
            return "StringEditor";
        }
    };
    final List<CapturedAction> capturedActions = new ArrayList<>();
    final DisplayerDescriptor displayerDescriptor = descriptorFactory.createDisplayerDescriptor("TestDisplayer",
            object);
    registry.addDisplayer(displayerDescriptor, () -> new Displayer<Object>() {

        @Override
        public void show(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.SHOW, component));
        }

        @Override
        public void hide(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.HIDE, component));
        }
    });

    registry.addUIComponent(componentDescriptor, () -> component);
    final UIStepDescriptor uiStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.SHOW_AND_HIDE, componentDescriptor);
    final AppFlowDescriptor uiFlow = descriptorFactory.createAppFlowDescriptor(uiStepDescriptor);

    try {
        @SuppressWarnings("unchecked")
        final AppFlow<String, String> flow = (AppFlow<String, String>) converter.convert(registry, uiFlow);
        final Ref<String> retVal = new Ref<>();
        executor.execute("foo", flow, val -> retVal.val = val);
        assertNotNull(retVal.val);
        assertEquals("oof", retVal.val);
        assertEquals(Arrays.asList(new CapturedAction(UIStepDescriptor.Action.SHOW, component),
                new CapturedAction(UIStepDescriptor.Action.HIDE, component)), capturedActions);
    } catch (final AssertionError ae) {
        throw ae;
    } catch (final Throwable t) {
        throw new AssertionError(t);
    }
}

From source file:org.kie.appformer.flow.unit.FlowDescriptorConverterTest.java

@Test
public void flowWithUIComponentAndSeparateShowAndHide() throws Exception {
    final SimpleType string = typeFactory.simpleType(String.class);
    final SimpleType object = typeFactory.simpleType(Object.class);
    final UIComponentDescriptor componentDescriptor = descriptorFactory
            .createUIComponentDescriptor("StringEditor", string, string, object);
    final Object viewObj = new Object();
    final UIComponent<String, String, Object> component = new UIComponent<String, String, Object>() {

        @Override// w  w  w .j a  v  a2  s .  c o m
        public void start(final String input, final Consumer<String> callback) {
            final String reversed = StringUtils.reverse(input);
            callback.accept(reversed);
        }

        @Override
        public void onHide() {
        }

        @Override
        public Object asComponent() {
            return viewObj;
        }

        @Override
        public String getName() {
            return "StringEditor";
        }
    };
    final List<CapturedAction> capturedActions = new ArrayList<>();
    final DisplayerDescriptor displayerDescriptor = descriptorFactory.createDisplayerDescriptor("TestDisplayer",
            object);
    registry.addDisplayer(displayerDescriptor, () -> new Displayer<Object>() {

        @Override
        public void show(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.SHOW, component));
        }

        @Override
        public void hide(final UIComponent<?, ?, Object> uiComponent) {
            capturedActions.add(new CapturedAction(UIStepDescriptor.Action.HIDE, component));
        }
    });

    registry.addUIComponent(componentDescriptor, () -> component);
    final UIStepDescriptor showStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.SHOW, componentDescriptor);
    final UIStepDescriptor hideStepDescriptor = descriptorFactory.createUIStepDescriptor(displayerDescriptor,
            UIStepDescriptor.Action.HIDE, componentDescriptor);
    final TransformationDescriptor doubleStringDescriptor = descriptorFactory
            .createTransformationDescriptor("DoubleString", string, string);
    registry.addTransformation(doubleStringDescriptor, () -> (final String s) -> s + s);

    final AppFlowDescriptor uiFlow = descriptorFactory.createAppFlowDescriptor(showStepDescriptor)
            .andThen(doubleStringDescriptor).andThen(hideStepDescriptor);

    try {
        @SuppressWarnings("unchecked")
        final AppFlow<String, String> flow = (AppFlow<String, String>) converter.convert(registry, uiFlow);
        final Ref<String> retVal = new Ref<>();
        executor.execute("foo", flow, val -> retVal.val = val);
        assertNotNull(retVal.val);
        assertEquals("oofoof", retVal.val);
        assertEquals(Arrays.asList(new CapturedAction(UIStepDescriptor.Action.SHOW, component),
                new CapturedAction(UIStepDescriptor.Action.HIDE, component)), capturedActions);
    } catch (final AssertionError ae) {
        throw ae;
    } catch (final Throwable t) {
        throw new AssertionError(t);
    }
}

From source file:org.ohdsi.webapi.service.CohortDefinitionService.java

private String formatBitMask(Long n, int size) {
    return StringUtils.reverse(StringUtils.leftPad(Long.toBinaryString(n), size, "0"));
}

From source file:org.phenotips.utilities.updowner.UpDowner.java

private static String turn(String value) {
    return StringUtils.reverse(StringUtils.replaceEach(value,
            "ABCDEFGJKLMPQRTUVWYabcdefghijklmnopqrstuvwxyz123456789'.,!?<>[](){}%".split(""),
            "??W?M?qp??uodbsn?xz??986,'><][)(}{%"
                    .split("")));
}

From source file:org.springframework.data.solr.core.DefaultQueryParserTests.java

@Test
public void testRegisterAlternateConverter() {
    Criteria criteria = new Criteria("field_1").is(100);
    queryParser.registerConverter(new Converter<Number, String>() {

        @Override/*from w w  w. j  a  v  a 2  s.  c  o  m*/
        public String convert(Number arg0) {
            return StringUtils.reverse(arg0.toString());
        }

    });
    Assert.assertEquals("field_1:001", queryParser.createQueryStringFromCriteria(criteria));
}

From source file:uk.ac.ebi.eva.pipeline.io.mappers.VariantVcfFactory.java

/**
 * Calculates the normalized start, end, reference and alternate of a variant where the
 * reference and the alternate are not identical.
 * <p>/*from  www.  j  a v  a  2  s.  co m*/
 * This task comprises 2 steps: removing the trailing bases that are
 * identical in both alleles, then the leading identical bases.
 * <p>
 * It is left aligned because the traling bases are removed before the leading ones, implying a normalization where
 * the position is moved the least possible from its original location.
 * @param chromosome needed for error reporting and logging
 * @param position Input starting position
 * @param reference Input reference allele
 * @param alternate Input alternate allele
 * @return The new start, end, reference and alternate alleles wrapped in a VariantKeyFields
 */
protected VariantKeyFields normalizeLeftAlign(String chromosome, int position, String reference,
        String alternate) throws NotAVariantException {
    if (reference.equals(alternate)) {
        throw new NotAVariantException("One alternate allele is identical to the reference. Variant found as: "
                + chromosome + ":" + position + ":" + reference + ">" + alternate);
    }

    // Remove the trailing bases
    String refReversed = StringUtils.reverse(reference);
    String altReversed = StringUtils.reverse(alternate);
    int indexOfDifference = StringUtils.indexOfDifference(refReversed, altReversed);
    reference = StringUtils.reverse(refReversed.substring(indexOfDifference));
    alternate = StringUtils.reverse(altReversed.substring(indexOfDifference));

    // Remove the leading bases
    indexOfDifference = StringUtils.indexOfDifference(reference, alternate);
    int start = position + indexOfDifference;
    int length = max(reference.length(), alternate.length());
    int end = position + length - 1; // -1 because end is inclusive
    if (indexOfDifference > 0) {
        reference = reference.substring(indexOfDifference);
        alternate = alternate.substring(indexOfDifference);
    }
    return new VariantKeyFields(start, end, reference, alternate);
}