org.kurento.commons.exception.KurentoException Java Examples

The following examples show how to use org.kurento.commons.exception.KurentoException. 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: RoomClientFakeTest.java    From kurento-room with Apache License 2.0 6 votes vote down vote up
@Override
public void setupBrowserTest() throws InterruptedException {
  super.setupBrowserTest();

  calculateUrl();

  String wsProtocol = "ws";
  if (protocol.equals(Protocol.HTTPS)) {
    wsProtocol = "wss";
  }
  String hostName = appUrl.getHost();
  try {
    appWsUrl = new URI(wsProtocol, null, hostName, serverPort, appWsPath, null, null);
  } catch (URISyntaxException e) {
    throw new KurentoException("Exception generating WS URI from " + wsProtocol + ", " + hostName
        + ", server port " + serverPort + " and WS path " + appWsPath);
  }
  log.debug("Protocol: {}, Hostname: {}, Port: {}, Path: {}", wsProtocol, hostName, serverPort,
      appWsPath);

  fakeKurentoClient = fakeKms.getKurentoClient();
  Assert.assertNotNull("Fake Kurento Client is null", fakeKurentoClient);
}
 
Example #2
Source File: FixedOneKmsManager.java    From openvidu with Apache License 2.0 6 votes vote down vote up
@Override
public List<Kms> initializeKurentoClients(List<KmsProperties> kmsProperties, boolean disconnectUponFailure) throws Exception {
	KmsProperties firstProps = kmsProperties.get(0);
	KurentoClient kClient = null;
	Kms kms = new Kms(firstProps, loadManager);
	try {
		kClient = KurentoClient.create(firstProps.getUri(), this.generateKurentoConnectionListener(kms.getId()));
		this.addKms(kms);
		kms.setKurentoClient(kClient);

		// TODO: This should be done in KurentoClient connected event
		kms.setKurentoClientConnected(true);
		kms.setTimeOfKurentoClientConnection(System.currentTimeMillis());

	} catch (KurentoException e) {
		log.error("KMS in {} is not reachable by OpenVidu Server", firstProps.getUri());
		if (kClient != null) {
			kClient.destroy();
		}
		throw new Exception();
	}
	return Arrays.asList(kms);
}
 
Example #3
Source File: KurentoClient.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
protected KurentoClient(JsonRpcClient client) {
  this.client = client;
  this.manager = new RomManager(new RomClientJsonRpcClient(client));
  client.setRequestTimeout(requesTimeout);
  client.setConnectionTimeout((int) connectionTimeout);
  if (client instanceof AbstractJsonRpcClientWebSocket) {
    ((AbstractJsonRpcClientWebSocket) client).enableHeartbeat(KEEPALIVE_TIME);
  }
  try {
    long start = System.currentTimeMillis();
    client.connect();
    long duration = System.currentTimeMillis() - start;

    if (duration > WARN_CONNECTION_TIME) {
      log.warn("Connected to KMS in {} millis (> {} millis)", duration, WARN_CONNECTION_TIME);
    }

  } catch (Exception e) {
    throw new KurentoException("Exception connecting to KMS", e);
  }
}
 
Example #4
Source File: SystemMonitorManager.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
private Object sendMessage(String message) {
  Object returnedMessage = null;
  try {
    log.debug("Sending message {} to {}", message, remoteKms.getHost());
    Socket client = new Socket(remoteKms.getHost(), monitorPort);
    PrintWriter output = new PrintWriter(client.getOutputStream(), true);
    ObjectInputStream input = new ObjectInputStream(client.getInputStream());
    output.println(message);

    returnedMessage = input.readObject();
    log.debug("Receive message {}", returnedMessage);

    output.close();
    input.close();
    client.close();

  } catch (Exception e) {
    throw new KurentoException(e);
  }

  return returnedMessage;
}
 
