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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private String addSessionToken(String request, String sessionToken) {
    String correctedRequest = request;
    if (!correctedRequest.contains(ParameterKeys.TOKEN)) {
        if (correctedRequest.contains("?")) {
            correctedRequest = correctedRequest + "&" + ParameterKeys.TOKEN + "=" + sessionToken;
        } else {/* w  w  w . j a va  2  s.com*/
            correctedRequest = correctedRequest + "?" + ParameterKeys.TOKEN + "=" + sessionToken;
        }
    } else {
        correctedRequest = StringUtils.replaceOnce(correctedRequest,
                StringUtils.substringBefore(
                        StringUtils.substringAfter(correctedRequest, ParameterKeys.TOKEN + "="), "&"),
                sessionToken);

    }
    return correctedRequest;
}

From source file:org.eclipse.smarthome.binding.homematic.handler.HomematicThingHandler.java

@Override
public void handleConfigurationUpdate(Map<String, Object> configurationParameters)
        throws ConfigValidationException {
    super.handleConfigurationUpdate(configurationParameters);

    try {/*ww w.ja  va2s .  c  o  m*/
        HomematicGateway gateway = getHomematicGateway();
        HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing()));

        for (Entry<String, Object> configurationParameter : configurationParameters.entrySet()) {
            String key = configurationParameter.getKey();
            Object newValue = configurationParameter.getValue();

            if (key.startsWith("HMP_")) {
                key = StringUtils.removeStart(key, "HMP_");
                Integer channelNumber = NumberUtils.toInt(StringUtils.substringBefore(key, "_"));
                String dpName = StringUtils.substringAfter(key, "_");

                HmDatapointInfo dpInfo = new HmDatapointInfo(device.getAddress(), HmParamsetType.MASTER,
                        channelNumber, dpName);
                HmDatapoint dp = device.getChannel(channelNumber).getDatapoint(dpInfo);

                if (dp != null) {
                    try {
                        if (newValue != null) {
                            if (newValue instanceof BigDecimal) {
                                final BigDecimal decimal = (BigDecimal) newValue;
                                if (dp.isIntegerType()) {
                                    newValue = decimal.intValue();
                                } else if (dp.isFloatType()) {
                                    newValue = decimal.doubleValue();
                                }
                            }
                            if (ObjectUtils.notEqual(dp.isEnumType() ? dp.getOptionValue() : dp.getValue(),
                                    newValue)) {
                                sendDatapoint(dp, new HmDatapointConfig(), newValue);
                            }
                        }
                    } catch (IOException ex) {
                        logger.error("Error setting thing property {}: {}", dpInfo, ex.getMessage());
                    }
                } else {
                    logger.error("Can't find datapoint for thing property {}", dpInfo);
                }
            }
        }
        gateway.triggerDeviceValuesReload(device);
    } catch (HomematicClientException | GatewayNotAvailableException ex) {
        logger.error("Error setting thing properties: {}", ex.getMessage(), ex);
    }
}

From source file:org.eclipse.smarthome.binding.homematic.internal.type.MetadataUtils.java

/**
 * Loads the standard datapoints for channel metadata generation.
 *///  w  w w  . j a va2s  .  c  o m
