org.fourthline.cling.model.message.UpnpResponse Java Examples

The following examples show how to use org.fourthline.cling.model.message.UpnpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: TVRemoteIME   Author: kingthy   File: ProtocolFactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public ReceivingAsync createReceivingAsync(IncomingDatagramMessage message) throws ProtocolCreationException {
    log.fine("Creating protocol for incoming asynchronous: " + message);

    if (message.getOperation() instanceof UpnpRequest) {
        IncomingDatagramMessage<UpnpRequest> incomingRequest = message;

        switch (incomingRequest.getOperation().getMethod()) {
            case NOTIFY:
                return isByeBye(incomingRequest) || isSupportedServiceAdvertisement(incomingRequest)
                    ? createReceivingNotification(incomingRequest) : null;
            case MSEARCH:
                return createReceivingSearch(incomingRequest);
        }

    } else if (message.getOperation() instanceof UpnpResponse) {
        IncomingDatagramMessage<UpnpResponse> incomingResponse = message;

        return isSupportedServiceAdvertisement(incomingResponse)
            ? createReceivingSearchResponse(incomingResponse) : null;
    }

    throw new ProtocolCreationException("Protocol for incoming datagram message not found: " + message);
}
 
Example #2
Source Project: DroidDLNA   Author: offbye   File: DatagramProcessorImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected IncomingDatagramMessage readResponseMessage(InetAddress receivedOnAddress,
                                                      DatagramPacket datagram,
                                                      ByteArrayInputStream is,
                                                      int statusCode,
                                                      String statusMessage,
                                                      String httpProtocol) throws Exception {

    // Headers
    UpnpHeaders headers = new UpnpHeaders(is);

    // Assemble the message
    IncomingDatagramMessage responseMessage;
    UpnpResponse upnpResponse = new UpnpResponse(statusCode, statusMessage);
    upnpResponse.setHttpMinorVersion(httpProtocol.toUpperCase(Locale.ENGLISH).equals("HTTP/1.1") ? 1 : 0);
    responseMessage = new IncomingDatagramMessage(upnpResponse, datagram.getAddress(), datagram.getPort(), receivedOnAddress);

    responseMessage.setHeaders(headers);

    return responseMessage;
}
 
Example #3
Source Project: HPlayer   Author: hezhubo   File: UpnpControlSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置音量
 */
public void setDeviceVolume(int volume) {
    ActionCallback setVolume = new SetVolume(renderingControlService, volume) {

        @Override
        public void failure(ActionInvocation arg0, UpnpResponse arg1, String arg2) {
            onFailureCallBack(SET_VOLUME, arg2);
        }

        @Override
        public void success(ActionInvocation invocation) {
            onSuccessCallBack(SET_VOLUME);
        }
    };
    mUpnpService.getControlPoint().execute(setVolume);
}
 
Example #4
Source Project: HPlayer   Author: hezhubo   File: UpnpControlSet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 设置静音
 */
public void setDeviceMute(boolean mute) {
    ActionCallback setMute = new SetMute(renderingControlService, mute) {

        @Override
        public void failure(ActionInvocation arg0, UpnpResponse arg1, String arg2) {
            onFailureCallBack(SET_MUTE, arg2);
        }

        @Override
        public void success(ActionInvocation invocation) {
            onSuccessCallBack(SET_MUTE);
        }
    };
    mUpnpService.getControlPoint().execute(setMute);
}
 
Example #5
Source Project: Popeens-DSub   Author: popeen   File: DLNAController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void shutdown() {
	try {
		controlPoint.execute(new Stop(getTransportService()) {
			@Override
			public void failure(ActionInvocation invocation, org.fourthline.cling.model.message.UpnpResponse operation, String defaultMessage) {
				Log.w(TAG, "Stop failed: " + defaultMessage);
			}
		});
	} catch(Exception e) {
		Log.w(TAG, "Failed to shutdown", e);
	}

	if(callback != null) {
		callback.end();
		callback = null;
	}

	if(proxy != null) {
		proxy.stop();
		proxy = null;
	}

	running = false;
}
 
