List of usage examples for org.apache.commons.lang StringUtils substringBetween
public static String substringBetween(String str, String open, String close)
Gets the String that is nested in between two Strings.
From source file:org.openhab.binding.sonos.handler.ZonePlayerHandler.java
protected void updateCurrentURIFormatted(String URI) { String currentURI = URI; SonosMetaData currentTrack = null;/* ww w.j av a2s. c o m*/ String coordinator = getCoordinator(); ZonePlayerHandler coordinatorHandler = getHandlerByName(coordinator); if (coordinatorHandler != null && coordinatorHandler != this) { if (currentURI.contains("x-rincon-stream")) { coordinatorHandler.updateMediaInfo(); } currentURI = coordinatorHandler.getCurrentURI(); currentTrack = coordinatorHandler.getTrackMetadata(); } else { // currentURI = getCurrentURI(); currentTrack = getTrackMetadata(); } if (currentURI != null) { String title = stateMap.get("CurrentTitle"); String resultString = stateMap.get("CurrentURIFormatted"); boolean needsUpdating = false; if (opmlPartnerID != null && currentURI.contains("x-sonosapi-stream")) { String stationID = StringUtils.substringBetween(currentURI, ":s", "?sid"); String previousStationID = stateMap.get("StationID"); Calendar now = Calendar.getInstance(); now.setTime(new Date()); now.add(Calendar.MINUTE, -1); if (previousStationID == null || !previousStationID.equals(stationID) || lastOPMLQuery == null || lastOPMLQuery.before(now)) { this.onValueReceived("StationID", stationID, "AVTransport"); String url = "http://opml.radiotime.com/Describe.ashx?c=nowplaying" + "&id=" + stationID + "&partnerId=" + opmlPartnerID + "&serial=" + getMACAddress(); String response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT); if (lastOPMLQuery == null) { lastOPMLQuery = Calendar.getInstance(); } lastOPMLQuery.setTime(new Date()); if (response != null) { List<String> fields = SonosXMLParser.getRadioTimeFromXML(response); if (fields != null && fields.size() > 0) { resultString = new String(); // radio name should be first field title = fields.get(0); Iterator<String> listIterator = fields.listIterator(); while (listIterator.hasNext()) { String field = listIterator.next(); resultString = resultString + field; if (listIterator.hasNext()) { resultString = resultString + " - "; } } needsUpdating = true; } } } } if (currentURI.contains("x-rincon-stream")) { if (currentTrack != null) { resultString = stateMap.get("CurrentTitle"); needsUpdating = true; } } if (!currentURI.contains("x-rincon-mp3") && !currentURI.contains("x-rincon-stream") && !currentURI.contains("x-sonosapi")) { if (currentTrack != null) { if (currentTrack.getAlbumArtist().equals("")) { resultString = currentTrack.getCreator() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle(); } else { resultString = currentTrack.getAlbumArtist() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle(); } needsUpdating = true; } } if (needsUpdating) { this.onValueReceived("CurrentURIFormatted", (resultString != null) ? resultString : "", "AVTransport"); this.onValueReceived("CurrentTitle", (title != null) ? title : "", "AVTransport"); } } }
From source file:org.openhab.binding.sonos.internal.SonosZonePlayer.java
public boolean updateCurrentURIFormatted() { if (stateMap != null && isConfigured()) { String currentURI = null; SonosMetaData currentURIMetaData = null; SonosMetaData currentTrack = null; if (!isGroupCoordinator()) { currentURI = getCoordinator().getCurrentURI(); currentURIMetaData = getCoordinator().getCurrentURIMetadata(); currentTrack = getCoordinator().getTrackMetadata(); } else {/* w w w.j a v a 2s. c o m*/ currentURI = getCurrentURI(); currentURIMetaData = getCurrentURIMetadata(); currentTrack = getTrackMetadata(); } if (currentURI != null) { String resultString = null; String artist = null; String album = null; String title = null; if (currentURI.contains("x-sonosapi-stream")) { //TODO: Get partner ID for openhab.org String stationID = StringUtils.substringBetween(currentURI, ":s", "?sid"); StateVariable newVariable = new StateVariable("StationID", new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())); StateVariableValue newValue = new StateVariableValue(newVariable, stationID); if (this.isUpdatedValue("StationID", newValue) || lastOPMLQuery == null || lastOPMLQuery.plusMinutes(1).isBeforeNow()) { processStateVariableValue(newVariable.getName(), newValue); String url = "http://opml.radiotime.com/Describe.ashx?c=nowplaying&id=" + stationID + "&partnerId=IAeIhU42&serial=" + getMACAddress(); String response = HttpUtil.executeUrl("GET", url, SO_TIMEOUT); //logger.debug("RadioTime Response: {}",response); lastOPMLQuery = DateTime.now(); List<String> fields = null; try { fields = SonosXMLParser.getRadioTimeFromXML(response); } catch (SAXException e) { logger.error("Could not parse RadioTime from String {}", response); } resultString = new String(); if (fields != null && fields.size() > 1) { artist = fields.get(0); title = fields.get(1); Iterator<String> listIterator = fields.listIterator(); while (listIterator.hasNext()) { String field = listIterator.next(); resultString = resultString + field; if (listIterator.hasNext()) { resultString = resultString + " - "; } } } } else { resultString = stateMap.get("CurrentURIFormatted").getValue().toString(); title = stateMap.get("CurrentTitle").getValue().toString(); artist = stateMap.get("CurrentArtist").getValue().toString(); } } else { if (currentTrack != null) { if (currentTrack.getResource().contains("x-rincon-stream")) { title = currentTrack.getTitle(); album = " "; artist = " "; resultString = title; } else if (!currentTrack.getResource().contains("x-sonosapi-stream")) { if (currentTrack.getAlbumArtist().equals("")) { resultString = currentTrack.getCreator() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle(); artist = currentTrack.getCreator(); } else { resultString = currentTrack.getAlbumArtist() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle(); artist = currentTrack.getAlbumArtist(); } album = currentTrack.getAlbum(); title = currentTrack.getTitle(); if (album.equals("")) { album = " "; } if (artist.equals("")) { artist = " "; } } } else { title = " "; album = " "; artist = " "; resultString = " "; } } StateVariable newVariable = new StateVariable("CurrentURIFormatted", new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())); StateVariableValue newValue = new StateVariableValue(newVariable, resultString); processStateVariableValue(newVariable.getName(), newValue); // update individual variables newVariable = new StateVariable("CurrentArtist", new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())); if (artist != null) { newValue = new StateVariableValue(newVariable, artist); } else { newValue = new StateVariableValue(newVariable, " "); } processStateVariableValue(newVariable.getName(), newValue); newVariable = new StateVariable("CurrentTitle", new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())); if (title != null) { newValue = new StateVariableValue(newVariable, title); } else { newValue = new StateVariableValue(newVariable, " "); } processStateVariableValue(newVariable.getName(), newValue); newVariable = new StateVariable("CurrentAlbum", new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype())); if (album != null) { newValue = new StateVariableValue(newVariable, album); } else { newValue = new StateVariableValue(newVariable, " "); } processStateVariableValue(newVariable.getName(), newValue); return true; } } return false; }
From source file:org.openhab.binding.weather.internal.gfx.WeatherTokenResolver.java
/** * Parses the token which should be replaced. *//*from w w w . j a va 2 s . com*/ private Token parseTokenName(String tokenName) { Token token = new Token(); token.full = tokenName; token.prefix = StringUtils.substringBefore(token.full, ":"); if (StringUtils.contains(token.prefix, "(")) { token.qualifier = StringUtils.substringBetween(token.prefix, "(", ")"); token.prefix = StringUtils.substringBefore(token.prefix, "("); } token.name = StringUtils.substringAfter(token.full, ":"); if (StringUtils.contains(token.name, "(")) { token.formatter = StringUtils.substringBetween(token.name, "(", ")"); token.name = StringUtils.substringBefore(token.name, "("); } if (StringUtils.contains(token.full, "[")) { token.unit = Unit.parse(StringUtils.substringBetween(token.full, "[", "]")); token.name = StringUtils.substringBefore(token.name, "["); } if (!token.isValid()) { throw new RuntimeException("Invalid weather token: " + token.full); } return token; }
From source file:org.openhab.binding.wemo.internal.handler.WemoHandler.java
/** * The {@link updateWemoState} polls the actual state of a WeMo device and * calls {@link onValueReceived} to update the statemap and channels.. * *//*ww w . j a v a2 s . c om*/ protected void updateWemoState() { String action = "GetBinaryState"; String variable = "BinaryState"; String actionService = "basicevent"; String value = null; if (getThing().getThingTypeUID().getId().equals("insight")) { action = "GetInsightParams"; variable = "InsightParams"; actionService = "insight"; } String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\""; 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:" + action + " xmlns:u=\"urn:Belkin:service:" + actionService + ":1\">" + "</u:" + action + ">" + "</s:Body>" + "</s:Envelope>"; try { String wemoURL = getWemoURL(actionService); if (wemoURL != null) { String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content); if (wemoCallResponse != null) { logger.trace("State response '{}' for device '{}' received", wemoCallResponse, getThing().getUID()); if (variable.equals("InsightParams")) { value = StringUtils.substringBetween(wemoCallResponse, "<InsightParams>", "</InsightParams>"); } else { value = StringUtils.substringBetween(wemoCallResponse, "<BinaryState>", "</BinaryState>"); } if (value != null) { logger.trace("New state '{}' for device '{}' received", value, getThing().getUID()); this.onValueReceived(variable, value, actionService + "1"); } } } } catch (Exception e) { logger.error("Failed to get actual state for device '{}': {}", getThing().getUID(), e.getMessage()); } }
From source file:org.openhab.binding.wemo.internal.handler.WemoLightHandler.java
/** * The {@link getDeviceState} is used for polling the actual state of a WeMo Light and updating the according * channel states.//from www .ja v a 2s . com */ public void getDeviceState() { logger.debug("Request actual state for LightID '{}'", wemoLightID); try { String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\""; 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:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>" + wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>"; String wemoURL = getWemoURL(); if (wemoURL != null) { String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content); if (wemoCallResponse != null) { wemoCallResponse = StringEscapeUtils.unescapeXml(wemoCallResponse); String response = StringUtils.substringBetween(wemoCallResponse, "<CapabilityValue>", "</CapabilityValue>"); logger.trace("wemoNewLightState = {}", response); String[] splitResponse = response.split(","); if (splitResponse[0] != null) { OnOffType binaryState = null; binaryState = splitResponse[0].equals("0") ? OnOffType.OFF : OnOffType.ON; if (binaryState != null) { updateState(CHANNEL_STATE, binaryState); } } if (splitResponse[1] != null) { String splitBrightness[] = splitResponse[1].split(":"); if (splitBrightness[0] != null) { int newBrightnessValue = Integer.valueOf(splitBrightness[0]); int newBrightness = Math.round(newBrightnessValue * 100 / 255); logger.trace("newBrightness = {}", newBrightness); State newBrightnessState = new PercentType(newBrightness); updateState(CHANNEL_BRIGHTNESS, newBrightnessState); currentBrightness = newBrightness; } } } } } catch (Exception e) { throw new IllegalStateException("Could not retrieve new Wemo light state", e); } }
From source file:org.openhab.binding.wemo.internal.handler.WemoMakerHandler.java
/** * The {@link updateWemoState} polls the actual state of a WeMo Maker. */// w ww . j a va 2s .co m protected void updateWemoState() { String action = "GetAttributes"; String actionService = "deviceevent"; String soapHeader = "\"urn:Belkin:service:" + actionService + ":1#" + action + "\""; 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:" + action + " xmlns:u=\"urn:Belkin:service:" + actionService + ":1\">" + "</u:" + action + ">" + "</s:Body>" + "</s:Envelope>"; try { String wemoURL = getWemoURL(actionService); if (wemoURL != null) { String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content); if (wemoCallResponse != null) { try { String stringParser = StringUtils.substringBetween(wemoCallResponse, "<attributeList>", "</attributeList>"); // Due to Belkins bad response formatting, we need to run this twice. stringParser = StringEscapeUtils.unescapeXml(stringParser); stringParser = StringEscapeUtils.unescapeXml(stringParser); logger.trace("Maker response '{}' for device '{}' received", stringParser, getThing().getUID()); stringParser = "<data>" + stringParser + "</data>"; 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("attribute"); // iterate the attributes for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList deviceIndex = element.getElementsByTagName("name"); Element line = (Element) deviceIndex.item(0); String attributeName = getCharacterDataFromElement(line); logger.trace("attributeName: {}", attributeName); NodeList deviceID = element.getElementsByTagName("value"); line = (Element) deviceID.item(0); String attributeValue = getCharacterDataFromElement(line); logger.trace("attributeValue: {}", attributeValue); switch (attributeName) { case "Switch": State relayState = attributeValue.equals("0") ? OnOffType.OFF : OnOffType.ON; if (relayState != null) { logger.debug("New relayState '{}' for device '{}' received", relayState, getThing().getUID()); updateState(CHANNEL_RELAY, relayState); } break; case "Sensor": State sensorState = attributeValue.equals("1") ? OnOffType.OFF : OnOffType.ON; if (sensorState != null) { logger.debug("New sensorState '{}' for device '{}' received", sensorState, getThing().getUID()); updateState(CHANNEL_SENSOR, sensorState); } break; } } } catch (Exception e) { logger.error("Failed to parse attributeList for WeMo Maker '{}'", this.getThing().getUID(), e); } } } } catch (Exception e) { logger.error("Failed to get attributes for device '{}'", getThing().getUID(), e); } }
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
public void wemoDiscovery() { logger.debug("wemoDiscovery() is called!"); try {/*from w ww . ja v a 2 s . com*/ final int SSDP_PORT = 1900; final int SSDP_SEARCH_PORT = 1901; // Broadcast address final String SSDP_IP = "239.255.255.250"; // Connection timeout int TIMEOUT = 1000; // Send from localhost:1901 InetAddress localhost = InetAddress.getLocalHost(); InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT); // Send to 239.255.255.250:1900 InetSocketAddress dstAddress = new InetSocketAddress(InetAddress.getByName(SSDP_IP), SSDP_PORT); // Request-Packet-Constructor StringBuffer discoveryMessage = new StringBuffer(); discoveryMessage.append("M-SEARCH * HTTP/1.1\r\n"); discoveryMessage.append("HOST: " + SSDP_IP + ":" + SSDP_PORT + "\r\n"); discoveryMessage.append("MAN: \"ssdp:discover\"\r\n"); discoveryMessage.append("MX: 5\r\n"); discoveryMessage.append("ST: urn:Belkin:service:basicevent:1\r\n"); discoveryMessage.append("\r\n"); logger.trace("Request: {}", discoveryMessage.toString()); byte[] discoveryMessageBytes = discoveryMessage.toString().getBytes(); DatagramPacket discoveryPacket = new DatagramPacket(discoveryMessageBytes, discoveryMessageBytes.length, dstAddress); // Send multi-cast packet MulticastSocket multicast = null; try { multicast = new MulticastSocket(null); multicast.bind(srcAddress); logger.trace("Source-Address = '{}'", srcAddress); multicast.setTimeToLive(5); logger.trace("Send multicast request."); multicast.send(discoveryPacket); } finally { logger.trace("Multicast ends. Close connection."); multicast.disconnect(); multicast.close(); } // Response-Listener MulticastSocket wemoReceiveSocket = null; DatagramPacket receivePacket = null; try { wemoReceiveSocket = new MulticastSocket(SSDP_SEARCH_PORT); wemoReceiveSocket.setTimeToLive(10); wemoReceiveSocket.setSoTimeout(TIMEOUT); logger.debug("Send datagram packet."); wemoReceiveSocket.send(discoveryPacket); while (true) { try { logger.debug("Receive SSDP Message."); receivePacket = new DatagramPacket(new byte[2048], 2048); wemoReceiveSocket.receive(receivePacket); final String message = new String(receivePacket.getData()); if (message.contains("Belkin")) { logger.trace("Received message: {}", message); } new Thread(new Runnable() { @Override public void run() { if (message != null) { String location = StringUtils.substringBetween(message, "LOCATION: ", "/setup.xml"); String udn = StringUtils.substringBetween(message, "USN: uuid:", "::urn:Belkin"); if (udn != null) { logger.trace("Save location '{}' for WeMo device with UDN '{}'", location, udn); wemoConfigMap.put(udn, location); logger.info("Wemo Device with UDN '{}' discovered", udn); } } } }).start(); } catch (SocketTimeoutException e) { logger.debug("Message receive timed out."); for (String name : wemoConfigMap.keySet()) { logger.trace(name + ":" + wemoConfigMap.get(name)); } break; } } } finally { if (wemoReceiveSocket != null) { wemoReceiveSocket.disconnect(); wemoReceiveSocket.close(); } } } catch (Exception e) { logger.error("Could not start wemo device discovery", e); } }
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
private String getWemoState(String itemName) { String stateRequest = null;/* w w w. java 2 s. co m*/ String returnState = null; try { stateRequest = wemoCall(itemName, "urn:Belkin:service:basicevent:1#GetBinaryState", getRequestXML); if (stateRequest != null) { returnState = StringUtils.substringBetween(stateRequest, "<BinaryState>", "</BinaryState>"); logger.debug("New binary state '{}' for item '{}' received", returnState, itemName); } } catch (Exception e) { logger.error("Failed to get binary state for item '{}'", itemName, e); } if (returnState != null) { return returnState; } else { return null; } }
From source file:org.openhab.binding.wemo.internal.WemoBinding.java
private String getInsightParams(String itemName) { String insightParamsRequest = null; String returnInsightParams = null; try {/*ww w . ja v a 2 s .com*/ insightParamsRequest = wemoCall(itemName, "urn:Belkin:service:insight:1#GetInsightParams", getInsightParamsXML); if (insightParamsRequest != null) { logger.trace("insightParamsRequestResponse :"); logger.trace("{}", insightParamsRequest); returnInsightParams = StringUtils.substringBetween(insightParamsRequest, "<InsightParams>", "</InsightParams>"); logger.debug("New raw InsightParams '{}' for device '{}' received", returnInsightParams, itemName); return returnInsightParams; } } catch (Exception e) { logger.error("Failed to get InsightParams for device '{}'", itemName, e); } return null; }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * This method writes the atom feed data to the given stream. <br/> * The given stream is not closed/* www.j a va 2 s. c o m*/ * * @param stream an open outputstream that will be written to * @param asOfDate if not null, limits the entries to only ones updated after this date * @should download full stream with null date * @should download partial stream by given date * @should stream multiline entry */ public static void getAtomFeedStream(OutputStream stream, Date asOfDate) { OutputStream out = new BufferedOutputStream(stream); File atomheaderfile = getFeedHeaderFile(); if (atomheaderfile.exists()) { try { // stream the atom header to output String atomHeader = FileUtils.readFileToString(atomheaderfile); // truncate "</feed>" from the atom header string if (StringUtils.isNotBlank(atomHeader)) { atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>"); } // write part of the header to the stream out.write(atomHeader.getBytes()); // then stream the entries to the output File atomfile = getFeedEntriesFile(); // if the date filtering parameter is passed in // we need to limit the entries to only ones, which were // updated after this date if (asOfDate != null) { String entry; BufferedReader br = new BufferedReader(new FileReader(atomfile)); while ((entry = br.readLine()) != null) { // if current entry has a new line then handle it gracefully while (!StringUtils.endsWith(entry, "</entry>")) { String newLine = br.readLine(); // if end of file is reached and new line does not contain new entry if (newLine != null && !StringUtils.contains(newLine, "<entry>")) { entry = entry.concat("\n").concat(newLine); } else { // otherwise an invalid entry is found, terminate processing throw new Exception("Invalid atom feed entry. No end tag </entry> found."); } } Date updated = new SimpleDateFormat(RFC_3339_DATE_FORMAT) .parse(StringUtils.substringBetween(entry, "<updated>", "</updated>")); if (updated.compareTo(asOfDate) > -1) { // write entry to the stream entry = entry.concat("\n"); out.write(entry.getBytes()); } else { // if entry with updatedDate lower that given one is reached // we need to stop filtering break; } } } else { // bulk write all entries to the stream out.write(FileUtils.readFileToByteArray(atomfile)); } // write the "</feed>" element that isn't in the entries file (and was // in the header file) out.write("</feed>".getBytes()); out.flush(); } catch (Exception e) { log.error("Unable to stream atom header file and/or entries file, because of error: ", e); } } }