Java Code Examples for java.util.ArrayList#wait()

The following examples show how to use java.util.ArrayList#wait() . 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 File: AbstractXBeeDevice.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the CoAP Rx Response packet that comes in through the serial 
 * port in the given timeout.
 * 
 * @param coapResponsePackets List of packets where the received packet will be stored.
 * 
 * @return CoAP Rx Response packet received.
 * 
 * @throws XBeeException if CoAP response packet is not received or it is 
 *                       not successful or if there is any other XBee 
 *                       related error.
 * 
 * @since 1.2.1
 */
private CoAPRxResponsePacket waitForCoAPRxResponsePacket(ArrayList<CoAPRxResponsePacket> coapResponsePackets) throws XBeeException {
	synchronized (coapResponsePackets) {
		try {
			coapResponsePackets.wait(receiveTimeout);
		} catch (InterruptedException e) {}
	}
	
	if (!coapResponsePackets.isEmpty()) {
		RestFulStatusEnum responseStatus = coapResponsePackets.get(0).getStatus();
		if (responseStatus != RestFulStatusEnum.SUCCESS
				&& responseStatus != RestFulStatusEnum.CREATED
				&& responseStatus != RestFulStatusEnum.ACCEPTED
				&& responseStatus != RestFulStatusEnum.NON_AUTHORITATIVE
				&& responseStatus != RestFulStatusEnum.NO_CONTENT
				&& responseStatus != RestFulStatusEnum.RESET_CONTENT)
			throw new XBeeException("CoAP response had an unexpected status: " + responseStatus.toString());
	} else {
		throw new XBeeException("CoAP response was not received.");
	}
	return coapResponsePackets.get(0);
}
 
Example 2
Source File: RequestReplyManagerImpl.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public Object sendSyncRequest(String fromParticipantId,
                              DiscoveryEntryWithMetaInfo toDiscoveryEntry,
                              Request request,
                              SynchronizedReplyCaller synchronizedReplyCaller,
                              MessagingQos messagingQos) {

    if (!running) {
        throw new IllegalStateException("Request: " + request.getRequestReplyId() + " failed. SenderImpl ID: "
                + System.identityHashCode(this) + ": joynr is shutting down");
    }

    final ArrayList<Object> responsePayloadContainer = new ArrayList<Object>(1);
    // the synchronizedReplyCaller will call notify on the responsePayloadContainer when a message arrives
    synchronizedReplyCaller.setResponseContainer(responsePayloadContainer);

    sendRequest(fromParticipantId, toDiscoveryEntry, request, messagingQos);

    long entryTime = System.currentTimeMillis();

    // saving all calling threads so that they can be interrupted at shutdown
    outstandingRequestThreads.add(Thread.currentThread());
    synchronized (responsePayloadContainer) {
        while (running && responsePayloadContainer.isEmpty()
                && entryTime + messagingQos.getRoundTripTtl_ms() > System.currentTimeMillis()) {
            try {
                responsePayloadContainer.wait();
            } catch (InterruptedException e) {
                if (running) {
                    throw new JoynrRequestInterruptedException("Request: " + request.getRequestReplyId()
                            + " interrupted.");
                }
                throw new JoynrShutdownException("Request: " + request.getRequestReplyId()
                        + " interrupted by shutdown");
            }
        }
    }
    outstandingRequestThreads.remove(Thread.currentThread());

    if (responsePayloadContainer.isEmpty()) {
        throw new JoynrIllegalStateException("Request: " + request.getRequestReplyId()
                + " failed unexpectedly without response.");
    }

    Object response = responsePayloadContainer.get(0);
    if (response instanceof Throwable) {
        Throwable error = (Throwable) response;
        throw new JoynrCommunicationException("Request: " + request.getRequestReplyId() + " failed: "
                + error.getMessage(), error);
    }

    return response;
}
 
Example 3
Source File: AbstractXBeeDevice.java    From xbee-java with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Sends the given XBee packet synchronously and blocks until response is 
 * received or receive timeout is reached.
 * 
 * <p>The receive timeout is configured using the {@code setReceiveTimeout}
 * method and can be consulted with {@code getReceiveTimeout} method.</p>
 * 
 * <p>Use {@link #sendXBeePacketAsync(XBeePacket)} for non-blocking 
 * operations.</p>
 * 
 * @param packet XBee packet to be sent.
 * @return An {@code XBeePacket} containing the response of the sent packet 
 *         or {@code null} if there is no response.
 * 
 * @throws InterfaceNotOpenException if this device connection is not open.
 * @throws InvalidOperatingModeException if the operating mode is different 
 *                                       than {@link OperatingMode#API} and 
 *                                       {@link OperatingMode#API_ESCAPE}.
 * @throws IOException if an I/O error occurs while sending the XBee packet.
 * @throws NullPointerException if {@code packet == null}.
 * @throws TimeoutException if the configured time expires while waiting for
 *                          the packet reply.
 * 
 * @see #sendXBeePacket(XBeePacket)
 * @see #sendXBeePacket(XBeePacket, IPacketReceiveListener)
 * @see #sendXBeePacketAsync(XBeePacket)
 * @see XBeeDevice#setReceiveTimeout(int)
 * @see XBeeDevice#getReceiveTimeout()
 * @see com.digi.xbee.api.packet.XBeePacket
 */
protected XBeePacket sendXBeePacket(final XBeePacket packet) 
		throws InvalidOperatingModeException, TimeoutException, IOException {
	// Check if the packet to send is null.
	if (packet == null)
		throw new NullPointerException("XBee packet cannot be null.");
	// Check connection.
	if (!connectionInterface.isOpen())
		throw new InterfaceNotOpenException();
	
	OperatingMode operatingMode = getOperatingMode();
	switch (operatingMode) {
	case AT:
	case UNKNOWN:
	default:
		throw new InvalidOperatingModeException(operatingMode);
	case API:
	case API_ESCAPE:
		// Build response container.
		ArrayList<XBeePacket> responseList = new ArrayList<XBeePacket>();
		
		// If the packet does not need frame ID, send it async. and return null.
		if (packet instanceof XBeeAPIPacket) {
			if (!((XBeeAPIPacket)packet).needsAPIFrameID()) {
				sendXBeePacketAsync(packet);
				return null;
			}
		} else {
			sendXBeePacketAsync(packet);
			return null;
		}
		
		// Add the required frame ID to the packet if necessary.
		insertFrameID(packet);
		
		// Generate a packet received listener for the packet to be sent.
		IPacketReceiveListener packetReceiveListener = createPacketReceivedListener(packet, responseList);
		
		// Add the packet listener to the data reader.
		addPacketListener(packetReceiveListener);
		
		// Write the packet data.
		writePacket(packet);
		try {
			// Wait for response or timeout.
			synchronized (responseList) {
				try {
					responseList.wait(receiveTimeout);
				} catch (InterruptedException e) {}
			}
			// After the wait check if we received any response, if not throw timeout exception.
			if (responseList.size() < 1)
				throw new TimeoutException();
			// Return the received packet.
			return responseList.get(0);
		} finally {
			// Always remove the packet listener from the list.
			removePacketListener(packetReceiveListener);
		}
	}
}