Example #5
Source File: TestReport.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public TestReport(String name, int numRetries, String htmlHeader) {
  try {
    this.numRetries = numRetries;
    this.extraInfoHtml = "";
    this.extraErrorHtml = "";
    String title = name == null ? "Tests report [" + new Date() + "]" : name;
    File file = new File(testReport);
    boolean exists = file.exists();
    writer = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
    if (!exists) {
      initPage();
      if (htmlHeader != null) {
        appendHtml(htmlHeader);
      }
    }
    appendTitle(title);
    writer.flush();
  } catch (IOException e) {
    throw new KurentoException(e);
  }
}
 
Example #6
Source File: KmsService.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
private void createFileFromTemplate(Configuration cfg, Map<String, Object> data,
    String filename) {

  try {
    Template template = cfg.getTemplate(filename + ".ftl");
    File file = new File(workspace + File.separator + filename);
    Writer writer = new FileWriter(file);
    template.process(data, writer);
    writer.flush();
    writer.close();

    log.trace("Created file '{}'", file.getAbsolutePath());

  } catch (Exception e) {
    throw new KurentoException("Exception while creating file from template", e);
  }
}
 
Example #7
Source File: FileRepositoryItem.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
@Override
public OutputStream createOutputStreamToWrite() {

  checkState(State.NEW);

  try {

    this.state = State.STORING;

    storingOutputStream = new FilterOutputStream(new FileOutputStream(file)) {
      @Override
      public void close() throws java.io.IOException {
        refreshAttributesOnClose();
      }
    };

    return storingOutputStream;

  } catch (FileNotFoundException e) {
    throw new KurentoException("There is a problem opening the output stream to the file "
        + "that will store the contents of the repositoty item", e);
  }
}
 
Example #8
Source File: BrowserTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public void syncTimeForOcr(final W[] webpages, final String[] videoTagsId,
    final String[] peerConnectionsId) throws InterruptedException {
  int webpagesLength = webpages.length;
  int videoTagsLength = videoTagsId.length;
  if (webpagesLength != videoTagsLength) {
    throw new KurentoException("The size of webpage arrays (" + webpagesLength
        + "}) must be the same as videoTags (" + videoTagsLength + ")");
  }

  final ExecutorService service = Executors.newFixedThreadPool(webpagesLength);
  final CountDownLatch latch = new CountDownLatch(webpagesLength);

  for (int i = 0; i < webpagesLength; i++) {
    final int j = i;
    service.execute(new Runnable() {
      @Override
      public void run() {
        webpages[j].syncTimeForOcr(videoTagsId[j], peerConnectionsId[j]);
        latch.countDown();
      }
    });
  }
  latch.await();
  service.shutdown();
}
 
Example #9
Source File: MediaPipelineAsyncBaseTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
protected static void releaseMediaObject(final MediaObject mo) throws InterruptedException {
  final CountDownLatch latch = new CountDownLatch(1);

  if (mo != null) {
    mo.release(new Continuation<Void>() {
      @Override
      public void onSuccess(Void result) {
        latch.countDown();
      }

      @Override
      public void onError(Throwable cause) {
        throw new KurentoException(cause);
      }
    });
    Assert.assertTrue("Timeout of 25s releasing object", latch.await(25, TimeUnit.SECONDS));
  }
}
 
Example #10
Source File: RepositoryHttpServlet.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
private String configureServletMapping(ServletConfig servletConfig) {
  Collection<String> mappings = servletConfig.getServletContext()
      .getServletRegistration(servletConfig.getServletName()).getMappings();

  if (mappings.isEmpty()) {
    throw new KurentoException(
        "There is no mapping for servlet " + RepositoryHttpServlet.class.getName());
  }

  String mapping = mappings.iterator().next();

  // TODO: Document this. We assume a mapping starting with / and ending
  // with /*
  mapping = mapping.substring(0, mapping.length() - 1);

  repoHttpManager.setServletPath(mapping);

  return mapping;
}
 