Example #6
Source Project: Popeens-DSub   Author: popeen   File: DLNAController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void stop() {
	try {
		controlPoint.execute(new Pause(getTransportService()) {
			@Override
			public void success(ActionInvocation invocation) {
				int secondsSinceLastUpdate = (int) ((System.currentTimeMillis() - lastUpdate.get()) / 1000L);
				currentPosition += secondsSinceLastUpdate;

				downloadService.setPlayerState(PlayerState.PAUSED);
			}

			@Override
			public void failure(ActionInvocation actionInvocation, UpnpResponse upnpResponse, String msg) {
				Log.w(TAG, "Failed to pause playing: " + msg);
			}
		});
	} catch(Exception e) {
		Log.w(TAG, "Failed to stop", e);
	}
}
 
Example #7
Source Project: Popeens-DSub   Author: popeen   File: DLNAController.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void start() {
	if(error) {
		Log.w(TAG, "Attempting to restart song");
		startSong(downloadService.getCurrentPlaying(), true, 0);
		return;
	}

	try {
		controlPoint.execute(new Play(getTransportService()) {
			@Override
			public void success(ActionInvocation invocation) {
				lastUpdate.set(System.currentTimeMillis());
				downloadService.setPlayerState(PlayerState.STARTED);
			}

			@Override
			public void failure(ActionInvocation actionInvocation, UpnpResponse upnpResponse, String msg) {
				Log.w(TAG, "Failed to start playing: " + msg);
				failedLoad();
			}
		});
	} catch(Exception e) {
		Log.w(TAG, "Failed to start", e);
	}
}
 
Example #8
Source Project: BeyondUPnP   Author: kevinshine   File: PlaybackCommand.java    License: Apache License 2.0 6 votes vote down vote up
public static void pause() {
    Device device = SystemManager.getInstance().getSelectedDevice();
    //Check selected device
    if (device == null) return;

    Service avtService = device.findService(SystemManager.AV_TRANSPORT_SERVICE);
    if (avtService != null) {
        ControlPoint cp = SystemManager.getInstance().getControlPoint();
        cp.execute(new Pause(avtService) {
            @Override
            public void success(ActionInvocation invocation) {
                Log.i(TAG, "Pause success.");
            }

            @Override
            public void failure(ActionInvocation arg0, UpnpResponse arg1, String arg2) {
                Log.e(TAG, "Pause failed");
            }
        });
    }
}
 
Example #9
Source Project: BeyondUPnP   Author: kevinshine   File: PlaybackCommand.java    License: Apache License 2.0 6 votes vote down vote up
public static void stop() {
    Device device = SystemManager.getInstance().getSelectedDevice();
    //Check selected device
    if (device == null) return;

    Service avtService = device.findService(SystemManager.AV_TRANSPORT_SERVICE);
    if (avtService != null) {
        ControlPoint cp = SystemManager.getInstance().getControlPoint();
        cp.execute(new Stop(avtService) {
            @Override
            public void success(ActionInvocation invocation) {
                Log.i(TAG, "Stop success.");
            }

            @Override
            public void failure(ActionInvocation arg0, UpnpResponse arg1, String arg2) {
                Log.e(TAG, "Stop failed");
            }
        });
    }
}
 
