Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element getAttribute.

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

Usage

From source file:org.tenje.jtrain.runnable.JTrainAccessories.java

License:Open Source License

private static void start(String[] args, Logger logger)
        throws FileNotFoundException, JDOMException, IOException, InterruptedException {
    DccppSocket socket;//from  w  ww . ja  v a 2s. c  om
    String[] addressParts;
    InetAddress address;
    int port;
    if (args.length < 1) {
        throw new IllegalArgumentException("no station address defined");
    }
    addressParts = args[0].split(":");
    if (addressParts.length < 2) {
        throw new IllegalArgumentException("no station port defined");
    }
    address = InetAddress.getByName(addressParts[0]);
    port = Integer.parseInt(addressParts[1]);
    // -

    PacketFactory packetFactory = new PacketFactoryImpl();
    PacketFactoryImpl.regiserDefaultPackets(packetFactory);
    PacketSensorRegistry sensorRegistry = null;
    PacketTurnoutRegistry turnoutRegistry = new PacketTurnoutRegistry();

    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new FileInputStream("accessories.xml"));
    Attribute attribute;
    AccessoryDecoderAddress accessoryAddress;
    List<Sensor> sensors = new ArrayList<>();
    for (Element accessoryElem : document.getRootElement().getChildren()) {
        if (accessoryElem.getName().equals("lightSignal")) {
            Map<SignalAspect, GpioPinDigitalOutput> pins = new EnumMap<>(SignalAspect.class);
            Map<AccessoryDecoderAddress, SignalAspect> addresses = new HashMap<>();
            Signal signal;
            SignalAspect aspect;
            AccessoryDecoderAddress aspectAddress = null;
            GpioPinDigitalOutput pin;
            for (Element aspectElem : accessoryElem.getChildren()) {
                if ((attribute = aspectElem.getAttribute("color")) != null) {
                    aspect = SignalAspect.valueOf(attribute.getValue().toUpperCase());
                } else {
                    throw new MissingFormatArgumentException("no color defined: " + aspectElem);
                }
                if ((attribute = aspectElem.getAttribute("address")) != null) {
                    aspectAddress = new AccessoryDecoderAddress(Integer.parseInt(attribute.getValue()), 0);
                } else {
                    throw new MissingFormatArgumentException("no address defined: " + accessoryElem);
                }
                pin = JTrainXmlReader.getOutputPin(aspectElem, "pin");
                if (pins.put(aspect, pin) != null) {
                    throw new IllegalArgumentException("color already defined: " + aspect.name().toLowerCase());
                }
                if (addresses.put(aspectAddress, aspect) != null) {
                    throw new IllegalArgumentException(
                            "address already defined: " + aspectAddress.getMainAddress());
                }
            }
            if (!pins.isEmpty()) {
                signal = new RPiSignal(aspectAddress, pins);
                for (Entry<AccessoryDecoderAddress, SignalAspect> entry : addresses.entrySet()) {
                    turnoutRegistry
                            .register(new SignalAspectControlTurnout(entry.getKey(), signal, entry.getValue()));
                }
            }
        } else if (accessoryElem.getName().equals("scheduler")) {
            SwitchableScheduler scheduler = JTrainXmlReader.getScheduler(accessoryElem);
            if ((attribute = accessoryElem.getAttribute("address")) != null) {
                accessoryAddress = new AccessoryDecoderAddress(Integer.parseInt(attribute.getValue()), 0);
                throw new UnsupportedOperationException("Not supported, yet");
            }
            scheduler.setSwitched(true);
        } else {
            if ((attribute = accessoryElem.getAttribute("address")) != null) {
                accessoryAddress = new AccessoryDecoderAddress(Integer.parseInt(attribute.getValue()), 0);
                switch (accessoryElem.getName()) {
                case "sensor": {
                    Sensor sensor = new RPiSensor(accessoryAddress,
                            JTrainXmlReader.getInputPin(accessoryElem, "pin"));
                    sensors.add(sensor);
                }
                    break;
                case "turnout": {
                    int switchTime = 0;
                    if ((attribute = accessoryElem.getAttribute("switchTime")) != null) {
                        switchTime = Integer.parseInt(attribute.getValue());
                    }
                    Turnout turnout = new RPiTurnout(accessoryAddress,
                            JTrainXmlReader.getOutputPin(accessoryElem, "straightPin"),
                            JTrainXmlReader.getOutputPin(accessoryElem, "thrownPin"), switchTime);
                    turnoutRegistry.register(turnout);
                }
                    break;
                case "servoTurnout": {
                    int pin, switchTime = 0;
                    double straightTime, thrownTime;
                    if ((attribute = accessoryElem.getAttribute("pin")) != null) {
                        pin = Integer.parseInt(attribute.getValue());
                    } else {
                        throw new MissingFormatArgumentException("no pin defined: " + accessoryElem);
                    }
                    if ((attribute = accessoryElem.getAttribute("straightPwm")) != null) {
                        straightTime = Double.parseDouble(attribute.getValue());
                    } else {
                        throw new MissingFormatArgumentException("no straightPwm defined: " + accessoryElem);
                    }
                    if ((attribute = accessoryElem.getAttribute("thrownPwm")) != null) {
                        thrownTime = Double.parseDouble(attribute.getValue());
                    } else {
                        throw new MissingFormatArgumentException("no thrownPwm defined: " + accessoryElem);
                    }
                    if ((attribute = accessoryElem.getAttribute("switchTime")) != null) {
                        switchTime = Integer.parseInt(attribute.getValue());
                    }
                    Turnout turnout = new RPiServoTurnout(accessoryAddress, pin, straightTime, thrownTime,
                            switchTime);
                    turnoutRegistry.register(turnout);
                }
                    break;
                }
            } else {
                throw new MissingFormatArgumentException("no address defined: " + accessoryElem);
            }
        }
    }

    // --
    logger.info("Connecting to " + address + ":" + port + "...");
    while (true) {
        try {
            socket = new DccppSocket(address, port, packetFactory);
            logger.info("Connected");
        } catch (IOException ex) {
            Thread.sleep(1_000);
            logger.log(Level.WARNING, "Connection failed. Retrying...");
            continue; // Retry
        }
        if (sensorRegistry == null) {
            sensorRegistry = new PacketSensorRegistry(socket, socket.getConnectedBroker());
            for (Sensor sensor : sensors) {
                sensorRegistry.register(sensor);
            }
            sensors = null;
        } else {
            sensorRegistry.setReceiver(socket.getConnectedBroker());
        }
        socket.addPacketListener(sensorRegistry);
        socket.addPacketListener(turnoutRegistry);
        synchronized (socket) {
            socket.wait(); // Wait until connection lost
        }
        logger.log(Level.WARNING, "Connection lost. Trying to reconnect...");
    }
}