Example #11
Source File: SshConnection.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public String execAndWaitCommand(String... command) {
  log.debug("execAndWaitCommand: {} ", Arrays.toString(command));

  CmdLine cmdLine = new CmdLine();
  for (String c : command) {
    cmdLine.addRaw(c);
  }
  OverthereProcess process = connection.startProcess(cmdLine);

  StringBuilder sb = new StringBuilder();
  try {
    BufferedReader r = new BufferedReader(new InputStreamReader(process.getStdout(), "UTF-8"));
    String line = null;
    while ((line = r.readLine()) != null) {
      log.debug(line);
      sb.append(line).append("\r\n");
    }
  } catch (Exception e) {
    throw new KurentoException("Exception executing command " + Arrays.toString(command), e);
  }

  return sb.toString();
}
 
Example #12
Source File: Shell.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
public static String runAndWaitNoLog(final String... command) {
  Process p;
  try {
    p = new ProcessBuilder(command).redirectErrorStream(true).start();

    String output = CharStreams.toString(new InputStreamReader(p.getInputStream(), "UTF-8"));

    p.destroy();

    return output;

  } catch (IOException e) {
    throw new KurentoException(
        "Exception executing command on the shell: " + Arrays.toString(command), e);
  }
}
 
Example #13
Source File: SystemMonitorManager.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public void startMonitoring() {

    final long startTime = new Date().getTime();
    executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    thread = new Thread() {
      @Override
      public void run() {
        try {
          while (true) {
            executor.execute(new Runnable() {
              @Override
              public void run() {
                registerSample(startTime);
              }
            });

            Thread.sleep(samplingTime);
          }
        } catch (InterruptedException | KurentoException re) {
          log.warn("Monitoring thread interrupted. Finishing execution");
        } catch (Exception e) {
          log.error("Exception in system monitor manager", e);
        }
      }
    };
    thread.setDaemon(true);
    thread.start();
  }
 
Example #14
Source File: PlayerHandler.java    From kurento-tutorial-java with Apache License 2.0 5 votes vote down vote up
private void doSeek(final WebSocketSession session, JsonObject jsonMessage) {
  UserSession user = users.get(session.getId());

  if (user != null) {
    try {
      user.getPlayerEndpoint().setPosition(jsonMessage.get("position").getAsLong());
    } catch (KurentoException e) {
      log.debug("The seek cannot be performed");
      JsonObject response = new JsonObject();
      response.addProperty("id", "seek");
      response.addProperty("message", "Seek failed");
      sendMessage(session, response.toString());
    }
  }
}
 
Example #15
Source File: KurentoClientKmsConnectionTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Test
public void errorSendingClosedKmsTest() throws Exception {

  String kmsUrl = kms.getWsUri();

  KurentoClient kurento = KurentoClient.create(kmsUrl, new KurentoConnectionListener() {

    @Override
    public void reconnected(boolean sameServer) {
    }

    @Override
    public void disconnected() {
      log.debug("Disconnected");
    }

    @Override
    public void connectionFailed() {
    }

    @Override
    public void connected() {
    }
  });

  kurento.createMediaPipeline();

  kms.stopKms();

  try {
    kurento.createMediaPipeline();
    fail("KurentoException should be thrown");
  } catch (KurentoException e) {
    assertThat(e.getMessage(), containsString("Exception connecting to WebSocket"));
  }
}
 
Example #16
Source File: RepositoryApplicationContextConfiguration.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Bean
public Repository repository() {
  RepositoryApiConfiguration repositoryApiConfiguration = repositoryApiConfiguration();
  RepoType rtype = repositoryApiConfiguration.getRepositoryType();
  log.debug("Repository type: {}", rtype);
  if (rtype.isFilesystem()) {
    return new FileSystemRepository();
  } else if (rtype.isMongoDB()) {
    return new MongoRepository();
  } else {
    throw new KurentoException("Unrecognized repository type. Must be filesystem or mongodb");
  }
}
 
