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

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

Introduction

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

Prototype

public static String substringBetween(String str, String open, String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:org.ebayopensource.turmeric.eclipse.test.utils.ServicesUtil.java

/**
 * Gets the consumer fqn.//from  w  ww  . j a v a2s  . c  o  m
 *
 * @param prj the prj
 * @return the consumer fqn
 */
@SuppressWarnings("unchecked")
public static String getConsumerFQN(IProject prj) {

    String className = null;
    NameFileFilter fileFilter = new NameFileFilter("TestConsumer.java");

    Collection<File> files = FileUtils.listFiles(prj.getLocation().toFile(), fileFilter,
            TrueFileFilter.INSTANCE);

    Assert.assertNotNull(files);
    Assert.assertTrue(files.size() > 0);

    File consFile = files.iterator().next();

    InputStream input = null;
    try {
        input = new FileInputStream(consFile);

        LineIterator iter = IOUtils.lineIterator(input, null);
        while (iter.hasNext()) {
            String line = iter.nextLine();
            if (line.startsWith("package")) {
                className = StringUtils.substringBetween(line, "package", ";").trim();
                className = className + ".TestConsumer";
                break;
            }
        }
        iter.close();
    } catch (Exception e) {
        e.printStackTrace();
        IOUtils.closeQuietly(input);
    }

    return className;

}

From source file:org.ebayopensource.turmeric.eclipse.test.utils.ServicesUtil.java

/**
 * Gets the domain classifier from wsdl.
 *
 * @param wsdlFilePath the wsdl file path
 * @return the domain classifier from wsdl
 *///from w  ww .  ja  va  2 s .  c  o m
public static String getDomainClassifierFromWsdl(String wsdlFilePath) { // gets
    // the
    // domain
    // classifier
    String domainClassifier = "";
    try {
        final Definition definition = WSDLUtil.readWSDL(wsdlFilePath);
        final String targetNamespace = definition.getTargetNamespace();

        if (StringUtils.isNotEmpty(targetNamespace)
                && targetNamespace.contains(TurmericConstants.DEFAULT_SERVICE_NAMESPACE_PREFIX)
                && !targetNamespace.equals(TurmericConstants.DEFAULT_SERVICE_NAMESPACE)) {
            domainClassifier = StringUtils.substringBetween(targetNamespace,
                    TurmericConstants.DEFAULT_SERVICE_NAMESPACE_PREFIX + "/", "/").trim();
        } else {
            domainClassifier = DEFAULT_DOMAIN_CLASSIFIER;

        }
    } catch (final WSDLException wsdlE) {
        wsdlE.printStackTrace();
    }
    return StringUtils.capitalize(domainClassifier);
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Gets the library name from protocol string.
 *
 * @param typeLibString the type lib string
 * @return the library name from protocol string
 *//*from w ww  . j a v  a2 s . co  m*/
public static String getLibraryNameFromProtocolString(String typeLibString) {
    String retValue = null;
    if (!StringUtils.isEmpty(typeLibString)
            && typeLibString.startsWith(SOATypeLibraryConstants.TURMERIC_XSD_FILE_PROTOCOL)) {
        if (isNewStylePrototocol(typeLibString)) {
            retValue = StringUtils.substringBetween(typeLibString, SOATypeLibraryConstants.PROTOCOL_DELIMITER,
                    SOATypeLibraryConstants.PROTOCOL_DELIMITER);
        }
    }
    return retValue;
}

From source file:org.ebayopensource.turmeric.eclipse.ui.UIActivator.java

/**
 * Gets the categories./*from  w w w .j av  a 2  s  .c o m*/
 *
 * @return the categories
 * Parses the global config categories the format is CATEGORIES =
 * {COMMON, DOMAIN, SERVICE}
 */
public static List<String> getCategories() {
    List<String> categories = new ArrayList<String>();
    String categoryStr = "";
    try {
        categoryStr = SOAGlobalConfigAccessor.getCategoriesForTypeLib();

    } catch (IOException e) {
        SOALogger.getLogger().error(e);
    }
    if (!StringUtils.isEmpty(categoryStr)) {
        categories = Arrays.asList(StringUtils.split(StringUtils.substringBetween(categoryStr, "{", "}"), ","));
    }
    return categories;
}

From source file:org.eclipse.leshan.server.demo.servlet.ClientServlet.java

/**
 * {@inheritDoc}// ww  w  . j  a  v  a 2s  . c  o  m
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {
            String target = StringUtils.substringBetween(req.getPathInfo(), clientEndpoint, "/observe");
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null
                        ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                        : null;

                // create & process request
                ObserveRequest request = new ObserveRequest(contentFormat, target);
                ObserveResponse cResponse = server.send(registration, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }

    String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);

    // /clients/endPoint/LWRequest : do LightWeight M2M execute request on a given client.
    if (path.length == 4) {
        try {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                ExecuteRequest request = new ExecuteRequest(target, IOUtils.toString(req.getInputStream()));
                ExecuteResponse cResponse = server.send(registration, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
    if (2 <= path.length && path.length <= 3) {
        try {
            Registration registration = server.getRegistrationService().getByEndpoint(clientEndpoint);
            if (registration != null) {
                // get content format
                String contentFormatParam = req.getParameter(FORMAT_PARAM);
                ContentFormat contentFormat = contentFormatParam != null
                        ? ContentFormat.fromName(contentFormatParam.toUpperCase())
                        : null;

                // create & process request
                LwM2mNode node = extractLwM2mNode(target, req);
                if (node instanceof LwM2mObjectInstance) {
                    CreateRequest request = new CreateRequest(contentFormat, target,
                            (LwM2mObjectInstance) node);
                    CreateResponse cResponse = server.send(registration, request, TIMEOUT);
                    processDeviceResponse(req, resp, cResponse);
                } else {
                    throw new IllegalArgumentException("payload must contain an object instance");
                }
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (RuntimeException | InterruptedException e) {
            handleException(e, resp);
        }
        return;
    }
}

From source file:org.eclipse.leshan.standalone.servlet.ClientServlet.java

/**
 * {@inheritDoc}//  www.j  ava 2 s.c o m
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] path = StringUtils.split(req.getPathInfo(), '/');
    String clientEndpoint = path[0];

    // /clients/endPoint/LWRequest/observe : do LightWeight M2M observe request on a given client.
    if (path.length >= 4 && "observe".equals(path[path.length - 1])) {
        try {
            String target = StringUtils.substringBetween(req.getPathInfo(), clientEndpoint, "/observe");
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                ObserveRequest request = new ObserveRequest(target);
                LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    String target = StringUtils.removeStart(req.getPathInfo(), "/" + clientEndpoint);

    // /clients/endPoint/LWRequest : do LightWeight M2M execute request on a given client.
    if (path.length == 4) {
        try {
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                ExecuteRequest request = new ExecuteRequest(target, IOUtils.toByteArray(req.getInputStream()),
                        null);
                LwM2mResponse cResponse = server.send(client, request, TIMEOUT);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }

    // /clients/endPoint/LWRequest : do LightWeight M2M create request on a given client.
    if (2 <= path.length && path.length <= 3) {
        try {
            Client client = server.getClientRegistry().get(clientEndpoint);
            if (client != null) {
                LwM2mResponse cResponse = this.createRequest(client, target, req, resp);
                processDeviceResponse(req, resp, cResponse);
            } else {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().format("no registered client with id '%s'", clientEndpoint).flush();
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Invalid request", e);
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().append(e.getMessage()).flush();
        } catch (ResourceAccessException | RequestFailedException e) {
            LOG.warn(String.format("Error accessing resource %s%s.", req.getServletPath(), req.getPathInfo()),
                    e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().append(e.getMessage()).flush();
        }
        return;
    }
}

From source file:org.eclipse.smarthome.binding.astro.discovery.AstroDiscoveryService.java

/**
 * {@inheritDoc}//from  w  w w.j  av  a2  s . co  m
 */
@Override
protected void startScan() {
    logger.debug("Starting Astro discovery scan");
    String result = null;
    try {
        result = HttpUtil.executeUrl("GET", "http://ip-api.com/json/?fields=lat,lon", 5000);
    } catch (IOException e) {
        logger.warn("Can't get latitude and longitude for the current location: {}", e);
    }

    if (result != null) {

        String lat = StringUtils.trim(StringUtils.substringBetween(result, "\"lat\":", ","));
        String lon = StringUtils.trim(StringUtils.substringBetween(result, "\"lon\":", "}"));

        try {
            Double latitude = Double.parseDouble(lat);
            Double longitude = Double.parseDouble(lon);

            logger.info("Evaluated Astro geolocation: latitude: {}, longitude: {}", latitude, longitude);

            ThingTypeUID sunType = new ThingTypeUID(BINDING_ID, SUN);
            ThingTypeUID moonType = new ThingTypeUID(BINDING_ID, MOON);

            ThingUID sunThing = new ThingUID(sunType, LOCAL);
            ThingUID moonThing = new ThingUID(moonType, LOCAL);

            String propGeolocation = String.format("%s,%s", latitude, longitude);
            thingDiscovered(DiscoveryResultBuilder.create(sunThing).withLabel("Local Sun")
                    .withProperty("geolocation", propGeolocation).build());
            thingDiscovered(DiscoveryResultBuilder.create(moonThing).withLabel("Local Moon")
                    .withProperty("geolocation", propGeolocation).build());
        } catch (Exception ex) {
            logger.warn("Can't discover Astro geolocation");
        }
    }
}

From source file:org.eclipse.smarthome.binding.sonos.handler.ZonePlayerHandler.java

protected void updateMediaInformation() {

    String currentURI = getCurrentURI();
    SonosMetaData currentTrack = getTrackMetadata();
    SonosMetaData currentUriMetaData = getCurrentURIMetadata();

    String artist = null;/*w  ww .  j a va2 s. c  o  m*/
    String album = null;
    String title = null;
    String resultString = null;
    boolean needsUpdating = false;

    if (currentURI == null) {
        // Do nothing
    }

    else if (currentURI.isEmpty()) {
        // Reset data
        needsUpdating = true;
    }

    else if (currentURI.contains(GROUP_URI)) {
        // The Sonos is a slave member of a group, we do nothing
        // The media information will be updated by the coordinator
        // Notification of group change occurs later, so we just check the URI
    }

    else if (isPlayingStream(currentURI)) {
        // Radio stream (tune-in)
        boolean opmlUrlSucceeded = false;
        if (opmlUrl != null) {
            String stationID = StringUtils.substringBetween(currentURI, ":s", "?sid");
            String mac = getMACAddress();
            if (stationID != null && !stationID.isEmpty() && mac != null && !mac.isEmpty()) {
                String url = opmlUrl;
                url = StringUtils.replace(url, "%id", stationID);
                url = StringUtils.replace(url, "%serial", mac);

                String response = null;
                try {
                    response = HttpUtil.executeUrl("GET", url, SOCKET_TIMEOUT);
                } catch (IOException e) {
                    logger.debug("Request to device failed: {}", e);
                }

                if (response != null) {
                    List<String> fields = SonosXMLParser.getRadioTimeFromXML(response);

                    if (fields != null && fields.size() > 0) {

                        opmlUrlSucceeded = true;

                        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 (!opmlUrlSucceeded) {
            if (currentUriMetaData != null) {
                title = currentUriMetaData.getTitle();
                if ((currentTrack == null) || (currentTrack.getStreamContent() == null)
                        || currentTrack.getStreamContent().isEmpty()) {
                    resultString = title;
                } else {
                    resultString = title + " - " + currentTrack.getStreamContent();
                }
                needsUpdating = true;
            }
        }
    }

    else if (isPlayingLineIn(currentURI)) {
        if (currentTrack != null) {
            title = currentTrack.getTitle();
            resultString = title;
            needsUpdating = true;
        }
    }

    else if (!currentURI.contains("x-rincon-mp3") && !currentURI.contains("x-sonosapi")) {
        if (currentTrack != null) {
            artist = !currentTrack.getAlbumArtist().isEmpty() ? currentTrack.getAlbumArtist()
                    : currentTrack.getCreator();
            album = currentTrack.getAlbum();
            title = currentTrack.getTitle();
            resultString = artist + " - " + album + " - " + title;
            needsUpdating = true;
        }
    }

    if (needsUpdating) {
        String albumArtURI = (currentTrack != null && currentTrack.getAlbumArtUri() != null
                && !currentTrack.getAlbumArtUri().isEmpty()) ? currentTrack.getAlbumArtUri() : "";
        for (String member : getZoneGroupMembers()) {
            try {
                ZonePlayerHandler memberHandler = getHandlerByName(member);
                if (memberHandler != null && memberHandler.getThing() != null
                        && ThingStatus.ONLINE.equals(memberHandler.getThing().getStatus())) {
                    memberHandler.onValueReceived("CurrentArtist", (artist != null) ? artist : "",
                            "AVTransport");
                    memberHandler.onValueReceived("CurrentAlbum", (album != null) ? album : "", "AVTransport");
                    memberHandler.onValueReceived("CurrentTitle", (title != null) ? title : "", "AVTransport");
                    memberHandler.onValueReceived("CurrentURIFormatted",
                            (resultString != null) ? resultString : "", "AVTransport");
                    memberHandler.onValueReceived("CurrentAlbumArtURI", albumArtURI, "AVTransport");
                }
            } catch (IllegalStateException e) {
                logger.warn("Cannot update media data for group member ({})", e.getMessage());
            }
        }
    }
}

From source file:org.eclipse.smarthome.binding.sonos.internal.handler.ZonePlayerHandler.java

private String extractStationId(String uri) {
    String stationID = null;// w w  w  .  j  a v  a2s . co m
    if (isPlayingStream(uri)) {
        stationID = StringUtils.substringBetween(uri, ":s", "?sid");
    } else if (isPlayingRadioStartedByAmazonEcho(uri)) {
        stationID = StringUtils.substringBetween(uri, "sid=s", "&");
    }
    return stationID;
}

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

public void sendWemoDiscoveryMessage() {
    logger.debug("wemoDiscovery() is called!");
    try {/* w  w w .j a v  a 2  s.co  m*/

        InetAddress localhost = InetAddress.getLocalHost();
        InetSocketAddress srcAddress = new InetSocketAddress(localhost, SSDP_SEARCH_PORT);

        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("ST: upnp:rootdevice\r\n");
        discoveryMessage.append("MAN: \"ssdp:discover\"\r\n");
        discoveryMessage.append("MX: 5\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(4);
            logger.debug("Send multicast request.");
            multicast.send(discoveryPacket);
        } finally {
            logger.trace("Multicast ends. Close connection.");
            multicast.disconnect();
            multicast.close();
        }

        // Response-Listener
        DatagramSocket wemoReceiveSocket = null;
        DatagramPacket receivePacket = null;
        try {
            wemoReceiveSocket = new DatagramSocket(SSDP_SEARCH_PORT);
            wemoReceiveSocket.setSoTimeout(TIMEOUT);
            logger.debug("Send datagram packet.");
            wemoReceiveSocket.send(discoveryPacket);

            while (true) {
                try {
                    receivePacket = new DatagramPacket(new byte[1536], 1536);
                    wemoReceiveSocket.receive(receivePacket);
                    final String message = new String(receivePacket.getData());
                    logger.trace("Received message: {}", message);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String label = "WeMo Device";
                            String wemoUDN = null;
                            String wemoLocation = null;
                            String wemoFriendlyName = null;
                            String wemoModelName = null;
                            ThingUID uid = null;

                            if (message != null) {
                                if (message.contains("Socket-1_0") || message.contains("Insight-1_0")
                                        || message.contains("Motion-1_0")
                                        || message.contains("Lightswitch-1_0")) {
                                    wemoUDN = StringUtils.substringBetween(message, "USN: uuid:",
                                            "::upnp:rootdevice");
                                    logger.debug("Wemo device with UDN '{}' found", wemoUDN);
                                    wemoLocation = StringUtils.substringBetween(message, "LOCATION: ",
                                            "/setup.xml");
                                    if (wemoLocation != null) {
                                        try {
                                            int timeout = 5000;
                                            String response = HttpUtil.executeUrl("GET",
                                                    wemoLocation + "/setup.xml", timeout);
                                            wemoFriendlyName = StringUtils.substringBetween(response,
                                                    "<friendlyName>", "</friendlyName>");
                                            logger.debug("Wemo device '{}' found at '{}'", wemoFriendlyName,
                                                    wemoLocation);
                                            wemoModelName = StringUtils.substringBetween(response,
                                                    "<modelName>", "</modelName>");
                                            logger.trace("Wemo device '{}' has model name '{}'",
                                                    wemoFriendlyName, wemoModelName);
                                            label = "Wemo" + wemoModelName;

                                            switch (wemoModelName) {
                                            case "Socket":
                                                logger.debug(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_SOCKET_TYPE_UID, wemoUDN);

                                                break;
                                            case "Insight":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_INSIGHT_TYPE_UID, wemoUDN);
                                                break;
                                            case "LightSwitch":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_LIGHTSWITCH_TYPE_UID, wemoUDN);
                                                break;
                                            case "Motion":
                                                logger.trace(
                                                        "Creating ThingUID for device model '{}' with UDN '{}'",
                                                        wemoModelName, wemoUDN);
                                                uid = new ThingUID(WEMO_MOTION_TYPE_UID, wemoUDN);
                                                break;
                                            }
                                            Map<String, Object> properties = new HashMap<>(4);
                                            properties.put(UDN, wemoUDN);
                                            properties.put(LOCATION, wemoLocation);

                                            DiscoveryResult result = DiscoveryResultBuilder.create(uid)
                                                    .withProperties(properties).withLabel(label).build();
                                            thingDiscovered(result);

                                        } catch (Exception te) {
                                            logger.error("Could not discover WeMo device", te);
                                        }
                                    }
                                }
                            }
                        }
                    }).start();

                } catch (SocketTimeoutException e) {
                    logger.debug("Message receive timed out.");
                    break;
                }
            }
        } finally {
            if (wemoReceiveSocket != null) {
                wemoReceiveSocket.disconnect();
                wemoReceiveSocket.close();
            }
        }

    } catch (Exception e) {
        logger.error("Could not send Wemo device discovery", e);
    }

}