Example #10
Source Project: DroidDLNA   Author: offbye   File: ProtocolFactoryImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
public ReceivingAsync createReceivingAsync(IncomingDatagramMessage message) throws ProtocolCreationException {
    log.fine("Creating protocol for incoming asynchronous: " + message);

    if (message.getOperation() instanceof UpnpRequest) {
        IncomingDatagramMessage<UpnpRequest> incomingRequest = message;

        switch (incomingRequest.getOperation().getMethod()) {
            case NOTIFY:
                return isByeBye(incomingRequest) || isSupportedServiceAdvertisement(incomingRequest)
                    ? createReceivingNotification(incomingRequest) : null;
            case MSEARCH:
                return createReceivingSearch(incomingRequest);
        }

    } else if (message.getOperation() instanceof UpnpResponse) {
        IncomingDatagramMessage<UpnpResponse> incomingResponse = message;

        return isSupportedServiceAdvertisement(incomingResponse)
            ? createReceivingSearchResponse(incomingResponse) : null;
    }

    throw new ProtocolCreationException("Protocol for incoming datagram message not found: " + message);
}
 
Example #11
Source Project: DroidDLNA   Author: offbye   File: ReceivingRetrieval.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected StreamResponseMessage executeSync() throws RouterException {

        if (!getInputMessage().hasHostHeader()) {
            log.fine("Ignoring message, missing HOST header: " + getInputMessage());
            return new StreamResponseMessage(new UpnpResponse(UpnpResponse.Status.PRECONDITION_FAILED));
        }

        URI requestedURI = getInputMessage().getOperation().getURI();

        Resource foundResource = getUpnpService().getRegistry().getResource(requestedURI);

        if (foundResource == null) {
            foundResource = onResourceNotFound(requestedURI);
            if (foundResource == null) {
                log.fine("No local resource found: " + getInputMessage());
                return null;
            }
        }

        return createResponse(requestedURI, foundResource);
    }
 
Example #12
Source Project: DroidDLNA   Author: offbye   File: ReceivingSubscribe.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected OutgoingSubscribeResponseMessage processRenewal(LocalService service,
                                                          IncomingSubscribeRequestMessage requestMessage) {

    subscription = getUpnpService().getRegistry().getLocalSubscription(requestMessage.getSubscriptionId());

    // Error conditions UDA 1.0 section 4.1.1 and 4.1.2
    if (subscription == null) {
        log.fine("Invalid subscription ID for renewal request: " + getInputMessage());
        return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.PRECONDITION_FAILED);
    }

    log.fine("Renewing subscription: " + subscription);
    subscription.setSubscriptionDuration(requestMessage.getRequestedTimeoutSeconds());
    if (getUpnpService().getRegistry().updateLocalSubscription(subscription)) {
        return new OutgoingSubscribeResponseMessage(subscription);
    } else {
        log.fine("Subscription went away before it could be renewed: " + getInputMessage());
        return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.PRECONDITION_FAILED);
    }
}
 
Example #13
Source Project: DroidDLNA   Author: offbye   File: OutgoingSearchResponse.java    License: GNU General Public License v3.0 6 votes vote down vote up
public OutgoingSearchResponse(IncomingDatagramMessage request,
                              Location location,
                              LocalDevice device) {

    super(new UpnpResponse(UpnpResponse.Status.OK), request.getSourceAddress(), request.getSourcePort());

    getHeaders().add(UpnpHeader.Type.MAX_AGE, new MaxAgeHeader(device.getIdentity().getMaxAgeSeconds()));
    getHeaders().add(UpnpHeader.Type.LOCATION, new LocationHeader(location.getURL()));
    getHeaders().add(UpnpHeader.Type.SERVER, new ServerHeader());
    getHeaders().add(UpnpHeader.Type.EXT, new EXTHeader());

    if (location.getNetworkAddress().getHardwareAddress() != null) {
        getHeaders().add(
                UpnpHeader.Type.EXT_IFACE_MAC,
                 new InterfaceMacHeader(location.getNetworkAddress().getHardwareAddress())
        );
    }
}
 
Example #14
Source Project: DroidDLNA   Author: offbye   File: ActionCallback.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected String createDefaultFailureMessage(ActionInvocation invocation, UpnpResponse operation) {
    String message = "Error: ";
    final ActionException exception = invocation.getFailure();
    if (exception != null) {
        message = message + exception.getMessage();
    }
    if (operation != null) {
        message = message + " (HTTP response was: " + operation.getResponseDetails() + ")";
    }
    return message;
}
 