Example #17
Source File: RepositoryHttpEndpointImpl.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void stopTimerAndCloseOS() {
  if (lastStartedTimerFuture != null) {
    lastStartedTimerFuture.cancel(false);
    lastStartedTimerFuture = null;
  }

  if (os != null) {
    try {
      os.close();
    } catch (IOException e) {
      throw new KurentoException(e);
    }
  }
}
 
Example #18
Source File: MongoRepositoryItem.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
protected void refreshAttributesOnClose() {
  dbFile = ((MongoRepository) repository).getGridFS().findOne(getId());
  if (dbFile == null) {
    throw new KurentoException("Grid object not found for id " + getId());
  }
  state = State.STORED;
  attributes.setContentLength(dbFile.getLength());
}
 
Example #19
Source File: FileRepositoryItem.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream createInputStreamToRead() {

  checkState(State.STORED);

  try {
    return new FileInputStream(file);
  } catch (FileNotFoundException e) {
    throw new KurentoException(
        "The file storing this repositoty item was deleted before creation", e);
  }
}
 
Example #20
Source File: FileSystemRepository.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(RepositoryItem item) {
  FileRepositoryItem fileItem = (FileRepositoryItem) item;
  httpManager.disposeHttpRepoItemElemByItemId(item, "Repository Item removed");
  File file = fileItem.getFile();
  boolean success = file.delete();
  if (!success) {
    throw new KurentoException("The file can't be deleted");
  }
}
 
Example #21
Source File: RepositoryController.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.DELETE, value = "/{itemId}")
public void removeRepositoryItem(@PathVariable("itemId") String itemId,
    HttpServletResponse response) {
  try {
    repoService.removeRepositoryItem(itemId);
  } catch (ItemNotFoundException e) {
    try {
      response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
    } catch (IOException ioe) {
      ioe.printStackTrace();
      throw new KurentoException(ioe);
    }
  }
}
 
Example #22
Source File: RepositoryController.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/{itemId}")
public RepositoryItemPlayer getReadEndpoint(@PathVariable("itemId") String itemId,
    HttpServletResponse response) {
  try {
    return repoService.getReadEndpoint(itemId);
  } catch (ItemNotFoundException e) {
    try {
      response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
    } catch (IOException ioe) {
      ioe.printStackTrace();
      throw new KurentoException(ioe);
    }
    return null;
  }
}
 
Example #23
Source File: RepositoryController.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET, value = "/{itemId}/metadata")
public Map<String, String> getRepositoryItemMetadata(@PathVariable("itemId") String itemId,
    HttpServletResponse response) {
  try {
    return repoService.getRepositoryItemMetadata(itemId);
  } catch (ItemNotFoundException e) {
    try {
      response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
    } catch (IOException ioe) {
      ioe.printStackTrace();
      throw new KurentoException(ioe);
    }
    return null;
  }
}
 
Example #24
Source File: RepositoryController.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT, value = "/{itemId}/metadata")
public void setRepositoryItemMetadata(@RequestBody(required = true) Map<String, String> metadata,
    @PathVariable("itemId") String itemId, HttpServletResponse response) {
  try {
    repoService.setRepositoryItemMetadata(itemId, metadata);
  } catch (ItemNotFoundException e) {
    try {
      response.sendError(HttpStatus.NOT_FOUND.value(), e.getMessage());
    } catch (IOException ioe) {
      ioe.printStackTrace();
      throw new KurentoException(ioe);
    }
  }
}
 
Example #25
Source File: SystemMonitorManager.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public SystemMonitorManager() {

    try {
      String wsUri = getProperty(KMS_WS_URI_PROP, KMS_WS_URI_DEFAULT);
      String kmsScope = getProperty(KMS_SCOPE_PROP, KMS_SCOPE_DEFAULT);

      boolean isKmsRemote = !wsUri.contains("localhost") && !wsUri.contains("127.0.0.1");
      boolean isKmsDocker = kmsScope.equalsIgnoreCase("docker");

      if (isKmsDocker) {
        // "Dockerized" KMS
        String containerId = KmsService.getMonitoredDockerContainerName();
        log.debug("KMS container ID: {}", containerId);
        monitor = new KmsDockerMonitor(containerId);

      } else if (isKmsRemote) {
        // Remote KMS

        String kmsLogin = getProperty(KMS_LOGIN_PROP);
        String kmsPasswd = getProperty(KMS_PASSWD_PROP);
        String kmsPem = getProperty(KMS_PEM_PROP);

        startRemoteMonitor(wsUri, kmsLogin, kmsPasswd, kmsPem);

      } else {
        // Local KMS

        monitor = new KmsLocalMonitor();
      }

    } catch (Exception e) {
      throw new KurentoException(e);
    }
  }
 
