public static SsdpResponse parse ( DatagramPacket packet ) { Map < String , String > headers = new HashMap < String , String > ( ) ; byte [ ] body = null ; SsdpResponse . Type type = null ; byte [ ] data = packet . getData ( ) ; // Find position of the last header data int endOfHeaders = findEndOfHeaders ( data ) ; if ( endOfHeaders == - 1 ) { endOfHeaders = packet . getLength ( ) ; } // Retrieve all header lines String [ ] headerLines = new String ( Arrays . copyOfRange ( data , 0 , endOfHeaders ) ) . split ( "\r\n" ) ; // Determine type of message if ( SEARCH_REQUEST_LINE_PATTERN . matcher ( headerLines [ 0 ] ) . matches ( ) ) { type = SsdpResponse . Type . DISCOVERY_RESPONSE ; } else if ( SERVICE_ANNOUNCEMENT_LINE_PATTERN . matcher ( headerLines [ 0 ] ) . matches ( ) ) { type = SsdpResponse . Type . PRESENCE_ANNOUNCEMENT ; } // If type was not found, this is not a valid SSDP message. get out of here if ( type == null ) { return null ; } // Let's parse our headers. for ( int i = 1 ; i < headerLines . length ; i ++ ) { String line = headerLines [ i ] ; Matcher matcher = HEADER_PATTERN . matcher ( line ) ; if ( matcher . matches ( ) ) { headers . put ( matcher . group ( 1 ) . toUpperCase ( ) . trim ( ) , matcher . group ( 2 ) . trim ( ) ) ; } } // Determine expiry depending on the presence of cache-control or expires headers. long expiry = parseCacheHeader ( headers ) ; // Let's see if we have a body. If we do, let's copy the byte array and put it into the response for the user to get. int endOfBody = packet . getLength ( ) ; if ( endOfBody > endOfHeaders + 4 ) { body = Arrays . copyOfRange ( data , endOfHeaders + 4 , endOfBody ) ; } return new SsdpResponse ( type , headers , body , expiry , packet . getAddress ( ) ) ; }
Parse incoming Datagram into SsdpResponse .