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

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

Introduction

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

Prototype

public static String leftPad(String str, int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Usage

From source file:org.openhab.binding.nikobus.internal.util.CRCUtil.java

/**
 * Calculate the second checksum on the input string and return the
 * input string with the checksum appended.
 * //from   ww w. j av a  2  s . co m
 * @param input
 *            String representing a nikobus command.
 * @return input string + CRC.
 */
public static String appendCRC2(String input) {

    int check = 0;

    for (byte b : input.getBytes()) {

        check = check ^ b;

        for (int i = 0; i < 8; i++) {

            if (((check & 0xff) >> 7) != 0) {
                check = check << 1;
                check = check ^ 0x99;
            } else {
                check = check << 1;
            }
            check = check & 0xff;
        }

    }
    return input + StringUtils.leftPad(Integer.toHexString(check), 2, "0").toUpperCase();

}

From source file:org.openhab.binding.nikobus.internal.util.SwitchModuleAnalyzer.java

/**
 * Try all 256 possible combinations for a checksum until one is found which
 * works. If no match is found, a second attempt done is but during this
 * attempt, commands will be sent slower.
 * /*from  w  ww .j av a  2  s.c  om*/
 * @param command
 *            command for which to find the checksum
 * @param expectedAck
 *            ACK expected from Nikobus which indicates a valid command was
 *            sent.
 * @return true if command was found
 */
private boolean guessChecksum(String command, String expectedAck) {

    String checksum = cache.get(command);

    if (checksum != null) {
        if (type == AnalysisType.VERIFY) {
            return verifyChecksum(command, checksum, expectedAck);
        } else {
            return true;
        }
    } else {
        if (type != AnalysisType.GUESS) {
            return false;
        }
    }

    long start = System.currentTimeMillis();
    boolean found = false;

    int i;

    for (i = 0; i < 256; i++) {

        // send 10 commands/second to try and locate the correct checksum
        checksum = StringUtils.leftPad(Integer.toHexString(i).toUpperCase(), 2, "0");

        try {
            binding.sendCommand(new NikobusCommand(command + checksum, expectedAck, 100));
            // if we get here, we got a async positive response
            // to one of the last commands sent.
            log.info("Found possible match.");
            break;
        } catch (Exception e) {
            // no match found, move on to next one..
        }
    }

    for (int j = i - 5; j <= i; j++) {
        // slow down search to find the exact match
        checksum = StringUtils.leftPad(Integer.toHexString(j).toUpperCase(), 2, "0");

        try {
            binding.sendCommand(new NikobusCommand(command + checksum, expectedAck, 400));
            log.info("Found checksum in {} ms using {} attempts.", (System.currentTimeMillis() - start),
                    (i + j + 1));
            cache.put(command, checksum);
            found = true;
            break;
        } catch (Exception e) {
            // no match found, move on to next one..
        }
    }

    if (!found) {
        log.error("Could not determine checksum for {}", command);
    }
    return found;
}

From source file:org.openhab.binding.phc.handler.PHCBridgeHandler.java

/**
 * Send the incoming command to the appropriate handler and channel.
 *
 * @param moduleAddress/*  w w w  .  j a  v a  2s.  co m*/
 * @param channel
 * @param cmd
 * @param rcvCrc
 */
private void handleIncomingCommand(byte moduleAddress, int channel, byte[] cmd) {
    ThingUID uid = PHCHelper.getThingUIDreverse(PHCBindingConstants.THING_TYPE_EM, moduleAddress);
    Thing thing = getThingByUID(uid);
    String channelId = "em#" + StringUtils.leftPad(Integer.toString(channel), 2, '0');

    if (thing != null) {
        OnOffType state = OnOffType.OFF;
        if ((cmd[0] & 0x0F) == 2) {
            state = OnOffType.ON;
        }

        logger.debug("{}, {}", thing.getUID(), state);
        ((PHCHandler) thing.getHandler()).handleIncoming(channelId, state);

    } else {
        logger.info("No Thing with UID {} available.", uid.getAsString());
    }
}

From source file:org.openhab.binding.phc.internal.PHCHelper.java

/**
 * Get the ThingUID by the given parameters.
 *
 * @param thingTypeUID//  w ww  .  j av  a 2  s  . co  m
 * @param moduleAddr reverse (to the reverse address - DIP switches)
 * @return
 */
public static ThingUID getThingUIDreverse(ThingTypeUID thingTypeUID, byte moduleAddr) {
    // convert to 5-bit binary string and reverse in second step
    String thingID = StringUtils.leftPad(StringUtils.trim(Integer.toBinaryString(moduleAddr & 0xFF)), 5, '0');
    thingID = new StringBuilder(thingID).reverse().toString();

    ThingUID thingUID = new ThingUID(thingTypeUID, thingID);

    return thingUID;
}

From source file:org.openhab.binding.phc.internal.PHCHelper.java

/**
 * Convert the byte b into an binary String
 *
 * @param b/*from w w w .  j av  a  2 s. co  m*/
 * @return
 */
public static Object byteToBinaryString(byte b) {
    return StringUtils.leftPad(StringUtils.trim(Integer.toBinaryString(b & 0xFF)), 8, '0') + " ";
}

From source file:org.openhab.io.imperihome.internal.model.device.RgbLightDevice.java

private String toHex(int value) {
    String hex = Integer.toHexString(value);
    return StringUtils.leftPad(hex, 2, '0');
}

From source file:org.openiot.gsn.wrappers.general.CSVHandler.java

public TreeMap<String, Serializable> convertTo(String[] formats, String[] fields, String nullValues[],
        String[] values, char separator) {
    TreeMap<String, Serializable> streamElement = new TreeMap<String, Serializable>(
            new CaseInsensitiveComparator());
    for (String field : fields) {
        streamElement.put(field, null);/*from ww w.j  ava 2 s  . com*/
    }
    HashMap<String, String> timeStampFormats = new HashMap<String, String>();
    for (int i = 0; i < Math.min(fields.length, values.length); i++) {
        if (isNull(nullValues, values[i])) {
            continue;
        } else if (formats[i].equalsIgnoreCase("numeric")) {
            try {
                streamElement.put(fields[i], Double.parseDouble(values[i]));
            } catch (java.lang.NumberFormatException e) {
                logger.error("Parsing to Numeric fails: Value to parse=" + values[i]);
                throw e;
            }
        } else if (formats[i].equalsIgnoreCase("string")) {
            streamElement.put(fields[i], values[i]);
        } else if (isTimeStampFormat(formats[i])) {
            String value = "";
            String format = "";
            if (streamElement.get(fields[i]) != null) {
                value = (String) streamElement.get(fields[i]);
                format = timeStampFormats.get(fields[i]);
                value += separator;
                format += separator;
            }
            if (isTimeStampLeftPaddedFormat(formats[i]))
                values[i] = StringUtils.leftPad(values[i], getTimeStampFormat(formats[i]).length(), '0');

            value += values[i];
            format += getTimeStampFormat(formats[i]);
            streamElement.put(fields[i], value);
            timeStampFormats.put(fields[i], format);
        }
    }
    for (String timeField : timeStampFormats.keySet()) {
        String timeFormat = timeStampFormats.get(timeField);
        String timeValue = (String) streamElement.get(timeField);
        try {
            DateTime x = DateTimeFormat.forPattern(timeFormat).withZone(getTimeZone()).parseDateTime(timeValue);
            streamElement.put(timeField, x.getMillis());
        } catch (IllegalArgumentException e) {
            logger.error("Parsing error: TimeFormat=" + timeFormat + " , TimeValue=" + timeValue);
            logger.error(e.getMessage(), e);
            throw e;
        }
    }

    return streamElement;
}

From source file:org.openlegacy.terminal.support.TerminalConnectionDelegator.java

private static void handleRightAdjust(TerminalSendAction terminalSendAction) {
    List<TerminalField> fields = terminalSendAction.getFields();
    for (TerminalField terminalField : fields) {
        if (terminalField.getRightAdjust() != RightAdjust.NONE) {
            if (terminalField.getLength() > terminalField.getValue().length()) {
                String fillerChar = terminalField.getRightAdjust() == RightAdjust.ZERO_FILL ? "0" : " ";
                String newValue = null;
                if (terminalField.isRightToLeft()) {
                    newValue = StringUtils.rightPad(terminalField.getValue(), terminalField.getLength(),
                            fillerChar);
                } else {
                    newValue = StringUtils.leftPad(terminalField.getValue(), terminalField.getLength(),
                            fillerChar);
                }/*ww w . j a v  a2  s  .c om*/
                terminalField.setValue(newValue);
            }
        }
    }
}

From source file:org.openmrs.module.emr.order.EmrOrderServiceImpl.java

@Override
public void ensureAccessionNumberAssignedTo(Order order) {
    if (order.getAccessionNumber() == null) {
        String accessionNumber = new LuhnMod10IdentifierValidator()
                .getValidIdentifier(order.getOrderId().toString());
        accessionNumber = StringUtils.leftPad(accessionNumber, 10, "0"); // pad the accession number to 10 digits
        order.setAccessionNumber(accessionNumber);
    }/*from  w w w. j a  v a  2 s.  co m*/
}

From source file:org.opennms.model.utils.StoreFormatter.java

@Override
public String formatForeignSource(String foreignSource) {
    return "Store" + StringUtils.leftPad(foreignSource, 4, '0');
}