Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

In this page you can find the example usage for java.util.concurrent TimeoutException TimeoutException.

Prototype

public TimeoutException() 

Source Link

Document

Constructs a TimeoutException with no specified detail message.

Usage

From source file:io.druid.data.input.impl.prefetch.Fetcher.java

private OpenedObject<T> openObjectFromLocal() throws IOException {
    final FetchedFile<T> fetchedFile;

    if (!fetchedFiles.isEmpty()) {
        // If there are already fetched files, use them
        fetchedFile = fetchedFiles.poll();
    } else {/* w  w w .jav  a2s.  c o  m*/
        // Otherwise, wait for fetching
        try {
            fetchIfNeeded(fetchedBytes.get());
            fetchedFile = fetchedFiles.poll(fetchTimeout, TimeUnit.MILLISECONDS);
            if (fetchedFile == null) {
                // Check the latest fetch is failed
                checkFetchException(true);
                // Or throw a timeout exception
                throw new RuntimeException(new TimeoutException());
            }
        } catch (InterruptedException e) {
            throw Throwables.propagate(e);
        }
    }
    final FetchedFile<T> maybeCached = cacheIfPossible(fetchedFile);
    // trigger fetch again for subsequent next() calls
    fetchIfNeeded(fetchedBytes.get());
    return new OpenedObject<>(maybeCached);
}

From source file:org.openmuc.j62056.Connection.java

/**
 * Requests a data message from the remote device using IEC 62056-21 Mode C.
 * The data message received is parsed and a list of data sets is returned.
 * //from  w w  w.  j  a  v  a  2  s. co m
 * @return A list of data sets contained in the data message response from
 *         the remote device. The first data set will contain the
 *         "identification" of the meter as the id and empty strings for
 *         value and unit.
 * @throws IOException
 *             if any kind of error other than timeout occurs while trying
 *             to read the remote device. Note that the connection is not
 *             closed when an IOException is thrown.
 * @throws TimeoutException
 *             if no response at all (not even a single byte) was received
 *             from the meter within the timeout span.
 */