Example #15
Source Project: TVRemoteIME   Author: kingthy   File: ReceivingSubscribe.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected OutgoingSubscribeResponseMessage executeSync() throws RouterException {

        ServiceEventSubscriptionResource resource =
                getUpnpService().getRegistry().getResource(
                        ServiceEventSubscriptionResource.class,
                        getInputMessage().getUri()
        );

        if (resource == null) {
            log.fine("No local resource found: " + getInputMessage());
            return null;
        }

        log.fine("Found local event subscription matching relative request URI: " + getInputMessage().getUri());

        IncomingSubscribeRequestMessage requestMessage =
                new IncomingSubscribeRequestMessage(getInputMessage(), resource.getModel());

        // Error conditions UDA 1.0 section 4.1.1 and 4.1.2
        if (requestMessage.getSubscriptionId() != null &&
                (requestMessage.hasNotificationHeader() || requestMessage.getCallbackURLs() != null)) {
            log.fine("Subscription ID and NT or Callback in subscribe request: " + getInputMessage());
            return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.BAD_REQUEST);
        }

        if (requestMessage.getSubscriptionId() != null) {
            return processRenewal(resource.getModel(), requestMessage);
        } else if (requestMessage.hasNotificationHeader() && requestMessage.getCallbackURLs() != null){
            return processNewSubscription(resource.getModel(), requestMessage);
        } else {
            log.fine("No subscription ID, no NT or Callback, neither subscription or renewal: " + getInputMessage());
            return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.PRECONDITION_FAILED);
        }

    }
 
Example #16
Source Project: TVRemoteIME   Author: kingthy   File: OutgoingActionResponseMessage.java    License: GNU General Public License v2.0 5 votes vote down vote up
public OutgoingActionResponseMessage(UpnpResponse.Status status, Action action) {
    super(new UpnpResponse(status));

    if (action != null) {
        if (action instanceof QueryStateVariableAction) {
            this.actionNamespace = Constants.NS_UPNP_CONTROL_10;
        } else {
            this.actionNamespace = action.getService().getServiceType().toString();
        }
    }

    addHeaders();
}
 
Example #17
Source Project: DroidDLNA   Author: offbye   File: GetTransportInfoCallback.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void failure(ActionInvocation paramActionInvocation, UpnpResponse paramUpnpResponse,
        String paramString) {
    if (this.type == 1) {
        this.handler.sendEmptyMessage(DMCControlMessage.PLAYIMAGEFAILED);
    } else if (this.type == 2) {
        this.handler.sendEmptyMessage(DMCControlMessage.PLAYAUDIOFAILED);
    } else if (this.type == 3) {
        this.handler.sendEmptyMessage(DMCControlMessage.PLAYVIDEOFAILED);
    }
}
 
Example #18
Source Project: TVRemoteIME   Author: kingthy   File: OutgoingSubscribeResponseMessage.java    License: GNU General Public License v2.0 5 votes vote down vote up
public OutgoingSubscribeResponseMessage(LocalGENASubscription subscription) {
    super(new UpnpResponse(UpnpResponse.Status.OK));

    getHeaders().add(UpnpHeader.Type.SERVER,new ServerHeader());
    getHeaders().add(UpnpHeader.Type.SID, new SubscriptionIdHeader(subscription.getSubscriptionId()));
    getHeaders().add(UpnpHeader.Type.TIMEOUT, new TimeoutHeader(subscription.getActualDurationSeconds()));
}
 