Example #26
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public void waitForContainer(String containerName) {
  boolean isRunning = false;

  long timeoutMs =
      System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(WAIT_CONTAINER_POLL_TIMEOUT);
  do {
    // Check timeout
    if (System.currentTimeMillis() > timeoutMs) {
      throw new KurentoException("Timeout of " + WAIT_CONTAINER_POLL_TIMEOUT
          + " seconds waiting for container " + containerName);
    }

    isRunning = isRunningContainer(containerName);
    if (!isRunning) {
      try {
        // Wait WAIT_HUB_POLL_TIME ms
        log.debug("Container {} is not still running ... waiting {} ms", containerName,
            WAIT_CONTAINER_POLL_TIME);
        Thread.sleep(WAIT_CONTAINER_POLL_TIME);

      } catch (InterruptedException e) {
        log.error("Exception waiting for hub");
      }

    }
  } while (!isRunning);
}
 
Example #27
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public Statistics getStatistics(String containerId) {
  FirstObjectResultCallback<Statistics> resultCallback = new FirstObjectResultCallback<>();

  try {
    return getClient().statsCmd(containerId).exec(resultCallback).waitForObject();
  } catch (InterruptedException e) {
    throw new KurentoException("Interrupted while waiting for statistics");
  }
}
 
Example #28
Source File: GridNode.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public String getHome() {
  if (home == null) {
    // OverThere SCP need absolute path, so home path must be known
    try {
      home = getSshConnection().execAndWaitCommandNoBr("echo", "~");
    } catch (KurentoException e) {
      log.error("Exception reading remote home " + e.getClass()
          + " ... returning default home value: ~");
      home = "~";
    }
  }
  return home;
}
 
Example #29
Source File: SshConnection.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public void scp(String origFile, String targetFile) {
  log.debug("Copying local file: {} to remote file: {} (in host {})", origFile, targetFile, host);

  OverthereFile motd = connection.getFile(targetFile);
  OutputStream w = motd.getOutputStream();

  try {
    byte[] origBytes = Files.readAllBytes(Paths.get(origFile));
    w.write(origBytes);
    w.close();
  } catch (IOException e) {
    throw new KurentoException("Exception in SCP " + origFile + " " + targetFile, e);
  }

}
 
Example #30
Source File: KmsService.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void createKurentoConf() {
  Map<String, Object> data = new HashMap<String, Object>();
  try {
    URI wsAsUri = new URI(wsUri);
    int port = wsAsUri.getPort();
    String path = wsAsUri.getPath();
    data.put("wsPort", String.valueOf(port));
    data.put("wsPath", path.substring(1));
    data.put("registrar", registrarUri);
    data.put("registrarLocalAddress", registrarLocalAddress);

  } catch (URISyntaxException e) {
    throw new KurentoException("Invalid ws uri: " + wsUri);
  }
  data.put("gstPlugins", getGstPlugins());
  data.put("debugOptions", getDebugOptions());
  data.put("serverCommand", getServerCommand());
  data.put("workspace", getKmsLogPath());

  Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
  cfg.setClassForTemplateLoading(this.getClass(), "/templates/");

  createFileFromTemplate(cfg, data, "kurento.conf.json");
  createFileFromTemplate(cfg, data, "kurento.sh");

  Shell.runAndWait("chmod", "+x", workspace + File.separator + "kurento.sh");
}