public List<DataSet> read() throws IOException, TimeoutException {

    if (serialPort == null) {
        throw new IllegalStateException("Connection is not open.");
    }

    try {
        serialPort.setSerialPortParams(300, SerialPort.DATABITS_7, SerialPort.STOPBITS_1,
                SerialPort.PARITY_EVEN);
    } catch (UnsupportedCommOperationException e) {
        throw new IOException("Unable to set the given serial comm parameters", e);
    }
    if (initMessage != null) {
        os.write(initMessage);
        os.flush();
    }

    os.write(REQUEST_MESSAGE);
    os.flush();
    int baudRateSetting;
    char protocolMode;
    int baudRate;

    boolean readSuccessful = false;
    int timeval = 0;
    int numBytesReadTotal = 0;

    while (timeout == 0 || timeval < timeout) {
        if (is.available() > 0) {

            int numBytesRead = is.read(buffer, numBytesReadTotal, INPUT_BUFFER_LENGTH - numBytesReadTotal);
            numBytesReadTotal += numBytesRead;

            if (numBytesRead > 0) {
                timeval = 0;
            }

            if (((handleEcho && numBytesReadTotal > 11) || (!handleEcho && numBytesReadTotal > 6))
                    && buffer[numBytesReadTotal - 2] == 0x0D && buffer[numBytesReadTotal - 1] == 0x0A) {
                readSuccessful = true;
                break;
            }
        }

        try {
            Thread.sleep(SLEEP_INTERVAL);
        } catch (InterruptedException e) {
        }

        timeval += SLEEP_INTERVAL;
    }

    int offset = 0;
    if (handleEcho) {
        offset = 5;
    }

    if (numBytesReadTotal == offset) {
        throw new TimeoutException();
    }

    if (!readSuccessful) {
        throw new IOException("Timeout while listening for Identification Message");
    }

    // System.out
    // .println("Got the following identification message: " +
    // getByteArrayString(buffer, numBytesReadTotal));

    int startPosition = 0;
    while (startPosition < numBytesReadTotal) {
        if (buffer[startPosition] == (byte) 0x2F) {

            if (buffer[startPosition + 1] == (byte) 0x00 | buffer[startPosition + 1] == (byte) 0x7F) {
                startPosition++;
            } else {
                break;
            }
            continue;
        }
        startPosition++;
    }

    byte[] bytes = new byte[numBytesReadTotal - startPosition];
    System.arraycopy(buffer, startPosition, bytes, 0, numBytesReadTotal - startPosition);

    /* baudrate identification http://manuals.lian98.biz/doc.en/html/u_iec62056_struct.htm
    * Protocol mode A : no baudrate change 
    * Protocol mode B : char from A to I; no acknowledgement
    * Protocol mode C : char from 0 to 9; with acknowledgement
    */
    baudRateSetting = bytes[offset + 4];
    if (baudRateSetting >= 0x41 && baudRateSetting <= 0x49) {
        protocolMode = 'B';//Mode B
        baudRate = baudRates[baudRateSetting - 0x40];//search with index (start with baudrate 600)
    } else if (baudRateSetting >= 0x30 && baudRateSetting <= 0x39) {
        protocolMode = 'C';//Mode C or E
        baudRate = baudRates[baudRateSetting - 0x30];//search with index
    } else if (baudRateSetting >= 0x32) {
        protocolMode = 'D';//Mode D no baudrate change
        baudRate = -1;
    } else {
        protocolMode = 'A';//Mode A no baudrate change
        baudRate = -1;
    }

    String identification = new String(buffer, offset + 5, numBytesReadTotal - offset - 7, charset);

    if (protocolMode == 'B' || protocolMode == 'C') {
        if (baudRate == -1) {
            throw new IOException(
                    "Syntax error in identification message received: unknown baud rate received: (hex: "
                            + Hex.encodeHexString(bytes) + ")");
        }
    }

    if (protocolMode == 'C') {
        ACKNOWLEDGE[2] = (byte) baudRateSetting;

        os.write(ACKNOWLEDGE);
        os.flush();
    }

    if (handleEcho) {
        readSuccessful = false;
        numBytesReadTotal = 0;
        while (timeout == 0 || timeval < timeout) {
            if (is.available() > 0) {
                int numBytesRead = is.read(buffer, numBytesReadTotal, ACKNOWLEDGE.length - numBytesReadTotal);
                numBytesReadTotal += numBytesRead;

                if (numBytesRead > 0) {
                    timeval = 0;
                }

                if (numBytesReadTotal == ACKNOWLEDGE.length) {
                    readSuccessful = true;
                    break;
                }
            }

            try {
                Thread.sleep(SLEEP_INTERVAL);
            } catch (InterruptedException e) {
            }

            timeval += SLEEP_INTERVAL;
        }

        // if (readSuccessful) {
        // System.out.println("Received the following echo of the acknowledge successfully : "
        // + getByteArrayString(buffer, numBytesReadTotal));
        // }
        // else {
        // System.out.println("Receiving full echo failed.");
        // }

    }

    if (baudRateChangeDelay > 0) {
        try {
            Thread.sleep(baudRateChangeDelay);
        } catch (InterruptedException e1) {
        }
    }

    try {
        serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_7, SerialPort.STOPBITS_1,
                SerialPort.PARITY_EVEN);
    } catch (UnsupportedCommOperationException e) {
        throw new IOException("Serial Port does not support " + baudRate + "bd 7E1");
    }

    readSuccessful = false;
    numBytesReadTotal = 0;
    int etxIndex = -1;

    while (timeout == 0 || timeval < timeout) {
        int available = is.available();
        if (available > 0) {
            if (buffer.length < (numBytesReadTotal + available)) {
                //grow buffer
                buffer = Arrays.copyOf(buffer, numBytesReadTotal + available);
            }
            int numBytesRead = is.read(buffer, numBytesReadTotal, available);
            numBytesReadTotal += numBytesRead;

            if (numBytesRead > 0) {
                timeval = 0;
            }

            if ((etxIndex = findEtx(buffer, numBytesRead, numBytesReadTotal)) != -1
                    || (numBytesReadTotal > 4 && buffer[numBytesReadTotal - 3] == 0x21)
                    || (numBytesReadTotal > 7 && buffer[numBytesReadTotal - 5] == 0x21)) {
                readSuccessful = true;
                break;
            }
        }

        try {
            Thread.sleep(SLEEP_INTERVAL);
        } catch (InterruptedException e) {
        }

        timeval += SLEEP_INTERVAL;
    }

    if (!readSuccessful) {
        throw new IOException("Timeout while listening for Data Message");
    }

    // System.out.println("Got the following data message: " +
    // getByteArrayString(buffer, numBytesReadTotal));

    int index;
    int endIndex;
    // if 2nd last character is ETX
    if (etxIndex != -1) {
        if (numBytesReadTotal < 8) {
            throw new IOException("Data message does not have minimum length of 8.");
        }
        index = 1;
        endIndex = etxIndex - 3;
        if (buffer[0] != 0x02) {

            startPosition = 0;
            while (startPosition < numBytesReadTotal) {
                if (buffer[startPosition] == (byte) 0x02) {
                    break;
                } else {
                    if (startPosition < numBytesReadTotal - 2) {
                        startPosition++;
                    } else {
                        throw new IOException(
                                "STX (0x02) character is expected but not received as first byte of data message. (hex: "
                                        + Hex.encodeHexString(buffer) + ")");
                    }
                }
            }
        }
    } else {
        if (numBytesReadTotal < 5) {
            throw new IOException("Data message does not have minimum length of 5.");
        }
        index = 0;
        endIndex = numBytesReadTotal - 3;
    }

    if (buffer[endIndex + 1] != 0x0D) {
        throw new IOException(
                "CR (0x0D) character is expected but not received after data block of data message. (hex: "
                        + Hex.encodeHexString(buffer) + ")");
    }

    if (buffer[endIndex + 2] != 0x0A) {
        throw new IOException(
                "LF (0x0A) character is expected but not received after data block of data message. (hex: "
                        + Hex.encodeHexString(buffer) + ")");
    }

    List<DataSet> dataSets = new ArrayList<DataSet>();
    dataSets.add(new DataSet(identification, "", ""));

    while (index != endIndex) {
        String id = null;

        for (int i = index; i < endIndex - 1; i++) {
            if (buffer[i] == 0x28) {
                // found '('
                id = new String(buffer, index, i - index, charset);
                index = i + 1;
                break;
            }
        }
        if (id == null) {
            throw new IOException(
                    "'(' (0x28) character is expected but not received inside data block of data message. (hex: "
                            + Hex.encodeHexString(buffer) + ")");
        }

        String value = "";
        String unit = "";
        for (int i = index; i < endIndex; i++) {
            if (buffer[i] == 0x2A) {
                // found '*'
                if (i > index) {
                    value = new String(buffer, index, i - index, charset);
                }
                index = i + 1;

                for (int j = index; j < endIndex; j++) {
                    if (buffer[j] == 0x29) {
                        // found ')'
                        unit = new String(buffer, index, j - index, charset);
                        index = j + 1;
                        break;
                    }
                }

                break;
            } else if (buffer[i] == 0x29) {
                // found ')'
                if (i > index) {
                    value = new String(buffer, index, i - index, charset);
                }
                index = i + 1;
                break;
            }
        }
        if (buffer[index - 1] != 0x29) {
            throw new IOException(
                    "')' (0x29) character is expected but not received inside data block of data message. (hex: "
                            + Hex.encodeHexString(buffer) + ")");
        }

        dataSets.add(new DataSet(id, value, unit));

        if (buffer[index] == 0x0d && buffer[index + 1] == 0x0a) {
            index += 2;
        }

    }
    return dataSets;

}

