List of usage examples for java.lang InterruptedException getMessage
public String getMessage()
From source file:com.minoritycode.Application.java
@Override public void run() { boolean lockAcquired = false; do {// w ww. j a va2 s . c o m //Lock and Block + remove file from file list. try { if (lock.tryLock(10, TimeUnit.MILLISECONDS)) { boardId = boards.get(0); boards.remove(0); lockAcquired = true; } } catch (InterruptedException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } finally { //release lock if (lockAcquired) { lock.unlock(); lockAcquired = false; } } BoardDownloader downloader = new BoardDownloader(); downloader.downloadBoard(url, boardId); long threadInterval = Long.parseLong(config.getProperty("threadInterval")); try { Thread.sleep(threadInterval); } catch (InterruptedException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } } while (boards.size() > 0); threadCounter++; // System.out.println(threadCounter+ " Threads completed"); if (threadCounter == Integer.parseInt(config.getProperty("numberOfThreads"))) { System.out.println(threadCounter + " Threads completed"); StringBuilder boardsMissed = new StringBuilder(); Iterator it = errorBoards.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); System.out.println(pair.getKey() + " = " + pair.getValue()); boardsMissed.append(pair.getKey() + " = " + pair.getValue() + "\n"); it.remove(); // avoids a ConcurrentModificationException } try { report.put("boardNumSuccessful", boardCountSuc); report.put("boardsNotDownloaded", boardsMissed.toString()); } catch (JSONException e) { e.printStackTrace(); logger.logLine(e.getMessage()); } logger.logger(report); logger.stopErrorLogger(); manageBackups(rootDir); if (manualOperation) { System.out.println("Press enter to exit.........."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); } } System.exit(0); } }
From source file:org.createnet.raptor.indexer.impl.ElasticSearchIndexer.java
/** * * @throws IndexerException/* ww w .j ava 2 s. co m*/ */ @Override public void open() throws IndexerException { int tries = 0, maxTries = 5, waitFor = 5000; while (true) { try { connect(); return; } catch (Exception ex) { logger.warn("Connection to cluster failed: {}", ex.getMessage()); if (tries >= maxTries) { break; } try { Thread.sleep(waitFor * tries); } catch (InterruptedException ex1) { logger.warn("Cannot sleep current thread {}", ex1.getMessage()); } } tries++; } throw new IndexerException("Connection failed"); }
From source file:com.bt.aloha.batchtest.BatchTest.java
private void waitForAllToFinish(int totalTime) { log.info("waiting for scenarios to finish..."); int loops = totalTime / 10; while (!allSucceeded() && loops > 0) { try {//from w w w. j a v a 2 s .c o m Thread.sleep(10 * 1000); } catch (InterruptedException e) { log.error(e.getMessage(), e); } loops--; } log.info("... finished waiting"); }
From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationWhen.java
public SELF i_start_the_project() { OkHttpClient httpClient = new OkHttpClient(); String url = "http://" + restEntryPointHost + ":" + restEntryPointPort + "/api/v1/project/" + projectConfiguration.getIdentifier(); RequestBody body = RequestBody.create(null, new byte[0]); Request.Builder builder = new Request.Builder().url(url).post(body); builder = HttpUserSupport.addBasicAuthentification(currentUser, builder); Response response = null;//from w w w. j a v a2s .com try { response = httpClient.newCall(builder.build()).execute(); assertThat(response.code()).isEqualTo(201); LOGGER.trace("Starting project"); Map<String, Boolean> brickRunning = new HashMap<>(); projectConfiguration.getDefaultBrickConfigurations().forEachRemaining(b -> { brickRunning.put(b.getName(), Boolean.FALSE); }); JsonParser parser = new JsonParser(); boolean allBrickStarted = true; long now = System.currentTimeMillis(); long end = now + 180000; do { Iterator<String> messageReceive = webSocketEventsListener.getMessages().iterator(); while (messageReceive.hasNext()) { String message = messageReceive.next(); JsonObject root = (JsonObject) parser.parse(message); if ("updateState".equals(root.getAsJsonPrimitive("action").getAsString())) { JsonObject data = root.getAsJsonObject("data"); String brickName = data.getAsJsonPrimitive("brickName").getAsString(); String brickState = data.getAsJsonPrimitive("state").getAsString(); if ("RUNNING".equals(brickState)) { brickRunning.put(brickName, Boolean.TRUE); } } } Iterator<Boolean> iterator = brickRunning.values().iterator(); allBrickStarted = true; while (allBrickStarted && iterator.hasNext()) { allBrickStarted = iterator.next(); } if (!allBrickStarted) { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } now = System.currentTimeMillis(); } while (!allBrickStarted && now < end); assertThat(allBrickStarted).isTrue(); } catch (IOException e) { fail(e.getMessage()); } finally { if (response != null) { IOUtils.closeQuietly(response.body()); } } return self(); }
From source file:com.amazon.aws.samplecode.travellog.web.TravelLogController.java
private void preloadJournal() { Configuration config = Configuration.getInstance(); String bucket = config.getProperty("bundleBucket"); String path = config.getProperty("bundlePath"); DataLoader loader = new DataLoader(bucket, path, dao); Thread thread = new Thread(loader); thread.start();/*from www . j av a 2s . com*/ try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block logger.log(Level.WARNING, e.getMessage(), e); } }
From source file:ch.wir_entwickeln.yavanna.serialport.SerialPortCCI.java
/** * Sends data on the serial port./*from www .j av a2 s .co m*/ * * @param data The data to send. */ public synchronized void send(byte[] data) { String formattedData = new String(data).replaceAll(Character.toString((char) 13), "<CR>"); logger.debug("Sending '{}' on serial port {}...", new String[] { formattedData, portName }); try { // Write data to serial port buffer for (byte dataByte : data) { outputStream.write(dataByte); try { Thread.sleep(30); } catch (InterruptedException e) { // Ignore exception } } outputStream.flush(); } catch (IOException e) { logger.error("Error sending data on serial port {}: {}", portName, e.getMessage()); } }
From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestExecutor.java
/** * Exponential sleep on failed request to avoid flooding a service with * retries.//from w w w . j a va 2 s. com * * @param retries Current retry count. * @param previousException Exception information for the previous attempt, if any. */ private void pauseExponentially(int retries, RestException previousException) { long delay; if (backoffStrategy != null) { delay = this.backoffStrategy.getDelayMillis(retries); } else { long scaleFactor = 300; if (previousException != null && isThrottlingException(previousException)) { scaleFactor = 500 + random.nextInt(100); } delay = (long) (Math.pow(2, retries) * scaleFactor); } delay = Math.min(delay, MAX_BACKOFF_IN_MILLISECONDS); log.debug("Retryable condition detected, will retry in {}ms, attempt number: {}", delay, retries); try { Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RestException(e.getMessage(), e); } }
From source file:br.usp.poli.lta.cereda.aa.execution.AdaptiveAutomaton.java
/** * Reconhece, apenas uma vez, uma lista de smbolos representado a cadeia * de entrada.//from w w w . j a v a2s. co m * @param input Lista de smbolos representando a cadeia de entrada. * @return Um valor lgico informando se o autmato adaptativo reconheceu * a cadeia de entrada. */ private boolean recognizeOnce(List<Symbol> input) { // realiza a configurao e verifica se a submquina // principal no nula setup(); Validate.notNull(mainSubmachine, "A submquina principal no pode ser nula."); // cria a thread inicial com os conjuntos // do modelo Kernel k = new Kernel(threads, removals, paths); k.setStack(stack); k.setActions(actions); k.setTransitions(transitions); k.setSubmachines(submachines); k.setCurrentSubmachine(mainSubmachine); k.setMainSubmachine(mainSubmachine); k.setInput(input); k.setCursor(0); k.setEnablePriorAction(true); // cria uma transio inicial em vazio que faz o autmato // entrar no estado inicial da submquina principal e ajusta // o cursor de leitura no incio da cadeia Transition t = new Transition(); t.setTransition(null, EPSILON, submachines.getFromName(mainSubmachine).getInitialState()); k.setTransition(t); // cria um novo caminho de reconhecimento e // adiciona a thread inicial na lista de threads paths.put(k.getIdentifier(), new RecognitionPath()); threads.add(k); // enquanto a lista de threads no estiver vazia e o autmato // adaptativo no retornou alguma sada em relao ao processo // de reconhecimento, repete o passo computacional while (!threads.isEmpty() && !atLeastOneRecognitionPathIsDone()) { // verifica se existem threads que j terminaram // e devem ser removidas if (!removals.isEmpty()) { // para cada identificador das threads a serem removidas, // percorre a lista de threads e remove aquelas cujo // identificador igual for (int i : removals) { for (int j = 0; j < threads.size(); j++) { if (threads.get(j).getIdentifier() == i) { threads.remove(j); break; } } // repete a operao no mapa de caminhos de // reconhecimento, mas apenas os reconhecimentos // incompletos so removidos if (!paths.get(i).done()) { paths.remove(i); } } // todas as threads marcadas para remoo foram // devidamente removidas, portanto, agora a lista // de remoo deve ser limpa removals.clear(); } // executa um passo computacional para cada thread // da lista de threads for (int i = 0; i < threads.size(); i++) { // tenta executar, talvez a thread d erro try { threads.get(i).start(); threads.get(i).join(); } catch (InterruptedException exception) { System.err.println("Thread error: " + exception.getMessage()); System.exit(1); } } } // o processo de reconhecimento da cadeia j encerrou, mas ainda // necessrio fazer uma ltima limpeza na lista de threads e no // mapa dos caminhos de reconhecimento if (!removals.isEmpty()) { // para cada identificador das threads a serem removidas, // percorre a lista de threads e remove aquelas cujo // identificador igual for (int i : removals) { for (int j = 0; j < threads.size(); j++) { if (threads.get(j).getIdentifier() == i) { threads.remove(j); break; } } // repete a operao no mapa de caminhos de // reconhecimento, mas apenas os reconhecimentos // incompletos so removidos if (!paths.get(i).done()) { paths.remove(i); } } // todas as threads marcadas para remoo foram // devidamente removidas, portanto, agora a lista // de remoo deve ser limpa removals.clear(); } // verifica se algum caminho de reconhecimento conduziu // aceitao da cadeia e retorna o resultado for (int i : paths.keySet()) { if (paths.get(i).done()) { if (paths.get(i).getResult() == true) { return true; } } } // a cadeia no foi aceita, retorna falso return false; }
From source file:com.cloudbees.plugins.deployer.impl.run.RunEngineImpl.java
@Override protected FilePath.FileCallable<DeployedApplicationLocation> newDeployActor(RunTargetImpl target) throws DeployException { try {/*from w w w . j a v a2 s. c o m*/ return new DeployFileCallable(build, listener, user, account, target, target.getApplicationConfigMap(build, listener)); } catch (InterruptedException e) { throw new DeployException("Deployment interrupted", e); } catch (IOException e) { throw new DeployException(e.getMessage(), e); } catch (MacroEvaluationException e) { throw new DeployException(e.getMessage(), e); } catch (Throwable t) { throw new DeployException(t.getMessage(), t); } }
From source file:edu.harvard.i2b2.crc.ejb.QueryManagerBeanUtil.java
public Map testSend(String domainId, String projectId, String ownerId, String generatedSql, String sessionId, String queryInstanceId, String patientSetId, String xmlRequest, long timeout) throws Exception { String status = null;// w w w. j a v a 2 s . com int queryResultInstanceId = 0; log.debug("in testSend"); QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance(); ServiceLocator serviceLocator = ServiceLocator.getInstance(); /* QueueConnection conn = serviceLocator.getQueueConnectionFactory( QUEUE_CONN_FACTORY_NAME).createQueueConnection(); Queue sendQueue = serviceLocator.getQueue(SMALL_QUEUE_NAME); Queue responseQueue = serviceLocator.getQueue(RESPONSE_QUEUE_NAME); QueueSession session = conn.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); String id = sessionId; String selector = "JMSCorrelationID='" + id + "'"; QueueSender sender = session.createSender(sendQueue); MapMessage mapMsg = session.createMapMessage(); mapMsg.setJMSCorrelationID(id); mapMsg.setJMSReplyTo(responseQueue); mapMsg.setString(XML_REQUEST_PARAM, xmlRequest); mapMsg.setString(QUERY_MASTER_GENERATED_SQL_PARAM, generatedSql); mapMsg.setString(QUERY_INSTANCE_ID_PARAM, queryInstanceId); mapMsg.setString(QUERY_PATIENT_SET_ID_PARAM, patientSetId); mapMsg.setString(DS_LOOKUP_DOMAIN_ID, domainId); mapMsg.setString(DS_LOOKUP_PROJECT_ID, projectId); mapMsg.setString(DS_LOOKUP_OWNER_ID, ownerId); sender.send(mapMsg); QueueConnection conn1 = serviceLocator.getQueueConnectionFactory( QUEUE_CONN_FACTORY_NAME).createQueueConnection(); conn1.start(); QueueSession recvSession = conn1.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); QueueReceiver rcvr = recvSession .createReceiver(responseQueue, selector); MapMessage receivedMsg = (MapMessage) rcvr.receive(timeout); if (receivedMsg == null) { status = "RUNNING"; log.info("STATUS IS RUNNING " + status); } else { String responseObj = (String) receivedMsg.getString("para1"); status = (String) receivedMsg .getString(QueryManagerBeanUtil.QUERY_STATUS_PARAM); log.debug("Got back response from executor " + responseObj); if (status != null && status.indexOf("LOCKEDOUT") > -1) { ; } else { status = "DONE"; } queryResultInstanceId = receivedMsg .getInt(QT_QUERY_RESULT_INSTANCE_ID_PARAM); log.info("RESULT INSTANCE ID " + queryResultInstanceId); } */ //TODO mm bypass JMS and call directly long waitTime = getTimeout(xmlRequest); ExecRunnable exec = new ExecRunnable(); exec.execute(generatedSql, queryInstanceId, patientSetId, xmlRequest, domainId, projectId, ownerId); Thread t = new Thread(exec); synchronized (t) { t.start(); try { //if (waitTime > 0) { // t.wait(waitTime); //} else { // t.wait(); //} long startTime = System.currentTimeMillis(); long deltaTime = -1; while ((exec.isJobCompleteFlag() == false) && (deltaTime < waitTime)) { if (waitTime > 0) { t.wait(waitTime - deltaTime); deltaTime = System.currentTimeMillis() - startTime; } else { t.wait(); } } if (exec.isJobCompleteFlag() == false) { String timeOuterror = "Result waittime millisecond <result_waittime_ms> :" + waitTime + " elapsed, setting to next queue"; log.debug(timeOuterror); DAOFactoryHelper daoFactoryHelper = new DAOFactoryHelper(domainId, projectId, ownerId); IDAOFactory daoFactory = daoFactoryHelper.getDAOFactory(); SetFinderDAOFactory sfDAOFactory = daoFactory.getSetFinderDAOFactory(); //DataSourceLookup dsLookup = sfDAOFactory.getDataSourceLookup(); // check if the status is cancelled IQueryInstanceDao queryInstanceDao = sfDAOFactory.getQueryInstanceDAO(); QtQueryInstance queryInstance = queryInstanceDao.getQueryInstanceByInstanceId(queryInstanceId); queryInstance.setBatchMode(MEDIUM_QUEUE); //queryInstance.setEndDate(new Date(System // .currentTimeMillis())); queryInstanceDao.update(queryInstance, false); log.debug("Set to MEDIUM Queue"); Map returnMap = new HashMap(); returnMap.put(QUERY_STATUS_PARAM, "RUNNING"); int id = Integer.parseInt(queryInstanceId); returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, id); return returnMap; //throw new Exception("Timed Out, setting to MEDIUM Queue"); } } catch (InterruptedException e) { log.error("Error in thread: " + e.getMessage()); e.printStackTrace(); throw new I2B2Exception("Thread error while running CRC job ", e); } finally { t.interrupt(); //exec = null; t = null; } } // closeAll(sender, null, conn, session); // closeAll(null, rcvr, conn1, recvSession); // closeAllTopic(rcvr,conn1,recvSession); //MM // Map returnMap = new HashMap(); // returnMap.put(QUERY_STATUS_PARAM, status); // returnMap.put(QT_QUERY_RESULT_INSTANCE_ID_PARAM, queryResultInstanceId); // return returnMap; return exec.getResult(); }