Example #19
Source Project: TVRemoteIME   Author: kingthy   File: StreamClientImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected ResponseHandler<StreamResponseMessage> createResponseHandler() {
    return new ResponseHandler<StreamResponseMessage>() {
        public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException {

            StatusLine statusLine = httpResponse.getStatusLine();
            if (log.isLoggable(Level.FINE))
                log.fine("Received HTTP response: " + statusLine);

            // Status
            UpnpResponse responseOperation =
                new UpnpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase());

            // Message
            StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation);

            // Headers
            responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse)));

            // Body
            HttpEntity entity = httpResponse.getEntity();
            if (entity == null || entity.getContentLength() == 0) return responseMessage;

            if (responseMessage.isContentTypeMissingOrText()) {
                if (log.isLoggable(Level.FINE))
                    log.fine("HTTP response message contains text entity");
                responseMessage.setBody(UpnpMessage.BodyType.STRING, EntityUtils.toString(entity));
            } else {
                if (log.isLoggable(Level.FINE))
                    log.fine("HTTP response message contains binary entity");
                responseMessage.setBody(UpnpMessage.BodyType.BYTES, EntityUtils.toByteArray(entity));
            }

            return responseMessage;
        }
    };
}
 
Example #20
Source Project: TVRemoteIME   Author: kingthy   File: SubscriptionCallback.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param responseStatus The (HTTP) response or <code>null</code> if there was no response.
 * @param exception The exception or <code>null</code> if there was no exception.
 * @return A human-friendly error message.
 */
public static String createDefaultFailureMessage(UpnpResponse responseStatus, Exception exception) {
    String message = "Subscription failed: ";
    if (responseStatus != null) {
        message = message + " HTTP response was: " + responseStatus.getResponseDetails();
    } else if (exception != null) {
        message = message + " Exception occured: " + exception;
    } else {
        message = message + " No response received.";
    }
    return message;
}
 
Example #21
Source Project: DroidDLNA   Author: offbye   File: SubscriptionCallback.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param responseStatus The (HTTP) response or <code>null</code> if there was no response.
 * @param exception The exception or <code>null</code> if there was no exception.
 * @return A human-friendly error message.
 */
public static String createDefaultFailureMessage(UpnpResponse responseStatus, Exception exception) {
    String message = "Subscription failed: ";
    if (responseStatus != null) {
        message = message + " HTTP response was: " + responseStatus.getResponseDetails();
    } else if (exception != null) {
        message = message + " Exception occured: " + exception;
    } else {
        message = message + " No response received.";
    }
    return message;
}
 
Example #22
Source Project: TVRemoteIME   Author: kingthy   File: ActionCallback.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected String createDefaultFailureMessage(ActionInvocation invocation, UpnpResponse operation) {
    String message = "Error: ";
    final ActionException exception = invocation.getFailure();
    if (exception != null) {
        message = message + exception.getMessage();
    }
    if (operation != null) {
        message = message + " (HTTP response was: " + operation.getResponseDetails() + ")";
    }
    return message;
}
 
Example #23
Source Project: BeyondUPnP   Author: kevinshine   File: ContentContainerActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void loadContent() {
    SystemManager systemManager = SystemManager.getInstance();
    Device device = null;
    try {
        device = systemManager.getRegistry().getDevice(new UDN(mIdentifierString), false);
    } catch (NullPointerException e) {
        Log.e(TAG, "Get device error.");
    }

    if (device != null) {
        //Get cds to browse children directories.
        Service contentDeviceService = device.findService(SystemManager.CONTENT_DIRECTORY_SERVICE);
        //Execute Browse action and init list view
        systemManager.getControlPoint().execute(new Browse(contentDeviceService, mObjectId, BrowseFlag.DIRECT_CHILDREN, "*", 0,
                null, new SortCriterion(true, "dc:title")) {
            @Override
            public void received(ActionInvocation actionInvocation, DIDLContent didl) {
                Message msg = Message.obtain(handler,ADD_OBJECTS,didl);
                msg.sendToTarget();
            }

            @Override
            public void updateStatus(Status status) {
            }

            @Override
            public void failure(ActionInvocation invocation, UpnpResponse operation, String defaultMsg) {
            }
        });
    }
}
 
Example #24
Source Project: DroidDLNA   Author: offbye   File: ReceivingSubscribe.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected OutgoingSubscribeResponseMessage executeSync() throws RouterException {

        ServiceEventSubscriptionResource resource =
                getUpnpService().getRegistry().getResource(
                        ServiceEventSubscriptionResource.class,
                        getInputMessage().getUri()
        );

        if (resource == null) {
            log.fine("No local resource found: " + getInputMessage());
            return null;
        }

        log.fine("Found local event subscription matching relative request URI: " + getInputMessage().getUri());

        IncomingSubscribeRequestMessage requestMessage =
                new IncomingSubscribeRequestMessage(getInputMessage(), resource.getModel());

        // Error conditions UDA 1.0 section 4.1.1 and 4.1.2
        if (requestMessage.getSubscriptionId() != null &&
                (requestMessage.hasNotificationHeader() || requestMessage.getCallbackURLs() != null)) {
            log.fine("Subscription ID and NT or Callback in subscribe request: " + getInputMessage());
            return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.BAD_REQUEST);
        }

        if (requestMessage.getSubscriptionId() != null) {
            return processRenewal(resource.getModel(), requestMessage);
        } else if (requestMessage.hasNotificationHeader() && requestMessage.getCallbackURLs() != null){
            return processNewSubscription(resource.getModel(), requestMessage);
        } else {
            log.fine("No subscription ID, no NT or Callback, neither subscription or renewal: " + getInputMessage());
            return new OutgoingSubscribeResponseMessage(UpnpResponse.Status.PRECONDITION_FAILED);
        }

    }
 
Example #25
Source Project: DroidDLNA   Author: offbye   File: OutgoingActionResponseMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public OutgoingActionResponseMessage(UpnpResponse.Status status, Action action) {
    super(new UpnpResponse(status));

    if (action != null) {
        if (action instanceof QueryStateVariableAction) {
            this.actionNamespace = Constants.NS_UPNP_CONTROL_10;
        } else {
            this.actionNamespace = action.getService().getServiceType().toString();
        }
    }

    addHeaders();
}
 
Example #26
Source Project: DroidDLNA   Author: offbye   File: GetVolumeCallback.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void failure(ActionInvocation paramActionInvocation,
		UpnpResponse paramUpnpResponse, String paramString) {
	if (this.type == 1) {
		this.handler.sendEmptyMessage(DMCControlMessage.PLAYIMAGEFAILED);
	} else if (this.type == 2) {
		this.handler.sendEmptyMessage(DMCControlMessage.PLAYAUDIOFAILED);
	} else if (this.type == 3) {
		this.handler.sendEmptyMessage(DMCControlMessage.PLAYVIDEOFAILED);
	}
}
 
Example #27
Source Project: DroidDLNA   Author: offbye   File: OutgoingSubscribeResponseMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public OutgoingSubscribeResponseMessage(LocalGENASubscription subscription) {
    super(new UpnpResponse(UpnpResponse.Status.OK));

    getHeaders().add(UpnpHeader.Type.SERVER,new ServerHeader());
    getHeaders().add(UpnpHeader.Type.SID, new SubscriptionIdHeader(subscription.getSubscriptionId()));
    getHeaders().add(UpnpHeader.Type.TIMEOUT, new TimeoutHeader(subscription.getActualDurationSeconds()));
}
 
Example #28
Source Project: DroidDLNA   Author: offbye   File: UpnpStream.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Selects a UPnP protocol, runs it within the calling thread, returns the response.
 * <p>
 * This method will return <code>null</code> if the UPnP protocol returned <code>null</code>.
 * The HTTP response in this case is always <em>404 NOT FOUND</em>. Any other (HTTP) error
 * condition will be encapsulated in the returned response message and has to be
 * passed to the HTTP client as it is.
 * </p>
 * @param requestMsg The TCP (HTTP) stream request message.
 * @return The TCP (HTTP) stream response message, or <code>null</code> if a 404 should be send to the client.
 */
