List of usage examples for java.io IOException getCause
public synchronized Throwable getCause()
From source file:com.freedomotic.environment.impl.EnvironmentRepositoryImpl.java
/** * * @param folder// w w w . j a v a 2 s .c om * @throws RepositoryException */ @RequiresPermissions("environments:save") @Override public void saveEnvironmentsToFolder(File folder) throws RepositoryException { if (environments.isEmpty()) { LOG.warn("There is no environment to persist. Folder \"{}\" will not be altered", folder.getAbsolutePath()); return; } if (folder.exists() && !folder.isDirectory()) { throw new RepositoryException( "\"" + folder.getAbsoluteFile() + "\" is not a valid environment folder. Skipped"); } try { for (EnvironmentLogic environment : environments) { String uuid = environment.getPojo().getUUID(); if ((uuid == null) || uuid.isEmpty()) { environment.getPojo().setUUID(UUID.randomUUID().toString()); } String fileName = environment.getPojo().getUUID() + ENVIRONMENT_FILE_EXTENSION; save(environment, new File(folder + "/" + fileName)); } } catch (IOException e) { throw new RepositoryException(e.getCause()); } // save environment's things if (appConfig.getBooleanProperty("KEY_OVERRIDE_OBJECTS_ON_EXIT", false)) { try { thingsRepository.saveAll(findAll().get(0).getObjectFolder()); } catch (RepositoryException ex) { LOG.error("Cannot save objects into \"{}\"", findAll().get(0).getObjectFolder().getAbsolutePath(), Freedomotic.getStackTraceInfo(ex)); } } }
From source file:com.lunabeat.dooper.HadoopCluster.java
/** * * @param host/*from w ww . j a v a2 s. co m*/ * @param command * @return * @throws CmdException */ public CmdSessionResult remoteCommand(ClusterInstance host, String command) throws CmdException { try { Connection conn = new Connection(host.getInstance().getPublicDnsName()); conn.connect(); File keyfile = new File(_config.get(ClusterConfig.KEYPAIR_FILE_KEY)); boolean isAuthenticated = conn.authenticateWithPublicKey(_config.get(ClusterConfig.USERNAME_KEY), keyfile, BLANK); if (!isAuthenticated) { throw new CmdException("Could not authenticate.", host); } Session session = conn.openSession(); LOGGER.info("EXEC '" + command + "' on instance: " + host.getInstance().getInstanceId()); session.execCommand(command); InputStream outStrm = new StreamGobbler(session.getStdout()); InputStream errStrm = new StreamGobbler(session.getStderr()); BufferedReader stdoutRdr = new BufferedReader(new InputStreamReader(outStrm)); BufferedReader stderrRdr = new BufferedReader(new InputStreamReader(errStrm)); StringBuilder sb = new StringBuilder(); String stdout; while ((stdout = stdoutRdr.readLine()) != null) { sb.append(stdout).append("\n"); } stdout = sb.toString(); sb = new StringBuilder(); String stderr; while ((stderr = stderrRdr.readLine()) != null) { sb.append(stderr).append("\n"); } stderr = sb.toString(); conn.close(); conn = null; return new CmdSessionResult(host, session.getExitStatus(), stdout, stderr); } catch (IOException e) { throw new CmdException(e.getMessage(), e.getCause(), host); } }
From source file:io.openvidu.java.client.OpenVidu.java
/** * Deletes a recording. The recording must have status * {@link io.openvidu.java.client.Recording.Status#stopped} or * {@link io.openvidu.java.client.Recording.Status#available} * * @param recordingId The id property of the recording you want to delete * /*ww w . j a va 2 s .c o m*/ * @throws OpenViduJavaClientException * @throws OpenViduHttpException Value returned from * {@link io.openvidu.java.client.OpenViduHttpException#getStatus()} * <ul> * <li><code>404</code>: no recording exists * for the passed <i>recordingId</i></li> * <li><code>409</code>: the recording has * <i>started</i> status. Stop it before * deletion</li> * </ul> */ public void deleteRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException { HttpDelete request = new HttpDelete(OpenVidu.urlOpenViduServer + API_RECORDINGS + "/" + recordingId); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e) { throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if (!(statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:io.openvidu.java.client.OpenVidu.java
/** * Gets an existing recording/* w w w . j av a 2 s . c o m*/ * * @param recordingId The id property of the recording you want to retrieve * * @throws OpenViduJavaClientException * @throws OpenViduHttpException Value returned from * {@link io.openvidu.java.client.OpenViduHttpException#getStatus()} * <ul> * <li><code>404</code>: no recording exists * for the passed <i>recordingId</i></li> * </ul> */ public Recording getRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException { HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_RECORDINGS + "/" + recordingId); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e) { throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { return new Recording(httpResponseToJson(response)); } else { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java
/** * Decrypts the given input stream into the given output stream. *//* ww w .j av a 2s . c om*/ protected void decrypt(InputStream in, OutputStream out) throws IOException { byte[] magic = new byte[FILE_MAGIC.length]; IOUtils.read(in, magic); if (!Arrays.equals(magic, FILE_MAGIC)) { throw new IOException("Invalid file (bad magic)"); } DataInputStream data = new DataInputStream(in); byte magicvers = data.readByte(); if (magicvers != FILE_VERSION_1) { throw new IOException("Invalid file (bad version)"); } byte usepb = data.readByte(); if (usepb == USE_PBKDF2) { if (!usePBKDF2) { throw new NuxeoException("File requires PBKDF2 password"); } } else if (usepb == USE_KEYSTORE) { if (usePBKDF2) { throw new NuxeoException("File requires keystore"); } } else { throw new IOException("Invalid file (bad use)"); } try { // secret key Key secret; if (usePBKDF2) { // read salt first int saltLen = data.readInt(); if (saltLen <= 0 || saltLen > MAX_SALT_LEN) { throw new NuxeoException("Invalid salt length: " + saltLen); } byte[] salt = new byte[saltLen]; data.read(salt, 0, saltLen); secret = generateSecretKey(salt); } else { secret = getSecretKey(); } // read IV int ivLen = data.readInt(); if (ivLen <= 0 || ivLen > MAX_IV_LEN) { throw new NuxeoException("Invalid IV length: " + ivLen); } byte[] iv = new byte[ivLen]; data.read(iv, 0, ivLen); // cipher Cipher cipher; cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); // read the encrypted data try (InputStream cipherIn = new CipherInputStream(in, cipher)) { IOUtils.copy(cipherIn, out); } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof BadPaddingException) { throw new NuxeoException(cause.getMessage(), e); } } } catch (GeneralSecurityException e) { throw new NuxeoException(e); } }
From source file:org.nuxeo.github.Analyzer.java
protected void fillAndSyncDevMaps() throws IOException { // Fill missing values for known developers (with login) for (Developer dev : developersByLogin.values()) { if (!dev.isComplete()) { User nxDev = nxDevelopersByLogin.get(dev.getLogin()); if (nxDev != null) { dev.set(nxDev);/*from w w w . ja va2s . com*/ dev.setCompany("Nuxeo"); } } if (!dev.isComplete()) { try { // TODO: use a cache dev.set(userService.getUser(dev.getLogin())); } catch (IOException e) { if (e.getCause() instanceof JsonSyntaxException) { // ignore } else { throw e; } } } if (dev.getName() != null) { Developer removed = developersByName.remove(dev.getName()); if (removed != null) { dev.updateWith(removed); } } if (findEmail(dev) && dev.getCompany() == null) { if (CollectionUtils.exists(dev.getEmails(), new NuxeoEmailPredicate())) { dev.setCompany("Nuxeo (ex?)"); } } } // Look for unknown developers' email in commits for (Developer dev : developersByName.values()) { if (findEmail(dev) && dev.getCompany() == null) { if (CollectionUtils.exists(dev.getEmails(), new NuxeoEmailPredicate())) { dev.setCompany("Nuxeo (ex?)"); } } } // Merge developersByName into developersByLogin when an email matches for (Iterator<Entry<String, Developer>> it = developersByName.entrySet().iterator(); it.hasNext();) { Developer dev = it.next().getValue(); if (dev.getEmails().isEmpty()) { log.warn("Couldn't find email for " + dev); continue; } for (Developer devWithLogin : developersByLogin.values()) { if (!CollectionUtils.intersection(devWithLogin.getEmails(), dev.getEmails()).isEmpty() || devWithLogin.getLogin().equals(dev.getName())) { devWithLogin.updateWith(dev); it.remove(); break; } } } // Update allDevelopersByName allDevelopersByName.putAll(developersByName); for (Developer dev : developersByLogin.values()) { if (StringUtils.isNotEmpty(dev.getName())) { allDevelopersByName.put(dev.getName(), dev); } } }
From source file:org.opencastproject.distribution.hydrant.HydrantDistributionService.java
/** * Distributes the mediapackage's element to the location that is returned by the concrete implementation. In * addition, a representation of the distributed element is added to the mediapackage. * /* ww w . j a v a2s . c om*/ * @see org.opencastproject.distribution.api.DistributionService#distribute(String, MediaPackageElement) */ protected MediaPackageElement distribute(Job job, MediaPackage mediapackage, String elementId) throws DistributionException { if (mediapackage == null) throw new IllegalArgumentException("Mediapackage must be specified"); if (elementId == null) throw new IllegalArgumentException("Element ID must be specified"); String mediaPackageId = mediapackage.getIdentifier().compact(); MediaPackageElement element = mediapackage.getElementById(elementId); // Make sure the element exists if (mediapackage.getElementById(elementId) == null) throw new IllegalStateException("No element " + elementId + " found in mediapackage"); try { // The hydrant server only supports tracks if (!(element instanceof Track)) { return null; } String parentpid = mediapackage.getTitle(); if (parentpid == null) { throw new DistributionException("Could not find Hydrant pid in mediapackage."); } logger.trace("Found parent pid: {}", parentpid); try { String url = UrlSupport.concat(new String[] { hydrantUrl, "derivatives" }); MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(mgr); Credentials defaultcreds = new UsernamePasswordCredentials(hydrantAdminUsername, hydrantAdminPassword); client.getState().setCredentials(AuthScope.ANY, defaultcreds); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(url); post.setDoAuthentication(true); Part[] parts = { new StringPart("stream_url", element.getURI().toString()), new StringPart("master", parentpid), }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = client.executeMethod(post); logger.debug("Got status: " + status); logger.trace("Got response body: " + post.getResponseBodyAsString()); } catch (IOException e) { logger.debug("Exception distributing to Hydrant: " + e.getCause()); throw new DistributionException("Error distributing to Hydrant instance", e); } logger.info("Distributed {} to hydrant", elementId); // Create a representation of the distributed file in the mediapackage MediaPackageElement distributedElement = (MediaPackageElement) element.clone(); //TODO Create and set a valid distribution URI /* try { distributedElement.setURI(getDistributionUri(mediaPackageId, element)); } catch (URISyntaxException e) { throw new DistributionException("Distributed element produces an invalid URI", e); } */ distributedElement.setIdentifier(null); logger.info("Finished distribution of {}", element); return distributedElement; } catch (Exception e) { logger.warn("Error distributing " + element, e); if (e instanceof DistributionException) { throw (DistributionException) e; } else { throw new DistributionException(e); } } }
From source file:io.openvidu.java.client.Session.java
/** * Gracefully closes the Session: unpublishes all streams and evicts every * participant//from www. j a v a 2 s.c o m * * @throws OpenViduJavaClientException * @throws OpenViduHttpException */ public void close() throws OpenViduJavaClientException, OpenViduHttpException { HttpDelete request = new HttpDelete( OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/" + this.sessionId); request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e) { throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode == org.apache.http.HttpStatus.SC_NO_CONTENT)) { OpenVidu.activeSessions.remove(this.sessionId); log.info("Session {} closed", this.sessionId); } else { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:io.openvidu.java.client.OpenVidu.java
/** * Lists all existing recordings/*from w ww . j a v a 2 s. co m*/ * * @return A {@link java.util.List} with all existing recordings * * @throws OpenViduJavaClientException * @throws OpenViduHttpException */ @SuppressWarnings("unchecked") public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException { HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_RECORDINGS); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e) { throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { List<Recording> recordings = new ArrayList<>(); JSONObject json = httpResponseToJson(response); JSONArray array = (JSONArray) json.get("items"); array.forEach(item -> { recordings.add(new Recording((JSONObject) item)); }); return recordings; } else { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:io.openvidu.java.client.Session.java
/** * Updates every property of the Session with the current status it has in * OpenVidu Server. This is especially useful for getting the list of active * connections to the Session//from w w w. j a va 2s .c o m * ({@link io.openvidu.java.client.Session#getActiveConnections()}) and use * those values to call * {@link io.openvidu.java.client.Session#forceDisconnect(Connection)} or * {@link io.openvidu.java.client.Session#forceUnpublish(Publisher)}. <br> * * To update every Session object owned by OpenVidu object, call * {@link io.openvidu.java.client.OpenVidu#fetch()} * * @return true if the Session status has changed with respect to the server, * false if not. This applies to any property or sub-property of the * object * * @throws OpenViduHttpException * @throws OpenViduJavaClientException */ public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException { String beforeJSON = this.toJson(); HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + OpenVidu.API_SESSIONS + "/" + this.sessionId); request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); HttpResponse response; try { response = OpenVidu.httpClient.execute(request); } catch (IOException e) { throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); } try { int statusCode = response.getStatusLine().getStatusCode(); if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { this.resetSessionWithJson(httpResponseToJson(response)); String afterJSON = this.toJson(); boolean hasChanged = !beforeJSON.equals(afterJSON); log.info("Session info fetched for session '{}'. Any change: {}", this.sessionId, hasChanged); return hasChanged; } else { throw new OpenViduHttpException(statusCode); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }