Example usage for java.lang Byte parseByte

List of usage examples for java.lang Byte parseByte

Introduction

In this page you can find the example usage for java.lang Byte parseByte.

Prototype

public static byte parseByte(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal byte .

Usage

From source file:edu.ucla.stat.SOCR.analyses.gui.Survival.java

/**This method defines the specific statistical Analysis to be carried our on the user specified data. ANOVA is done in this case. */
public void doAnalysis() {
    if (dataTable.isEditing())
        dataTable.getCellEditor().stopCellEditing();

    String timeHeader = null;/*from   w ww. ja va 2s  .c  o  m*/
    String censorHeader = null;
    String groupNameHeader = null;

    try {
        timeHeader = columnModel.getColumn(timeIndex).getHeaderValue().toString().trim();
    } catch (Exception e) {
    }
    try {
        censorHeader = columnModel.getColumn(censorIndex).getHeaderValue().toString().trim();
    } catch (Exception e) {
    }
    try {
        groupNameHeader = columnModel.getColumn(groupNamesIndex).getHeaderValue().toString().trim();
    } catch (Exception e) {
    }

    ////System.out.println("doAnalysis timeHeader = " + timeHeader+ ", timeIndex = " + timeIndex);
    ////System.out.println("doAnalysis censorHeader = " + censorHeader+ ", censorIndex = " + censorIndex);
    ////System.out.println("doAnalysis groupNameHeader = " + groupNameHeader+ ", groupNamesIndex = " + groupNamesIndex);

    // DO NOT NEED TO PRINT THIS FOR ONE_T
    // ONE_T has only one variable, we use Y to contain it (not X).
    // Reason of not using X but Y: Y is at the top of the panel.
    if (!hasExample) {
        JOptionPane.showMessageDialog(this, DATA_MISSING_MESSAGE);
        return;
    }
    /*
    if (timeIndex < 0 || censorIndex < 0 || groupNamesIndex < 0) {
       JOptionPane.showMessageDialog(this, VARIABLE_MISSING_MESSAGE);
       return;
    }*/

    if (timeIndex < 0 || censorIndex < 0) {
        JOptionPane.showMessageDialog(this, VARIABLE_MISSING_MESSAGE);
        return;
    }
    if (groupNamesIndex < 0) {
        useGroupNames = false;
    }

    Data data = new Data();

    /******************************************************************
    From this point, the code has been modified to work with input cells that are empty.
    ******************************************************************/

    /************* TIME *************/
    String cellValue = null;

    ArrayList<String> timeArrayList = new ArrayList<String>();
    timeLength = 0;
    try {
        for (int k = 0; k < dataTable.getRowCount(); k++) {
            try {
                cellValue = ((String) dataTable.getValueAt(k, timeIndex)).trim();
                if (cellValue != null && !cellValue.equals("")) {
                    timeArrayList.add(timeLength, cellValue);
                    timeLength++;
                } else {
                    continue; // to the next for
                }
            } catch (Exception e) { // do nothing?

            }
        }

    } catch (Exception e) {
    }

    if (timeLength <= 0) {
        JOptionPane.showMessageDialog(this, NULL_VARIABLE_MESSAGE);
        return;
    }

    double[] time = new double[timeLength];
    for (int i = 0; i < timeLength; i++) {
        time[i] = Double.parseDouble((String) timeArrayList.get(i));
        //////////////System.out.println("gui.Survival doAnalysis time[" + i + "] = " + time[i]);
    }

    /************* CENSOR *************/
    int censorLength = 0;

    ArrayList<String> censorArrayList = new ArrayList<String>();
    try {
        for (int k = 0; k < dataTable.getRowCount(); k++) {
            try {
                cellValue = ((String) dataTable.getValueAt(k, censorIndex)).trim();
                if (cellValue != null && !cellValue.equals("")) {
                    censorArrayList.add(censorLength, cellValue);
                    censorLength++;
                } else {
                    continue; // to the next for
                }
            } catch (Exception e) { // do nothing?
            }
        }

    } catch (Exception e) {
    }

    if (censorLength <= 0) {
        JOptionPane.showMessageDialog(this, NULL_VARIABLE_MESSAGE);
        return;
    }

    byte[] censor = new byte[censorLength];
    for (int i = 0; i < censorLength; i++) {
        censor[i] = Byte.parseByte((String) censorArrayList.get(i));
    }

    /************* TREATMENT (GROUPS) *************/
    int treatLength = 0;
    String[] treat = null;
    ////System.out.println("gui.Survival doAnalysis useGroupNames = " + useGroupNames);
    ////System.out.println("gui.Survival doAnalysis groupNamesIndex = " + groupNamesIndex);

    if (useGroupNames) {
        ArrayList<String> treatArrayList = new ArrayList<String>();
        try {
            for (int k = 0; k < dataTable.getRowCount(); k++) {
                try {
                    cellValue = ((String) dataTable.getValueAt(k, groupNamesIndex)).trim();
                    if (cellValue != null && !cellValue.equals("")) {
                        treatArrayList.add(treatLength, cellValue);
                        treatLength++;
                    } else {
                        continue; // to the next for
                    }
                } catch (Exception e) { // do nothing?
                }
            }

        } catch (Exception e) {
            ////System.out.println("gui.Survival doAnalysis useGroupNames Exception = " + e);

        }
        if (treatLength <= 0) {
            JOptionPane.showMessageDialog(this, NULL_VARIABLE_MESSAGE);
            return;
        }

        treat = new String[treatLength];
        for (int i = 0; i < treatLength; i++) {
            treat[i] = (String) treatArrayList.get(i);
            ////System.out.println("gui.Survival doAnalysis treat["+i+"] = " + treat[i]);
        }
    } else { // default only one group.
        treatLength = timeLength;
        treat = new String[treatLength];

        for (int i = 0; i < treatLength; i++) {
            treat[i] = "GROUP_ONE";
            //////////System.out.println("gui.Survival doAnalysis treat["+i+"] = " + treat[i]);
        }
    }

    /*String[] treat = new String[treatLength];
    */
    //for (int i = 0; i < treatLength; i++) {
    //treat[i] = (String)treatArrayList.get(i);
    //////////System.out.println("gui.Survival doAnalysis treat["+i+"] = " + treat[i]);
    //}

    // But the Analyses tools package takes the data in X HashMap.

    //double[] testTime = {1,10,22,7,3,32,12,23,8,22,17,6,2,16,11,34,8,32,12,25,2,11,5,20,4,19,15,6,8,17,23,35,5,6,11,13,4,9,1,6,8,10};
    //byte[] censor = {1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,0};
    //String[] treat = {"control","6-MP","control","6-MP","control","6-MP","control","6-MP",    "control","6-MP","control","6-MP","control","6-MP","control","6-MP","control","6-MP",   "control","6-MP","control","6-MP","control","6-MP","control","6-MP","control","6-MP",    "control","6-MP","control","6-MP","control","6-MP","control","6-MP","control","6-MP",    "control","6-MP","control","6-MP"};

    //////////System.out.println("now get result ");

    try {
        result = (SurvivalResult) data.getSurvivalResult(time, censor, treat);
        //////////System.out.println("result = " + result);
        //result = (NormalPowerResult) data.getNormalPower(100, 3500, 0.05, 2500 , 2450, hypothesisType);
    } catch (Exception e) {
        //////////System.out.println("in gui result Exception " + e);
    }

    /* every one has have its own, otherwise one Exception spills the whole. */

    try {
        survivalTime = result.getSurvivalTime();//((Double)result.getTexture().get(OneTResult.SAMPLE_MEAN)).doubleValue();
    } catch (NullPointerException e) {
        //////////System.out.println("survivalTime NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("survivalTime Exception = " + e);
    }
    try {
        survivalRate = result.getSurvivalRate();//((Double)result.getTexture().get(OneTResult.SAMPLE_VAR)).doubleValue();
    } catch (NullPointerException e) {
        //////////System.out.println("survivalRate NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("survivalRate Exception = " + e);
    }
    try {
        upperCI = result.getSurvivalUpperCI();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        //////////System.out.println("upperCI NullPointerException = " + e);

    } catch (Exception e) {
        //////////////System.out.println("upperCI Exception = " + e);
    }
    try {
        lowerCI = result.getSurvivalLowerCI();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        //////////System.out.println("lowerCI NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("lowerCI Exception = " + e);
    }
    try {
        atRisk = result.getSurvivalAtRisk();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        //////////System.out.println("atRisk NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("atRisk Exception = " + e);
    }
    try {
        survivalSE = result.getSurvivalSE();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        //////////System.out.println("survivalSE NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("survivalSE Exception = " + e);
    }

    try {
        groupNames = result.getSurvivalGroupNames();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {

    } catch (Exception e) {
        //////////System.out.println("Exception = " + e);
    }

    try {
        timeList = result.getSurvivalTimeList();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        //////////System.out.println("NullPointerException = " + e);

    } catch (Exception e) {
        //////////System.out.println("Exception = " + e);
    }

    try {
        censoredTime = result.getCensoredTimeArray();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        ////////System.out.println("NullPointerException = " + e);

    } catch (Exception e) {
        ////////System.out.println("Exception = " + e);
    }

    try {
        numberCaseCensored = result.getNumberCensored();
    } catch (NullPointerException e) {
        //System.out.println("NullPointerException = " + e);

    } catch (Exception e) {
        //System.out.println("numberCaseCensored Exception = " + e);
    }

    try {
        censoredRate = result.getCensoredRateArray();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        ////////System.out.println("NullPointerException = " + e);

    } catch (Exception e) {
        ////////System.out.println("Exception = " + e);
    }
    try {
        maxTime = result.getMaxTime();//((Integer)result.getTexture().get(OneTResult.DF)).intValue();
    } catch (NullPointerException e) {
        ////////System.out.println("NullPointerException = " + e);

    } catch (Exception e) {
        ////////System.out.println("Exception = " + e);
    }
    ////////System.out.println("Print maxTime  = " + maxTime);

    for (int i = 0; i < maxTime.length; i++) {
        ////////System.out.println("maxTime["+i+"] = " + maxTime[i]);
    }

    ////////System.out.println("gui censoredTime.length = " +  censoredTime.length);
    for (int i = 0; i < censoredTime.length; i++) {
        ////////System.out.println("gui groupName = " + groupNames[i]+", censoredTime["+i+"].length = " + censoredTime[i].length);
        if (censoredTime[i].length > 0) {
            for (int j = 0; j < censoredTime[i].length; j++) {
                ////////System.out.println("gui censored["+i+"]["+j + "] = " + censoredTime[i][j] + " rate = " + censoredRate[i][j]);
            }
        }

    }

    t_stat = sampleMean / Math.sqrt(sampleVar / (df + 1));
    p_value = 1 - (new edu.ucla.stat.SOCR.distributions.StudentDistribution(df)).getCDF(t_stat);
    p_valueS = AnalysisUtility.enhanceSmallNumber(p_value);

    updateResults();
    doGraph();
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private GeoPathFinding() {
    LineNumberReader lnr = null;//from  w ww  .j a va  2 s  .c o  m
    try {
        _log.info("PathFinding Engine: - Loading Path Nodes...");
        File Data = new File("./data/pathnode/pn_index.txt");
        if (!Data.exists())
            return;

        lnr = new LineNumberReader(new BufferedReader(new FileReader(Data)));
    } catch (Exception e) {
        throw new Error("Failed to Load pn_index File.", e);
    }
    String line;
    try {
        while ((line = lnr.readLine()) != null) {
            if (line.trim().length() == 0)
                continue;
            StringTokenizer st = new StringTokenizer(line, "_");
            byte rx = Byte.parseByte(st.nextToken());
            byte ry = Byte.parseByte(st.nextToken());
            LoadPathNodeFile(rx, ry);
        }
    } catch (Exception e) {
        throw new Error("Failed to Read pn_index File.", e);
    } finally {
        try {
            lnr.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.sonar.plugins.openedge.foundation.OpenEdgeComponents.java

private static void configureField(Object check, Field field, String value) {
    try {//from w  ww.  java 2 s . c  o m
        field.setAccessible(true);

        if (field.getType().equals(String.class)) {
            field.set(check, value);
        } else if (int.class == field.getType()) {
            field.setInt(check, Integer.parseInt(value));
        } else if (short.class == field.getType()) {
            field.setShort(check, Short.parseShort(value));
        } else if (long.class == field.getType()) {
            field.setLong(check, Long.parseLong(value));
        } else if (double.class == field.getType()) {
            field.setDouble(check, Double.parseDouble(value));
        } else if (boolean.class == field.getType()) {
            field.setBoolean(check, Boolean.parseBoolean(value));
        } else if (byte.class == field.getType()) {
            field.setByte(check, Byte.parseByte(value));
        } else if (Integer.class == field.getType()) {
            field.set(check, new Integer(Integer.parseInt(value)));
        } else if (Long.class == field.getType()) {
            field.set(check, new Long(Long.parseLong(value)));
        } else if (Double.class == field.getType()) {
            field.set(check, new Double(Double.parseDouble(value)));
        } else if (Boolean.class == field.getType()) {
            field.set(check, Boolean.valueOf(Boolean.parseBoolean(value)));
        } else {
            throw MessageException
                    .of("The type of the field " + field + " is not supported: " + field.getType());
        }
    } catch (IllegalAccessException e) {
        throw MessageException.of(
                "Can not set the value of the field " + field + " in the class: " + check.getClass().getName(),
                e);
    }
}

From source file:hu.javaforum.commons.ReflectionHelper.java

/**
 * Converts the string value to instance of primitive wrapper.
 *
 * @param fieldClass The field class/*from   w w  w  . j  a v a  2  s.co  m*/
 * @param stringValue The string value
 * @return The instance of the field class
 * @throws ParseException Throws when the string isn't parseable
 */
private static Object convertToPrimitiveWrapper(final Class fieldClass, final String stringValue)
        throws ParseException {
    Object parameter = null;

    if (fieldClass.equals(Boolean.class)) {
        parameter = Boolean.parseBoolean(stringValue);
    } else if (fieldClass.equals(Byte.class)) {
        parameter = Byte.parseByte(stringValue);
    } else if (fieldClass.equals(Double.class)) {
        parameter = Double.parseDouble(stringValue);
    } else if (fieldClass.equals(Float.class)) {
        parameter = Float.parseFloat(stringValue);
    } else if (fieldClass.equals(Integer.class)) {
        parameter = Integer.parseInt(stringValue);
    } else if (fieldClass.equals(Long.class)) {
        parameter = Long.parseLong(stringValue);
    } else if (fieldClass.equals(Short.class)) {
        parameter = Short.parseShort(stringValue);
    }

    return parameter;
}

From source file:com.fanniemae.ezpie.common.StringUtilities.java

public static Object toObject(String typeName, String value) {
    if ((value == null) || value.isEmpty()) {
        return "";
    }/* w ww .j  a  v a 2 s .  c om*/

    switch (typeName) {
    case "Boolean":
        return Boolean.parseBoolean(value);
    case "Byte":
    case "SByte":
        return Byte.parseByte(value);
    case "Byte[]":
        return value.toCharArray();
    case "Char":
        return value.charAt(0);
    case "Char[]":
        return value.toCharArray();
    case "DateTime":
        Date dtValue = new Date(Long.parseLong(value));
        if (dtValue == new Date(Long.MIN_VALUE)) {
            return null;
        }
        return dtValue;
    case "Decimal":
    case "Double":
    case "Single":
        return Double.parseDouble(value);
    case "Float":
        return Float.parseFloat(value);
    case "UUID":
        return UUID.fromString(value);
    case "Int":
    case "Integer":
    case "Int16":
    case "Int32":
    case "UInt16":
        return Integer.parseInt(value);
    case "Int64":
    case "Long":
    case "UInt32":
    case "UInt64":
        return Long.parseLong(value);
    case "NCLOB":
        return "NCLOB";
    case "Short":
        return Short.parseShort(value);
    case "String":
        return value;
    case "TimeSpan":
        return value;
    default:
        return null;
    }
}

From source file:org.romaframework.core.schema.SchemaHelper.java

public static Object assignValueToLiteral(String v, Class<?> type) {
    Object value;/*from w w  w  . j  a  v  a 2 s .c o  m*/
    if (v.length() == 0) {
        value = null;
    } else {
        if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            value = Integer.parseInt(v);
        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            value = Long.parseLong(v);
        } else if (type.equals(Short.class) || type.equals(Short.TYPE)) {
            value = Short.parseShort(v);
        } else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) {
            value = Boolean.parseBoolean(v);
        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            value = Float.parseFloat(v);
        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            value = Double.parseDouble(v);
        } else if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            value = Byte.parseByte(v);
        } else if (type.equals(Character.class) || type.equals(Character.TYPE)) {
            value = v.charAt(0);
        } else {
            value = v;
        }
    }
    return value;
}

From source file:cn.ac.ncic.mastiff.io.coding.DictionaryBitPackingRLEByteReader.java

@Override
public byte[] ensureDecompressed() throws IOException {
    FlexibleEncoding.ORC.DynamicByteArray dynamicBuffer = new FlexibleEncoding.ORC.DynamicByteArray();
    dynamicBuffer.add(inBuf.getData(), 12, inBuf.getLength() - 12);
    ByteBuffer byteBuf = ByteBuffer.allocate(dynamicBuffer.size());
    dynamicBuffer.setByteBuffer(byteBuf, 0, dynamicBuffer.size());
    byteBuf.flip();/*from www.j  a va  2 s .co  m*/
    DataInputBuffer dib = new DataInputBuffer();
    dib.reset(byteBuf.array(), 0, byteBuf.array().length);
    int dictionarySize = dib.readInt();
    int OnlydictionarySize = dib.readInt();
    dib.reset(byteBuf.array(), 8, dictionarySize - 4);
    byte[] dictionaryBuffer = dib.getData();
    dib.reset(byteBuf.array(), 4 + dictionarySize, (byteBuf.array().length - dictionarySize - 4));
    byte[] dictionaryId = dib.getData();
    dib.close();
    DictionaryValuesReader cr = initDicReader(OnlydictionarySize, dictionaryBuffer,
            PrimitiveType.PrimitiveTypeName.BINARY);
    cr.initFromPage(numPairs, dictionaryId, 0);
    DataOutputBuffer decoding = new DataOutputBuffer();
    decoding.writeInt(decompressedSize);
    decoding.writeInt(numPairs);
    decoding.writeInt(startPos);
    for (int i = 0; i < numPairs; i++) {
        byte tmp = Byte.parseByte(cr.readBytes().toStringUsingUTF8());
        decoding.writeInt(tmp);
    }
    byteBuf.clear();
    inBuf.close();
    return decoding.getData();

}

From source file:IndexService.Indexer.java

public static void main(String[] args) throws IOException {
    System.out.println("input cmd:   indexdir  idx  type  startvalue  endvalue");
    String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
    StringTokenizer st = new StringTokenizer(str);
    String indexdir = st.nextToken();
    int idx = Integer.parseInt(st.nextToken());
    String type = st.nextToken();
    String startvalue = st.nextToken();
    String endvalue = null;//from w  ww.  jav a2 s . c o m
    if (st.hasMoreTokens())
        endvalue = st.nextToken();
    else
        endvalue = startvalue;
    ArrayList<IRecord.IFValue> values = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values.add(new IRecord.IFValue(Byte.parseByte(startvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values.add(new IRecord.IFValue(Short.parseShort(startvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values.add(new IRecord.IFValue(Integer.parseInt(startvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values.add(new IRecord.IFValue(Long.parseLong(startvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values.add(new IRecord.IFValue(Float.parseFloat(startvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values.add(new IRecord.IFValue(Double.parseDouble(startvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values.add(new IRecord.IFValue(startvalue, idx));
    ArrayList<IRecord.IFValue> values1 = new ArrayList<IRecord.IFValue>();
    if (type.equalsIgnoreCase("byte"))
        values1.add(new IRecord.IFValue(Byte.parseByte(endvalue), idx));
    if (type.equalsIgnoreCase("short"))
        values1.add(new IRecord.IFValue(Short.parseShort(endvalue), idx));
    if (type.equalsIgnoreCase("int"))
        values1.add(new IRecord.IFValue(Integer.parseInt(endvalue), idx));
    if (type.equalsIgnoreCase("long"))
        values1.add(new IRecord.IFValue(Long.parseLong(endvalue), idx));
    if (type.equalsIgnoreCase("float"))
        values1.add(new IRecord.IFValue(Float.parseFloat(endvalue), idx));
    if (type.equalsIgnoreCase("double"))
        values1.add(new IRecord.IFValue(Double.parseDouble(endvalue), idx));
    if (type.equalsIgnoreCase("string"))
        values1.add(new IRecord.IFValue(endvalue, idx));
    Indexer indexer = new Indexer();
    List<IRecord> recs = indexer.getRange(indexdir, null, values, values1, 100, null, -1);
    for (IRecord rec : recs) {
        rec.show();
    }

}

From source file:org.gridgain.grid.util.GridConfigurationHelper.java

/**
 * Converts value from {@code String} to simple type.
 *
 * @param val Value.//from   w w w  . j av a 2 s  . c  om
 * @param cls Result type.
 * @param name Name.
 * @return Converted value.
 * @throws GridException If convert fails.
 */
private static Object convert(String val, Class<?> cls, String name) throws GridException {
    if (cls == String.class)
        return val;

    if (cls == Boolean.class || cls == boolean.class)
        return Boolean.parseBoolean(val);

    if (cls == Character.class || cls == char.class)
        return val.charAt(0);

    try {
        if (cls == Byte.class || cls == byte.class)
            return Byte.parseByte(val);

        if (cls == Short.class || cls == short.class)
            return Short.parseShort(val);

        if (cls == Integer.class || cls == int.class)
            return Integer.parseInt(val);

        if (cls == Long.class || cls == long.class)
            return Long.parseLong(val);

        if (cls == Float.class || cls == float.class)
            return Float.parseFloat(val);

        if (cls == Double.class || cls == double.class)
            return Double.parseDouble(val);
    } catch (NumberFormatException ignore) {
        throw new GridException(
                "Failed to parse configuration property value [name=" + name + ", value=" + val + ']');
    }

    throw new GridException("Unexpected configuration property type (must be primitive or String) [name=" + name
            + ", value=" + val + ", cls=" + cls + ']');
}

From source file:org.openhab.binding.wr3223.internal.WR3223Binding.java

/**
 * Configure binding.//from  w w  w  . ja va  2s  .  com
 *
 * @param configuration
 */
private void configure(final Map<String, Object> configuration) {
    // Configure refresh
    String refreshIntervalString = (String) configuration.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
        if (refreshInterval > 20000) {
            logger.warn("Refresh interval should not be over 20 seconds.");
        }
    }

    // Controller
    String controllerAddrString = (String) configuration.get("controllerAddr");
    if (StringUtils.isNotBlank(controllerAddrString)) {
        controllerAddr = Byte.parseByte(controllerAddrString);
    }

    // Configure connection
    String hostString = (String) configuration.get("host");
    String portString = (String) configuration.get("port");
    String serialPortString = (String) configuration.get("serialPort");
    if (StringUtils.isNotBlank(hostString) && StringUtils.isNotBlank(portString)) {
        host = hostString;
        port = Integer.parseInt(portString);
        serialPort = null;
        logger.info("Connect over IP to host {}:{}", host, port);
        setProperlyConfigured(true);
    } else if (StringUtils.isNotBlank(serialPortString)) {
        serialPort = serialPortString;
        host = null;
        logger.info("Connect over serial port {}", serialPort);
        setProperlyConfigured(true);
    } else {
        setProperlyConfigured(false);
        logger.error("No connection configured");
    }

    // Close the connector if already one is open.
    if (connector != null) {
        try {
            connector.close();
        } catch (IOException ex) {
            logger.error("Error by closing connector.", ex);
        }
    }

}