From source file:one.nio.mem.OffheapMap.java

public WritableRecord<K, V> lockRecordForWrite(K key, long timeout, boolean create) throws TimeoutException {
    long hashCode = hashCode(key);
    RWLock lock = lockFor(hashCode);//from ww  w .ja  va2  s .c om
    if (!lock.lockWrite(timeout)) {
        throw new TimeoutException();
    }
    return createWritableRecord(key, hashCode, lock, create);
}

From source file:org.apache.usergrid.rest.applications.assets.AssetResourceIT.java

@Test
@Ignore("Just enable and run when testing S3 large file upload specifically")
public void largeFileInS3() throws Exception {
    UserRepo.INSTANCE.load(resource(), access_token);

    byte[] data = IOUtils.toByteArray(this.getClass().getResourceAsStream("/file-bigger-than-5M"));
    FormDataMultiPart form = new FormDataMultiPart().field("file", data, MediaType.MULTIPART_FORM_DATA_TYPE);

    // send data//  w  ww.  jav  a  2  s .co m
    JsonNode node = resource().path("/test-organization/test-app/foos").queryParam("access_token", access_token)
            .accept(MediaType.APPLICATION_JSON).type(MediaType.MULTIPART_FORM_DATA).post(JsonNode.class, form);
    logNode(node);
    JsonNode idNode = node.get("entities").get(0).get("uuid");
    String uuid = idNode.getTextValue();

    // get entity
    long timeout = System.currentTimeMillis() + 60000;
    while (true) {
        LOG.info("Waiting for upload to finish...");
        Thread.sleep(2000);
        node = resource().path("/test-organization/test-app/foos/" + uuid)
                .queryParam("access_token", access_token).accept(MediaType.APPLICATION_JSON_TYPE)
                .get(JsonNode.class);
        logNode(node);

        // poll for the upload to complete
        if (node.findValue(AssetUtils.E_TAG) != null) {
            break;
        }
        if (System.currentTimeMillis() > timeout) {
            throw new TimeoutException();
        }
    }
    LOG.info("Upload complete!");

    // get data
    InputStream is = resource().path("/test-organization/test-app/foos/" + uuid)
            .queryParam("access_token", access_token).accept(MediaType.APPLICATION_OCTET_STREAM_TYPE)
            .get(InputStream.class);

    byte[] foundData = IOUtils.toByteArray(is);
    assertEquals(5324800, foundData.length);

    // delete
    node = resource().path("/test-organization/test-app/foos/" + uuid).queryParam("access_token", access_token)
            .accept(MediaType.APPLICATION_JSON_TYPE).delete(JsonNode.class);
}

From source file:org.rifidi.edge.readerplugin.llrp.LLRPReaderSession.java

/**
 * This method sends a message and waits for an LLRP response message.
 * /*www  . j av a2s.  com*/
 * @param message
 *            The LLRP message to send to the reader
 * @return The response message
 * @throws TimeoutException
 *             If there was a timeout when processing this command.
 */
public LLRPMessage transact(LLRPMessage message) throws TimeoutException {
    synchronized (connection) {
        try {
            if (timingOut.get()) {
                throw new IllegalStateException("Cannot execute while timing out: " + message.getName());
            }
            LLRPMessage response = this.connection.transact(message, 20000);
            if (response != null) {
                return response;
            } else {
                logger.error("Response for message: " + message.getName() + " was null");
                throw new TimeoutException();
            }
        } catch (TimeoutException e) {
            timingOut.set(true);
            logger.error("Timeout when sending an LLRP Message: " + message.getName());
            throw e;
        }
    }
}

From source file:com.vmware.photon.controller.deployer.xenon.task.UploadVibTaskService.java

private void handlePeriodicMaintenance(State currentState) {

    checkState(currentState.taskTimeoutMicros != 0);

    boolean failTask = (currentState.taskState.stage == TaskState.TaskStage.STARTED
            && currentState.taskStartTimeMicros != null
            && currentState.taskStartTimeMicros < Utils.getNowMicrosUtc() + currentState.taskTimeoutMicros);

    if (failTask) {
        State patchState = buildPatch(TaskState.TaskStage.FAILED, null, new TimeoutException());
        patchState.taskState.failure.statusCode = Operation.STATUS_CODE_TIMEOUT;
        TaskUtils.sendSelfPatch(this, patchState);
    }//from  ww  w  .  java 2 s  . co m
}