public StreamResponseMessage process(StreamRequestMessage requestMsg) {
    log.fine("Processing stream request message: " + requestMsg);

    try {
        // Try to get a protocol implementation that matches the request message
        syncProtocol = getProtocolFactory().createReceivingSync(requestMsg);
    } catch (ProtocolCreationException ex) {
        log.warning("Processing stream request failed - " + Exceptions.unwrap(ex).toString());
        return new StreamResponseMessage(UpnpResponse.Status.NOT_IMPLEMENTED);
    }

    // Run it
    log.fine("Running protocol for synchronous message processing: " + syncProtocol);
    syncProtocol.run();

    // ... then grab the response
    StreamResponseMessage responseMsg = syncProtocol.getOutputMessage();

    if (responseMsg == null) {
        // That's ok, the caller is supposed to handle this properly (e.g. convert it to HTTP 404)
        log.finer("Protocol did not return any response message");
        return null;
    }
    log.finer("Protocol returned response: " + responseMsg);
    return responseMsg;
}
 
Example #29
Source Project: TVRemoteIME   Author: kingthy   File: ProtocolFactoryImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected ReceivingAsync createReceivingSearchResponse(IncomingDatagramMessage<UpnpResponse> incomingResponse) {
    return new ReceivingSearchResponse(getUpnpService(), incomingResponse);
}
 
Example #30
Source Project: TVRemoteIME   Author: kingthy   File: ReceivingRetrieval.java    License: GNU General Public License v2.0 4 votes vote down vote up
protected StreamResponseMessage createResponse(URI requestedURI, Resource resource) {

        StreamResponseMessage response;

        try {

            if (DeviceDescriptorResource.class.isAssignableFrom(resource.getClass())) {

                log.fine("Found local device matching relative request URI: " + requestedURI);
                LocalDevice device = (LocalDevice) resource.getModel();

                DeviceDescriptorBinder deviceDescriptorBinder =
                        getUpnpService().getConfiguration().getDeviceDescriptorBinderUDA10();
                String deviceDescriptor = deviceDescriptorBinder.generate(
                        device,
                        getRemoteClientInfo(),
                        getUpnpService().getConfiguration().getNamespace()
                );
                response = new StreamResponseMessage(
                        deviceDescriptor,
                        new ContentTypeHeader(ContentTypeHeader.DEFAULT_CONTENT_TYPE)
                );
            } else if (ServiceDescriptorResource.class.isAssignableFrom(resource.getClass())) {


                log.fine("Found local service matching relative request URI: " + requestedURI);
                LocalService service = (LocalService) resource.getModel();

                ServiceDescriptorBinder serviceDescriptorBinder =
                        getUpnpService().getConfiguration().getServiceDescriptorBinderUDA10();
                String serviceDescriptor = serviceDescriptorBinder.generate(service);
                response = new StreamResponseMessage(
                        serviceDescriptor,
                        new ContentTypeHeader(ContentTypeHeader.DEFAULT_CONTENT_TYPE)
                );

            } else if (IconResource.class.isAssignableFrom(resource.getClass())) {

                log.fine("Found local icon matching relative request URI: " + requestedURI);
                Icon icon = (Icon) resource.getModel();
                response = new StreamResponseMessage(icon.getData(), icon.getMimeType());

            } else {

                log.fine("Ignoring GET for found local resource: " + resource);
                return null;
            }

        } catch (DescriptorBindingException ex) {
            log.warning("Error generating requested device/service descriptor: " + ex.toString());
            log.log(Level.WARNING, "Exception root cause: ", Exceptions.unwrap(ex));
            response = new StreamResponseMessage(UpnpResponse.Status.INTERNAL_SERVER_ERROR);
        }
        
        response.getHeaders().add(UpnpHeader.Type.SERVER, new ServerHeader());

        return response;
    }