下面列出了怎么用java.net.UnknownServiceException的API类实例代码及写法,或者点击链接到github查看源代码。
public InputStream getInputStream() throws IOException, UnknownServiceException {
connect();
if (iStream == null) {
try {
if (fo.isFolder()) {
iStream = new FIS(fo);
} else {
iStream = fo.getInputStream();
}
} catch (FileNotFoundException e) {
ExternalUtil.exception(e);
throw e;
}
}
return iStream;
}
/**
* Sets the supported RTSP method by the server
*
* @throws IOException
*/
protected void setSupportedMethods() throws IOException {
options();
if (isSuccessfullResponse()) {
String pub = responses.findValue("Public");
if (pub != null) {
StringTokenizer st = new StringTokenizer(pub, ",");
if (st.countTokens() > 0) {
List<String> l = new ArrayList<String>();
l.add(OPTIONS);
String s;
while (st.hasMoreTokens()) {
s = st.nextToken().trim();
if (Arrays.binarySearch(getPlatformPossibleMethods(), s) >= 0) {
Debug.println(" ADD SRV METHOD " + s);
l.add(s);
}
}
this.supportedMethods = l.toArray(new String[l.size()]);
return;
}
}
}
throw new UnknownServiceException("Cannot retreive server supported rtsp methods.");
}
/**
* @throws NoRouteToHostException if the process is terminated.
* @throws UnknownServiceException if the process has no known monitor address.
*/
@Nonnull
public QApiConnection getConnection() throws IOException {
if (monitor == null)
throw new UnknownServiceException("No monitor address known.");
try {
// If this succeeds, then we have exited.
int exitValue = process.exitValue();
connection = null;
throw new NoRouteToHostException("Process terminated with exit code " + exitValue);
} catch (IllegalThreadStateException e) {
}
synchronized (lock) {
if (connection != null)
return connection;
connection = new QApiConnection(monitor);
return connection;
}
}
/**
* Configures the supplied {@link SSLSocket} to connect to the specified host using an appropriate
* {@link ConnectionSpec}. Returns the chosen {@link ConnectionSpec}, never {@code null}.
*
* @throws IOException if the socket does not support any of the TLS modes available
*/
public ConnectionSpec configureSecureSocket(SSLSocket sslSocket) throws IOException {
ConnectionSpec tlsConfiguration = null;
for (int i = nextModeIndex, size = connectionSpecs.size(); i < size; i++) {
ConnectionSpec connectionSpec = connectionSpecs.get(i);
if (connectionSpec.isCompatible(sslSocket)) {
tlsConfiguration = connectionSpec;
nextModeIndex = i + 1;
break;
}
}
if (tlsConfiguration == null) {
// This may be the first time a connection has been attempted and the socket does not support
// any the required protocols, or it may be a retry (but this socket supports fewer
// protocols than was suggested by a prior socket).
throw new UnknownServiceException(
"Unable to find acceptable protocols. isFallback=" + isFallback
+ ", modes=" + connectionSpecs
+ ", supported protocols=" + Arrays.toString(sslSocket.getEnabledProtocols()));
}
isFallbackPossible = isFallbackPossible(sslSocket);
Internal.instance.apply(tlsConfiguration, sslSocket, isFallback);
return tlsConfiguration;
}
public @Override InputStream getInputStream() throws IOException, UnknownServiceException {
connect();
if (iStream == null) {
if (fo.isFolder()) {
throw new FileNotFoundException("Can not read from a folder.");
} else {
iStream = fo.getInputStream();
}
}
return iStream;
}
public void connect() throws IOException {
if (f == null) {
f = NbinstURLMapper.decodeURL(url);
if (f == null) {
throw new FileNotFoundException("Cannot find: " + url); // NOI18N
}
}
if (!f.isFile()) {
throw new UnknownServiceException();
}
}
public OutputStream getOutputStream() throws IOException, UnknownServiceException {
connect();
if (fo.isFolder()) {
throw new UnknownServiceException();
}
if (oStream == null) {
FileLock flock = fo.lock();
oStream = new LockOS(fo.getOutputStream(flock), flock);
}
return oStream;
}
public @Override InputStream getInputStream() throws IOException, UnknownServiceException {
connect();
if (iStream == null) {
if (fo.isFolder()) {
throw new FileNotFoundException("Can not read from a folder.");
} else {
iStream = fo.getInputStream();
}
}
return iStream;
}
protected WebResponse submitRequest( String event, WebRequest request ) throws IOException, SAXException {
try {
return super.submitRequest( event, request );
} catch (UnknownServiceException e) {
throw new UnsupportedActionException( "HttpUnit does not support " + request.getURL().getProtocol() + " URLs in form submissions" );
}
}
private void onMediathekLoadError(Throwable e) {
adapter.setLoading(false);
swipeRefreshLayout.setRefreshing(false);
Timber.e(e);
if (e instanceof SSLHandshakeException || e instanceof UnknownServiceException) {
showError(R.string.error_mediathek_ssl_error);
} else {
showError(R.string.error_mediathek_info_not_available);
}
}
@Test
public void connectServiceError() throws Exception {
Mockito.doThrow(new UnknownServiceException()).when(mockSocket).connect(Mockito.any());
final TcpCollector.ConnectDatum result;
try (TcpCollector tcpCollector = new TcpCollector(dstAddress, GROUP)) {
result = tcpCollector.tryConnect(mockSocket);
}
assertThat(result.getResult(), equalTo(TcpCollector.ConnectResult.UNKNOWN_SERVICE));
Mockito.verify(mockSocket, times(1)).connect(Mockito.eq(dstAddress));
Mockito.verifyNoMoreInteractions(mockSocket);
}
/**
* Configures the supplied {@link SSLSocket} to connect to the specified host using an appropriate
* {@link ConnectionSpec}. Returns the chosen {@link ConnectionSpec}, never {@code null}.
*
* @throws IOException if the socket does not support any of the TLS modes available
*/
public ConnectionSpec configureSecureSocket(SSLSocket sslSocket) throws IOException {
ConnectionSpec tlsConfiguration = null;
for (int i = nextModeIndex, size = connectionSpecs.size(); i < size; i++) {
ConnectionSpec connectionSpec = connectionSpecs.get(i);
if (connectionSpec.isCompatible(sslSocket)) {
tlsConfiguration = connectionSpec;
nextModeIndex = i + 1;
break;
}
}
if (tlsConfiguration == null) {
// This may be the first time a connection has been attempted and the socket does not support
// any the required protocols, or it may be a retry (but this socket supports fewer
// protocols than was suggested by a prior socket).
throw new UnknownServiceException(
"Unable to find acceptable protocols. isFallback=" + isFallback
+ ", modes=" + connectionSpecs
+ ", supported protocols=" + Arrays.toString(sslSocket.getEnabledProtocols()));
}
isFallbackPossible = isFallbackPossible(sslSocket);
Internal.instance.apply(tlsConfiguration, sslSocket, isFallback);
return tlsConfiguration;
}
/**
* From http://vaibhavblogs.org/2012/12/common-java-networking-exceptions/
*/
public static boolean isNetworkException(Throwable e) {
return e instanceof SocketException || e instanceof ClosedChannelException ||
e instanceof InterruptedIOException || e instanceof ProtocolException ||
e instanceof SSLException || e instanceof UnknownHostException ||
e instanceof UnknownServiceException;
}
public void connect(
int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) {
if (protocol != null) throw new IllegalStateException("already connected");
RouteException routeException = null;
List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);
if (route.address().sslSocketFactory() == null) {
if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication not enabled for client"));
}
String host = route.address().url().host();
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication to " + host + " not permitted by network security policy"));
}
}
while (true) {
try {
if (route.requiresTunnel()) {
connectTunnel(connectTimeout, readTimeout, writeTimeout);
} else {
connectSocket(connectTimeout, readTimeout);
}
establishProtocol(connectionSpecSelector);
break;
} catch (IOException e) {
closeQuietly(socket);
closeQuietly(rawSocket);
socket = null;
rawSocket = null;
source = null;
sink = null;
handshake = null;
protocol = null;
http2Connection = null;
if (routeException == null) {
routeException = new RouteException(e);
} else {
routeException.addConnectException(e);
}
if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
throw routeException;
}
}
}
if (http2Connection != null) {
synchronized (connectionPool) {
allocationLimit = http2Connection.maxConcurrentStreams();
}
}
}
public void connect(
int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) {
if (protocol != null) throw new IllegalStateException("already connected");
RouteException routeException = null;
List<ConnectionSpec> connectionSpecs = route.address().connectionSpecs();
ConnectionSpecSelector connectionSpecSelector = new ConnectionSpecSelector(connectionSpecs);
if (route.address().sslSocketFactory() == null) {
if (!connectionSpecs.contains(ConnectionSpec.CLEARTEXT)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication not enabled for client"));
}
String host = route.address().url().host();
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication to " + host + " not permitted by network security policy"));
}
}
while (true) {
try {
if (route.requiresTunnel()) {
connectTunnel(connectTimeout, readTimeout, writeTimeout);
} else {
connectSocket(connectTimeout, readTimeout);
}
establishProtocol(connectionSpecSelector);
break;
} catch (IOException e) {
closeQuietly(socket);
closeQuietly(rawSocket);
socket = null;
rawSocket = null;
source = null;
sink = null;
handshake = null;
protocol = null;
http2Connection = null;
if (routeException == null) {
routeException = new RouteException(e);
} else {
routeException.addConnectException(e);
}
if (!connectionRetryEnabled || !connectionSpecSelector.connectionFailed(e)) {
throw routeException;
}
}
}
if (http2Connection != null) {
synchronized (connectionPool) {
allocationLimit = http2Connection.maxConcurrentStreams();
}
}
}
/**
* Performs the RTSP SETUP request using a specific media description which
* will be used as media stream urls source. The field attributes are used
* to endow the message header with extra header field.
*
* @throws IOException
* if an IO error occurs
*/
public void setup(MediaDescriptions mediaCfg, FieldAttributes attributes) throws IOException {
// 2 mode setup default == use decribe result to setup all media or
// setup
// using setup config [] url/port!
Debug.println("RtspURLConnection.setup() desc == null?" + (descContent == null));
if (describNeeded&&descContent == null && (mediaCfg == null || getSessionID() == null)) // setup
// needs
// describe
// content
// or a
// media
// stream
// cfg
// (in
// this
// case
// session
// id
// should
// be
// valide)
throw new UnknownServiceException(" No describe method was made to perform setup method.");
//long t0=System.currentTimeMillis();
doCmd(SETUP, new Object[] { mediaCfg, attributes });
//System.err.println(" SETUP DO CMD = "+(System.currentTimeMillis() - t0));
// System.err.println(" SETUP IS OK = "+isSuccessfullResponse());
Debug.println("RtspURLConnection.setup() success = " + isSuccessfullResponse());
if (isSuccessfullResponse()) {
// t0=System.currentTimeMillis();
String sid = responses.findValue("Session");
// System.err.println(" FND VALUE= "+(System.currentTimeMillis() - t0)+" SID="+sid);
com.net.rtsp.Debug.println("RtspURLConnection.setup() sid = " + sid);
// t0=System.currentTimeMillis();
if (sid != null) {
int i = sid.indexOf(';');
if (i > 0) {
String s = sid;
setSessionID(s.substring(0, i));
try {
setSessionTimeout(Integer.parseInt(s.substring(i + 1)));
} catch (NumberFormatException e) {
Debug.println("RtspURLConnection.setup() WARNING : time value syntax err : " + s);
}
} else
setSessionID(sid);
Debug.println("---> SESSION = " + sid);
state = READY_STATE;
// System.err.println(" REST "+(System.currentTimeMillis() - t0));
return;
}
}
throw new IOException("cannot perform setup: Resource not found");
}
private void parse(byte[] b) throws IOException {
com.net.rtsp.Debug.println("Server.parse() "+new String(b));
if (!ParserTools.isRtspResponse(b)) {//request is for client processor.
// may be a method...
ByteArrayInputStream bin = new ByteArrayInputStream(b);
BufferedReader br = new BufferedReader(new InputStreamReader(bin));
List<String> lines = new ArrayList<String>();
String l;
RequestMessage h = new RequestMessage();
// header
while (((l = br.readLine()).trim()).length() > 0) {
l=l.trim();
lines.add(l);
if (lines.size() == 1) {// 1st line ==> method SO METHOD ANNOUNCE [URL] RTSP/1.0
if (!l.endsWith(RTSP_VERSION) )
throw new UnknownServiceException("Protocol version not supported :" + l);
h.setRequestLine(l);
} else {
int jj = l.indexOf(':');
if (jj > 0) {
String s1=l.substring(0, jj).trim(),
s2=l.substring(jj+1).trim();
com.net.rtsp.Debug.println("**Server.parse() "+s1+" / "+s2);
h.add(s1,s2 );
}
else
h.add(l, null);
}
}
Content cnt = null;
try{cnt = (Content) rtspURLConnection.getContent();}catch(IOException ex) {}
if (cnt != null)
h.setContent(cnt);
this.h = h;
}
/*
* String[] supportedMethod =
* ServerRequestHandlerFactory.getInstance
* ().getSupportedClientMethod(); rl=rl.substring(0,rl.indexOf('
* ')); if(supportedMethod)
*
* request.findValue("CSeq");
*/
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
@Override
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException("Writing not supported");
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
@Override
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* DataSource method to return an output stream. <p>
*
* This implementation throws the UnknownServiceException.
*/
public OutputStream getOutputStream() throws IOException {
throw new UnknownServiceException();
}
/**
* Check if the RTSP method with this method label supported by this rtsp
* url connection.
*
* @param method
* Method label
* @throws IOException
* id an IO error occurs.
*/
protected void checkMethod(String method) throws IOException {
if (!isSupportedMethod(method))
throw new UnknownServiceException("Unsupported method by server :" + method);
}