From source file:org.cloudifysource.esc.driver.provisioning.byon.ByonProvisioningDriver.java

@Override
protected MachineDetails createServer(final String serverName, final long endTime,
        final ComputeTemplate template) throws CloudProvisioningException, TimeoutException {

    final CustomNode node;
    final MachineDetails machineDetails;
    logger.info(//from w  w w  .  j  av  a  2 s  .  c  o m
            "Cloudify Deployer is creating a machine named: " + serverName + ". This may take a few minutes");
    node = deployer.createServer(cloudTemplateName, serverName);

    machineDetails = createMachineDetailsFromNode(node);

    // At this point the machine is starting. Any error beyond this point
    // must clean up the machine.
    try {
        handleServerCredentials(machineDetails, template);
    } catch (final CloudProvisioningException e) {
        try {
            deployer.invalidateServer(cloudTemplateName, node);
        } catch (final CloudProvisioningException ie) {
            logger.log(Level.SEVERE, "Failed to mark machine [" + machineDetails.getPublicAddress() + "/"
                    + machineDetails.getPrivateAddress() + "] as Invalid.", ie);
        }
        throw new CloudProvisioningException(e);
    }

    if (System.currentTimeMillis() > endTime) {
        throw new TimeoutException();
    }

    logger.info("Machine successfully allocated");
    return machineDetails;
}

From source file:cm.aptoide.pt.DownloadQueueService.java

private void downloadFile(final int apkidHash) {

    try {/*from  w ww . ja  va2 s.c  o m*/

        new Thread() {
            public void run() {
                this.setPriority(Thread.MAX_PRIORITY);

                if (!keepScreenOn.isHeld()) {
                    keepScreenOn.acquire();
                }
                int threadApkidHash = apkidHash;

                String remotePath = notifications.get(threadApkidHash).get("remotePath");
                String md5hash = notifications.get(threadApkidHash).get("md5hash");

                String localPath = notifications.get(threadApkidHash).get("localPath");
                Log.d("Aptoide-DownloadQueuService",
                        "thread apkidHash: " + threadApkidHash + " localPath: " + localPath);

                Message downloadArguments = new Message();
                try {

                    // If file exists, removes it...
                    File f_chk = new File(localPath);
                    if (f_chk.exists()) {
                        f_chk.delete();
                    }
                    f_chk = null;

                    FileOutputStream saveit = new FileOutputStream(localPath);
                    DefaultHttpClient mHttpClient = new DefaultHttpClient();
                    HttpGet mHttpGet = new HttpGet(remotePath);

                    if (Boolean.parseBoolean(notifications.get(threadApkidHash).get("loginRequired"))) {
                        URL mUrl = new URL(remotePath);
                        mHttpClient.getCredentialsProvider().setCredentials(
                                new AuthScope(mUrl.getHost(), mUrl.getPort()),
                                new UsernamePasswordCredentials(
                                        notifications.get(threadApkidHash).get("username"),
                                        notifications.get(threadApkidHash).get("password")));

                    }

                    HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);

                    if (mHttpResponse == null) {
                        Log.d("Aptoide", "Problem in network... retry...");
                        mHttpResponse = mHttpClient.execute(mHttpGet);
                        if (mHttpResponse == null) {
                            Log.d("Aptoide", "Major network exception... Exiting!");
                            /*msg_al.arg1= 1;
                            download_error_handler.sendMessage(msg_al);*/
                            throw new TimeoutException();
                        }
                    }

                    if (mHttpResponse.getStatusLine().getStatusCode() == 401) {
                        throw new TimeoutException();
                    } else {
                        InputStream getit = mHttpResponse.getEntity().getContent();
                        byte data[] = new byte[8096];
                        int red;
                        red = getit.read(data, 0, 8096);

                        int progressNotificationUpdate = 200;
                        int intermediateProgress = 0;
                        while (red != -1) {
                            if (progressNotificationUpdate == 0) {
                                if (!keepScreenOn.isHeld()) {
                                    keepScreenOn.acquire();
                                }
                                progressNotificationUpdate = 200;
                                Message progressArguments = new Message();
                                progressArguments.arg1 = threadApkidHash;
                                progressArguments.arg2 = intermediateProgress;
                                downloadProgress.sendMessage(progressArguments);
                                intermediateProgress = 0;
                            } else {
                                intermediateProgress += red;
                                progressNotificationUpdate--;
                            }

                            saveit.write(data, 0, red);
                            red = getit.read(data, 0, 8096);
                        }
                        Log.d("Aptoide",
                                "Download done! apkidHash: " + threadApkidHash + " localPath: " + localPath);
                        saveit.flush();
                        saveit.close();
                        getit.close();
                    }

                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }

                    File f = new File(localPath);
                    Md5Handler hash = new Md5Handler();
                    if (md5hash == null || md5hash.equalsIgnoreCase(hash.md5Calc(f))) {
                        downloadArguments.arg1 = 1;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadArguments.obj = localPath;
                        downloadHandler.sendMessage(downloadArguments);
                    } else {
                        Log.d("Aptoide", md5hash + " VS " + hash.md5Calc(f));
                        downloadArguments.arg1 = 0;
                        downloadArguments.arg2 = threadApkidHash;
                        downloadErrorHandler.sendMessage(downloadArguments);
                    }

                } catch (Exception e) {
                    if (keepScreenOn.isHeld()) {
                        keepScreenOn.release();
                    }
                    downloadArguments.arg1 = 1;
                    downloadArguments.arg2 = threadApkidHash;
                    downloadErrorHandler.sendMessage(downloadArguments);
                }
            }
        }.start();

    } catch (Exception e) {
    }
}