private static void loadStandardDatapoints() {
    Bundle bundle = FrameworkUtil.getBundle(MetadataUtils.class);
    try (InputStream stream = bundle.getResource("homematic/standard-datapoints.properties").openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {

        String line;
        while ((line = reader.readLine()) != null) {
            if (StringUtils.trimToNull(line) != null && !StringUtils.startsWith(line, "#")) {
                String channelType = StringUtils.trimToNull(StringUtils.substringBefore(line, "|"));
                String datapointName = StringUtils.trimToNull(StringUtils.substringAfter(line, "|"));

                Set<String> channelDatapoints = standardDatapoints.get(channelType);
                if (channelDatapoints == null) {
                    channelDatapoints = new HashSet<String>();
                    standardDatapoints.put(channelType, channelDatapoints);
                }

                channelDatapoints.add(datapointName);
            }
        }
    } catch (IllegalStateException | IOException e) {
        logger.warn("Can't load standard-datapoints.properties file!", e);
    }
}

From source file:org.eclipse.smarthome.binding.wemo.discovery.WemoLinkDiscoveryService.java

@Override
protected void startScan() {

    logger.trace("Starting WeMoEndDevice discovery on WeMo Link {}", wemoBridgeHandler.getThing().getUID());
    try {//from  w ww . j a  v  a 2 s . co m

        String devUDN = "uuid:" + wemoBridgeHandler.getThing().getConfiguration().get(UDN).toString();
        logger.trace("devUDN = '{}'", devUDN);

        String soapHeader = "\"urn:Belkin:service:bridge:1#GetEndDevices\"";
        String content = "<?xml version=\"1.0\"?>"
                + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
                + "<s:Body>" + "<u:GetEndDevices xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DevUDN>" + devUDN
                + "</DevUDN><ReqListType>PAIRED_LIST</ReqListType>" + "</u:GetEndDevices>" + "</s:Body>"
                + "</s:Envelope>";

        URL descriptorURL = service.getDescriptorURL(this);

        if (descriptorURL != null) {
            String deviceURL = StringUtils.substringBefore(descriptorURL.toString(), "/setup.xml");
            String wemoURL = deviceURL + "/upnp/control/bridge1";

            String endDeviceRequest = WemoHttpCall.executeCall(wemoURL, soapHeader, content);

            if (endDeviceRequest != null) {
                logger.trace("endDeviceRequest answered '{}'", endDeviceRequest);

                try {
                    String stringParser = StringUtils.substringBetween(endDeviceRequest, "<DeviceLists>",
                            "</DeviceLists>");

                    stringParser = StringEscapeUtils.unescapeXml(stringParser);

                    // check if there are already paired devices with WeMo Link
                    if ("0".equals(stringParser)) {
                        logger.debug("There are no devices connected with WeMo Link. Exit discovery");
                        return;
                    }

                    // Build parser for received <DeviceList>
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(stringParser));

                    Document doc = db.parse(is);
                    NodeList nodes = doc.getElementsByTagName("DeviceInfo");

                    // iterate the devices
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Element element = (Element) nodes.item(i);

                        NodeList deviceIndex = element.getElementsByTagName("DeviceIndex");
                        Element line = (Element) deviceIndex.item(0);
                        logger.trace("DeviceIndex: " + getCharacterDataFromElement(line));

                        NodeList deviceID = element.getElementsByTagName("DeviceID");
                        line = (Element) deviceID.item(0);
                        String endDeviceID = getCharacterDataFromElement(line);
                        logger.trace("DeviceID: " + endDeviceID);

                        NodeList friendlyName = element.getElementsByTagName("FriendlyName");
                        line = (Element) friendlyName.item(0);
                        String endDeviceName = getCharacterDataFromElement(line);
                        logger.trace("FriendlyName: " + endDeviceName);

                        NodeList vendor = element.getElementsByTagName("Manufacturer");
                        line = (Element) vendor.item(0);
                        String endDeviceVendor = getCharacterDataFromElement(line);
                        logger.trace("Manufacturer: " + endDeviceVendor);

                        NodeList model = element.getElementsByTagName("ModelCode");
                        line = (Element) model.item(0);
                        String endDeviceModelID = getCharacterDataFromElement(line);
                        endDeviceModelID = endDeviceModelID.replaceAll(NORMALIZE_ID_REGEX, "_");

                        logger.trace("ModelCode: " + endDeviceModelID);

                        if (SUPPORTED_THING_TYPES.contains(new ThingTypeUID(BINDING_ID, endDeviceModelID))) {
                            logger.debug("Discovered a WeMo LED Light thing with ID '{}'", endDeviceID);

                            ThingUID bridgeUID = wemoBridgeHandler.getThing().getUID();
                            ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, endDeviceModelID);

                            if (thingTypeUID.equals(THING_TYPE_MZ100)) {
                                String thingLightId = endDeviceID;
                                ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingLightId);

                                Map<String, Object> properties = new HashMap<>(1);
                                properties.put(DEVICE_ID, endDeviceID);

                                DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
                                        .withProperties(properties)
                                        .withBridge(wemoBridgeHandler.getThing().getUID())
                                        .withLabel(endDeviceName).build();

                                thingDiscovered(discoveryResult);
                            }

                        } else {
                            logger.debug("Discovered an unsupported device :");
                            logger.debug("DeviceIndex : " + getCharacterDataFromElement(line));
                            logger.debug("DeviceID    : " + endDeviceID);
                            logger.debug("FriendlyName: " + endDeviceName);
                            logger.debug("Manufacturer: " + endDeviceVendor);
                            logger.debug("ModelCode   : " + endDeviceModelID);
                        }

                    }
                } catch (Exception e) {
                    logger.error("Failed to parse endDevices for bridge '{}'",
                            wemoBridgeHandler.getThing().getUID(), e);
                }
            }

        }
    } catch (Exception e) {
        logger.error("Failed to get endDevices for bridge '{}'", wemoBridgeHandler.getThing().getUID(), e);
    }
}