From source file:org.tenje.jtrain.runnable.JTrainRPiTrain.java

License:Open Source License

private static Train buildTrain()
        throws LineUnavailableException, IOException, UnsupportedAudioFileException, JDOMException {
    SAXBuilder builder = new SAXBuilder();
    Document document = builder.build(new FileInputStream("train.xml"));
    Element root = document.getRootElement();
    int id, addressValue, forwardPin, reversePin, acceleration = DEFAULT_ACCELERATION,
            minPower = DEFAULT_MIN_POWER, maxPower = DEFAULT_MAX_POWER;
    TrainFunction function = null;// www .j a  v  a2  s.  co m
    RPiTrain train;

    addressValue = JTrainXmlReader.getInt(root, "address");
    forwardPin = JTrainXmlReader.getInt(root, "forwardPin");
    reversePin = JTrainXmlReader.getInt(root, "reversePin");

    // Parse optional attributes
    if (root.getAttribute("acceleration") != null) {
        acceleration = JTrainXmlReader.getInt(root, "acceleration");
    }
    if (root.getAttribute("minPower") != null) {
        acceleration = JTrainXmlReader.getInt(root, "minPower");
    }
    if (root.getAttribute("maxPower") != null) {
        acceleration = JTrainXmlReader.getInt(root, "maxPower");
    }

    // Create train
    train = new RPiTrain(new LongTrainAddress(addressValue), forwardPin, reversePin, acceleration, minPower,
            maxPower);
    for (Element functionElem : root.getChild("functions").getChildren()) {
        id = JTrainXmlReader.getInt(functionElem, "id");
        switch (functionElem.getName()) {
        case "gpioFunction": {
            function = getPinFunction(functionElem, train);
        }
            break;
        case "volatileSoundFunction": {
            function = getVolatileSoundFunction(functionElem);
        }
            break;
        case "permanentSoundFunction": {
            function = getPermanentSoundFunction(functionElem);
        }
            break;
        case "functionCollection": {
            Set<TrainFunction> subFunctions = new HashSet<>(functionElem.getChildren().size());
            for (Element subFunctionElem : functionElem.getChildren()) {
                switch (subFunctionElem.getName()) {
                case "gpioFunction": {
                    subFunctions.add(getPinFunction(subFunctionElem, train));
                }
                    break;
                case "volatileSoundFunction": {
                    subFunctions.add(getVolatileSoundFunction(subFunctionElem));
                }
                    break;
                case "permanentSoundFunction": {
                    subFunctions.add(getPermanentSoundFunction(subFunctionElem));
                }
                    break;
                }
            }
            function = new TrainFunctionSet(subFunctions);
        }
            break;
        }
        train.setFunction(id, function);
    }
    return train;
}