From source file:com.github.trask.sandbox.ec2.Ec2Service.java

public Instance waitForStartup(String instanceId, long timeoutMillis)
        throws TimeoutException, InterruptedException {

    Instance instance = getInstance(instanceId);
    String state = instance.getState().getName();
    if ("running".equals(state)) {
        return instance;
    }//  w  ww. jav a 2 s  . co  m
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() - startTime < timeoutMillis) {
        logger.debug("waiting for instance to start...");
        Thread.sleep(5000);
        instance = getInstance(instance.getInstanceId());
        state = instance.getState().getName();
        if ("running".equals(state)) {
            return instance;
        }
    }
    throw new TimeoutException();
}

From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java

protected void add(NeoEMFEObject object, EAttribute eAttribute, int index, Object value) {
    try {//from   ww  w.j a v a  2s.c  o m
        String[] array;
        boolean passed = false;
        int attemp = 0;

        do {
            array = (String[]) getFromTable(object, eAttribute);
            //array = (String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value));
            Put put = new Put(Bytes.toBytes(object.neoemfId()))
                    .add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()),
                            NeoEMFUtil.EncoderUtil.toBytes(index < 0
                                    ? (String[]) ArrayUtils.add(array, serializeValue(eAttribute, value))
                                    : (String[]) ArrayUtils.add(array, serializeValue(eAttribute, value))));
            passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY,
                    Bytes.toBytes(eAttribute.getName()),
                    array == null ? null : NeoEMFUtil.EncoderUtil.toBytes(array), put);
            if (!passed) {
                if (attemp > ATTEMP_TIMES_DEFAULT)
                    throw new TimeoutException();
                Thread.sleep((++attemp) * SLEEP_DEFAULT);
            }

        } while (!passed);

    } catch (IOException e) {
        Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format(
                "Unable to add ''{0}'' to ''{1}'' for element ''{2}''", value, eAttribute.getName(), object));
    } catch (TimeoutException e) {
        Logger.log(Logger.SEVERITY_ERROR,
                MessageFormat.format("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times",
                        value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT));
        e.printStackTrace();
    } catch (InterruptedException e) {
        Logger.log(Logger.SEVERITY_ERROR, MessageFormat
                .format("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()));
        e.printStackTrace();
    }
}