From source file:org.eclipse.smarthome.binding.wemo.handler.WemoCoffeeHandler.java

public String getWemoURL(String actionService) {
    URL descriptorURL = service.getDescriptorURL(this);
    String wemoURL = null;//from   w  ww.  j  a v a  2  s  .  c o m
    if (descriptorURL != null) {
        String deviceURL = StringUtils.substringBefore(descriptorURL.toString(), "/setup.xml");
        wemoURL = deviceURL + "/upnp/control/" + actionService + "1";
        return wemoURL;
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.wemo.handler.WemoLightHandler.java

public String getWemoURL() {
    URL descriptorURL = service.getDescriptorURL(this);
    String wemoURL = null;//from  w  w w . ja  v  a2 s . c om
    if (descriptorURL != null) {
        String deviceURL = StringUtils.substringBefore(descriptorURL.toString(), "/setup.xml");
        wemoURL = deviceURL + "/upnp/control/bridge1";
        return wemoURL;
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.wemo.internal.discovery.WemoLinkDiscoveryService.java

@Override
public void startScan() {
    logger.trace("Starting WeMoEndDevice discovery on WeMo Link {}", wemoBridgeHandler.getThing().getUID());
    try {//  w ww.ja v  a2  s  . co m
        String devUDN = "uuid:" + wemoBridgeHandler.getThing().getConfiguration().get(UDN).toString();
        logger.trace("devUDN = '{}'", devUDN);

        String soapHeader = "\"urn:Belkin:service:bridge:1#GetEndDevices\"";
        String content = "<?xml version=\"1.0\"?>"
                + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
                + "<s:Body>" + "<u:GetEndDevices xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DevUDN>" + devUDN
                + "</DevUDN><ReqListType>PAIRED_LIST</ReqListType>" + "</u:GetEndDevices>" + "</s:Body>"
                + "</s:Envelope>";

        URL descriptorURL = service.getDescriptorURL(this);

        if (descriptorURL != null) {
            String deviceURL = StringUtils.substringBefore(descriptorURL.toString(), "/setup.xml");
            String wemoURL = deviceURL + "/upnp/control/bridge1";

            String endDeviceRequest = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);

            if (endDeviceRequest != null) {
                logger.trace("endDeviceRequest answered '{}'", endDeviceRequest);

                try {
                    String stringParser = StringUtils.substringBetween(endDeviceRequest, "<DeviceLists>",
                            "</DeviceLists>");

                    stringParser = StringEscapeUtils.unescapeXml(stringParser);

                    // check if there are already paired devices with WeMo Link
                    if ("0".equals(stringParser)) {
                        logger.debug("There are no devices connected with WeMo Link. Exit discovery");
                        return;
                    }

                    // Build parser for received <DeviceList>
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(stringParser));

                    Document doc = db.parse(is);
                    NodeList nodes = doc.getElementsByTagName("DeviceInfo");

                    // iterate the devices
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Element element = (Element) nodes.item(i);

                        NodeList deviceIndex = element.getElementsByTagName("DeviceIndex");
                        Element line = (Element) deviceIndex.item(0);
                        logger.trace("DeviceIndex: {}", getCharacterDataFromElement(line));

                        NodeList deviceID = element.getElementsByTagName("DeviceID");
                        line = (Element) deviceID.item(0);
                        String endDeviceID = getCharacterDataFromElement(line);
                        logger.trace("DeviceID: {}", endDeviceID);

                        NodeList friendlyName = element.getElementsByTagName("FriendlyName");
                        line = (Element) friendlyName.item(0);
                        String endDeviceName = getCharacterDataFromElement(line);
                        logger.trace("FriendlyName: {}", endDeviceName);

                        NodeList vendor = element.getElementsByTagName("Manufacturer");
                        line = (Element) vendor.item(0);
                        String endDeviceVendor = getCharacterDataFromElement(line);
                        logger.trace("Manufacturer: {}", endDeviceVendor);

                        NodeList model = element.getElementsByTagName("ModelCode");
                        line = (Element) model.item(0);
                        String endDeviceModelID = getCharacterDataFromElement(line);
                        endDeviceModelID = endDeviceModelID.replaceAll(NORMALIZE_ID_REGEX, "_");

                        logger.trace("ModelCode: {}", endDeviceModelID);

                        if (SUPPORTED_THING_TYPES.contains(new ThingTypeUID(BINDING_ID, endDeviceModelID))) {
                            logger.debug("Discovered a WeMo LED Light thing with ID '{}'", endDeviceID);

                            ThingUID bridgeUID = wemoBridgeHandler.getThing().getUID();
                            ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, endDeviceModelID);

                            if (thingTypeUID.equals(THING_TYPE_MZ100)) {
                                String thingLightId = endDeviceID;
                                ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingLightId);

                                Map<String, Object> properties = new HashMap<>(1);
                                properties.put(DEVICE_ID, endDeviceID);

                                DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
                                        .withProperties(properties)
                                        .withBridge(wemoBridgeHandler.getThing().getUID())
                                        .withLabel(endDeviceName).build();

                                thingDiscovered(discoveryResult);
                            }
                        } else {
                            logger.debug("Discovered an unsupported device :");
                            logger.debug("DeviceIndex : {}", getCharacterDataFromElement(line));
                            logger.debug("DeviceID    : {}", endDeviceID);
                            logger.debug("FriendlyName: {}", endDeviceName);
                            logger.debug("Manufacturer: {}", endDeviceVendor);
                            logger.debug("ModelCode   : {}", endDeviceModelID);
                        }

                    }
                } catch (Exception e) {
                    logger.error("Failed to parse endDevices for bridge '{}'",
                            wemoBridgeHandler.getThing().getUID(), e);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Failed to get endDevices for bridge '{}'", wemoBridgeHandler.getThing().getUID(), e);
    }
}

From source file:org.eclipse.smarthome.config.core.ConfigDispatcher.java

private static String[] parseLine(final String filePath, final String line) {
    String trimmedLine = line.trim();
    if (trimmedLine.startsWith("#") || trimmedLine.isEmpty()) {
        return null;
    }/* www  . j av a  2  s .  c o m*/

    if (trimmedLine.substring(1).contains(":")) {
        String pid = StringUtils.substringBefore(line, ":");
        String rest = line.substring(pid.length() + 1);
        if (!pid.contains(".")) {
            pid = "org.eclipse.smarthome." + pid;
        }
        if (!rest.isEmpty() && rest.substring(1).contains("=")) {
            String property = StringUtils.substringBefore(rest, "=");
            String value = rest.substring(property.length() + 1);
            return new String[] { pid.trim(), property.trim(), value.trim() };
        }
    }

    logger.warn("Cannot parse line '{}' of main configuration file '{}'.", line, filePath);
    return null;
}

From source file:org.eclipse.smarthome.config.dispatch.internal.ConfigDispatcher.java

private String[] parseLine(final String filePath, final String line) {
    String trimmedLine = line.trim();
    if (trimmedLine.startsWith("#") || trimmedLine.isEmpty()) {
        return null;
    }//from  w w  w .  j  a  va  2s. c  o m

    String pid = null; // no override of the pid
    String key = StringUtils.substringBefore(trimmedLine, "=");
    if (key.contains(":")) {
        pid = StringUtils.substringBefore(key, ":");
        trimmedLine = trimmedLine.substring(pid.length() + 1);
        pid = pid.trim();
    }
    if (!trimmedLine.isEmpty() && trimmedLine.substring(1).contains("=")) {
        String property = StringUtils.substringBefore(trimmedLine, "=");
        String value = trimmedLine.substring(property.length() + 1);
        return new String[] { pid, property.trim(), value.trim() };
    } else {
        logger.warn("Could not parse line '{}'", line);
        return null;
    }
}

From source file:org.eclipse.smarthome.core.audio.internal.AudioServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    removeTimedOutStreams();//w w w  .  ja va 2s.  co  m

    final String streamId = StringUtils
            .substringBefore(StringUtils.substringAfterLast(req.getRequestURI(), "/"), ".");

    try (final InputStream stream = prepareInputStream(streamId, resp)) {
        if (stream == null) {
            logger.debug("Received request for invalid stream id at {}", req.getRequestURI());
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            IOUtils.copy(stream, resp.getOutputStream());
            resp.flushBuffer();
        }
    } catch (final AudioException ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}