From source file:org.tenje.jtrain.runnable.JTrainRPiTrain.java

License:Open Source License

private static TrainFunction getPinFunction(Element functionElem, RPiTrain train) {
    GpioController gpio = GpioFactory.getInstance();
    if (functionElem.getAttribute("pin") != null) {
        return new RPiPinTrainFunction(JTrainXmlReader.getOutputPin(functionElem, "pin"));
    } else {//from w w w.j  a  va2  s  . co  m
        int forwardPin = -1;
        int reversePin = -1;
        if (functionElem.getAttribute("forwardPin") != null) {
            forwardPin = JTrainXmlReader.getInt(functionElem, "forwardPin");
        }
        if (functionElem.getAttribute("reversePin") != null) {
            reversePin = JTrainXmlReader.getInt(functionElem, "reversePin");
        }
        if (forwardPin == -1 && reversePin == -1) {
            throw new XmlReadException("no pin defined in gpioFunction");
        }
        GpioPinDigitalOutput forward = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(forwardPin));
        if (forward == null) {
            throw new XmlReadException("pin does not exist: " + forwardPin);
        }
        GpioPinDigitalOutput reverse = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(reversePin));
        if (reverse == null) {
            throw new XmlReadException("pin does not exist: " + reversePin);
        }
        return new RPiPinTrainFunctionDirectionDepend(forward, reverse, train);
    }
}

From source file:org.tenje.jtrain.runnable.JTrainRPiTrain.java

License:Open Source License

private static TrainFunction getVolatileSoundFunction(Element functionElem)
        throws LineUnavailableException, IOException, UnsupportedAudioFileException {
    List<Element> soundElems = functionElem.getChildren("sound");
    List<Clip> clips = new ArrayList<>(soundElems.size());
    Attribute attribute = functionElem.getAttribute("order");
    Order order;//from ww  w.  ja v  a  2s  .  c  o m
    if (attribute != null && soundElems.size() > 1) {
        order = Order.valueOf(attribute.getValue().toUpperCase());
    } else { // Not defined or only one element
        order = Order.RANDOM;
    }
    for (Element soundElem : soundElems) {
        Line.Info linfo = new Line.Info(Clip.class);
        Line line = AudioSystem.getLine(linfo);
        Clip clip = (Clip) line;
        clip.open(AudioSystem.getAudioInputStream(new File(soundElem.getTextNormalize())));
        clips.add(clip);
    }
    return new MultipleVolatileSoundFunction(clips, order);
}

From source file:org.tenje.jtrain.runnable.JTrainXmlReader.java

License:Open Source License

static SwitchableScheduler getScheduler(Element elem) {
    SwitchableSchedulerBuilder builder = new SwitchableSchedulerBuilder();
    Attribute attribute;/*from  w w w.  j  av  a  2s.co  m*/
    boolean loop = true;
    if ((attribute = elem.getAttribute("loop")) != null) {
        String attributeValue = attribute.getValue().toLowerCase();
        if (attributeValue.equals("false")) {
            loop = false;
        } else if (!attributeValue.equals("true")) {
            throw new XmlReadException("state argument: " + attribute.getValue());
        }
    }
    for (Element child : elem.getChildren()) {
        switch (child.getName()) {
        case "pinState": {
            GpioPinDigitalOutput pin = getOutputPin(child, "pin");
            boolean state = true;
            attribute = child.getAttribute("state");
            if (attribute == null) {
                throw new XmlReadException("no state defined: " + child);
            }
            String attributeValue = attribute.getValue().toLowerCase();
            if (attributeValue.equals("low")) {
                state = false;
            } else if (!attributeValue.equals("low")) {
                throw new XmlReadException("illegal state argument: " + attribute.getValue());
            }
            builder.setState(new RPiOutputPin(pin), state);
        }
            break;
        case "sleep": {
            long time = getLong(child, "time");
            builder.sleep(time);
        }
            break;
        }
    }
    return builder.build(loop);
}

From source file:org.tenje.jtrain.runnable.JTrainXmlReader.java

License:Open Source License

static TrainFunction getPinFunction(Element elem, RPiTrain train) {
    Attribute attribute;//  w  ww. jav  a2s  .  co  m
    GpioController gpio = GpioFactory.getInstance();
    GpioPinDigitalOutput pin;
    if ((attribute = elem.getAttribute("pin")) != null) {
        pin = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(getInt(elem, "pin")));
        if (pin != null) {
            return new RPiPinTrainFunction(pin);
        } else {
            throw new XmlReadException("pin does not exist: " + attribute.getValue());
        }
    } else {
        int forwardPin = -1;
        int reversePin = -1;
        if ((attribute = elem.getAttribute("forwardPin")) != null) {
            forwardPin = Integer.parseInt(attribute.getValue());
        }
        if ((attribute = elem.getAttribute("reversePin")) != null) {
            reversePin = Integer.parseInt(attribute.getValue());
        }
        if (forwardPin == -1 && reversePin == -1) {
            throw new XmlReadException("no pin defined in gpioFunction");
        }
        GpioPinDigitalOutput forward = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(forwardPin));
        if (forward == null) {
            throw new XmlReadException("pin does not exist: " + forwardPin);
        }
        GpioPinDigitalOutput reverse = gpio.provisionDigitalOutputPin(RaspiPin.getPinByAddress(reversePin));
        if (reverse == null) {
            throw new XmlReadException("pin does not exist: " + reversePin);
        }
        return new RPiPinTrainFunctionDirectionDepend(forward, reverse, train);
    }
}

From source file:org.tenje.jtrain.runnable.JTrainXmlReader.java

License:Open Source License

static TrainFunction getVolatileSoundFunction(Element functionElem)
        throws LineUnavailableException, IOException, UnsupportedAudioFileException {
    List<Element> soundElems = functionElem.getChildren("sound");
    List<Clip> clips = new ArrayList<>(soundElems.size());
    Attribute attribute = functionElem.getAttribute("order");
    Order order;//from w w w.  j a v a 2s.  co m
    if (attribute != null && soundElems.size() > 1) {
        order = Order.valueOf(attribute.getValue().toUpperCase());
    } else { // Not defined or only one element
        order = Order.RANDOM;
    }
    for (Element soundElem : soundElems) {
        Line.Info linfo = new Line.Info(Clip.class);
        Line line = AudioSystem.getLine(linfo);
        Clip clip = (Clip) line;
        clip.open(AudioSystem.getAudioInputStream(new File(soundElem.getTextNormalize())));
        clips.add(clip);
    }
    return new MultipleVolatileSoundFunction(clips, order);
}

From source file:org.tenje.jtrain.runnable.JTrainXmlReader.java

License:Open Source License

static int getInt(Element elem, String name) {
    Attribute attribute = elem.getAttribute(name);
    if (attribute != null) {
        try {/*from   w  ww.j  ava 2  s  .  com*/
            return Integer.parseInt(attribute.getValue());
        } catch (NumberFormatException ex) {
            throw new XmlReadException(
                    name + " attribute of " + elem + " is not a valid integer: " + attribute.getValue());
        }
    }
    throw new XmlReadException(name + " attribute missing for " + elem);
}

From source file:org.tenje.jtrain.runnable.JTrainXmlReader.java

License:Open Source License

static long getLong(Element elem, String name) {
    Attribute attribute = elem.getAttribute(name);
    if (attribute != null) {
        try {/*from   w ww .j a  va 2s .co  m*/
            return Long.parseLong(attribute.getValue());
        } catch (NumberFormatException ex) {
            throw new XmlReadException(
                    name + " attribute of " + elem + " is not a valid integer: " + attribute.getValue());
        }
    }
    throw new XmlReadException(name + " attribute missing for " + elem);
}

From source file:org.universaal.tools.configurationEditor.editors.ConfigurationEditor.java

License:Apache License

private void showValidator(Element e) {
    for (Control wi : selectedItemGroup.getChildren()) {
        wi.dispose();//ww  w .java  2  s. c om
    }
    Label l1;
    Text t1;

    l1 = new Label(selectedItemGroup, SWT.NONE);
    l1.setText("class:");
    l1.pack();

    t1 = new Text(selectedItemGroup, SWT.SINGLE | SWT.BORDER);
    t1.setEditable(true);
    t1.setText(e.getAttributeValue("class"));
    t1.pack();

    // ------------- <Listener> --------------

    WidgetMapping.put(t1, e.getAttribute("class"));
    t1.addModifyListener(widgetListener);

    // ------------- </Listener> --------------

    GridData gd = new GridData();
    gd.horizontalAlignment = GridData.FILL;
    gd.grabExcessHorizontalSpace = true;
    t1.setLayoutData(gd);

    // Validator attributs
    List<Element> vAtts = e.getChildren();

    for (Element vAt : vAtts) {
        l1 = new Label(selectedItemGroup, SWT.NONE);
        l1.setText(vAt.getName() + ":");

        t1 = new Text(selectedItemGroup, SWT.SINGLE | SWT.BORDER);
        t1.setEditable(true);
        t1.setText(vAt.getValue());

        // ------------- <Listener> --------------

        WidgetMapping.put(t1, vAt);
        t1.addModifyListener(widgetListener);

        // ------------- </Listener> --------------

        gd = new GridData();
        gd.horizontalAlignment = GridData.FILL;
        gd.grabExcessHorizontalSpace = true;
        t1.setLayoutData(gd);
    }
}