List of usage examples for java.io IOException initCause
public synchronized Throwable initCause(Throwable cause)
From source file:ch.cyberduck.core.cf.CFSessionFederatedKeystone.java
@Override protected void login(final LoginController controller, final Credentials credentials) throws IOException { final FilesClientFederatedKeystone client = this.getClient(); client.setUserName(credentials.getUsername()); client.setPassword(credentials.getPassword()); try {/*from w w w .j a v a 2 s .co m*/ List<String> realms = (LinkedList<String>) client.getRealmList(); //call dialog String selectedRealm = controller.prompt("IdP Server", "Choose a IdP server:", "Servers", realms); if (selectedRealm.equals("")) { return; } String[] idpRequest = client.getIdPRequest(selectedRealm); String idpResponse = client.getIdPResponse(idpRequest[0], idpRequest[1]); String unscopedTokenJson = client.getUnscopedToken(idpResponse, selectedRealm); List<String> tenants = (LinkedList<String>) client.getTenantsName(); //call dialog String selectedTenant = controller.prompt("Tenants", "Choose a Tenant:", "Tenants", tenants); if (selectedTenant.equals("")) { return; } controller.prompt(selectedTenant); } catch (Exception e) { IOException failure = new IOException(); throw failure; } try { if (!client.login()) { this.message(Locale.localizedString("Login failed", "Credentials")); controller.fail(host.getProtocol(), credentials); this.login(); } } // catch (HttpException e) { IOException failure = new IOException(e.getMessage()); failure.initCause(e); throw failure; } }
From source file:hudson.remoting.Launcher.java
/** * Parses the connection arguments from JNLP file given in the URL. *//* ww w . j a v a 2 s .com*/ public List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException { while (true) { try { URLConnection con = slaveJnlpURL.openConnection(); if (con instanceof HttpURLConnection && slaveJnlpCredentials != null) { HttpURLConnection http = (HttpURLConnection) con; String userPassword = slaveJnlpCredentials; String encoding = new String(Base64.encodeBase64(userPassword.getBytes())); http.setRequestProperty("Authorization", "Basic " + encoding); } con.connect(); if (con instanceof HttpURLConnection) { HttpURLConnection http = (HttpURLConnection) con; if (http.getResponseCode() >= 400) // got the error code. report that (such as 401) throw new IOException("Failed to load " + slaveJnlpURL + ": " + http.getResponseCode() + " " + http.getResponseMessage()); } Document dom; // check if this URL points to a .jnlp file String contentType = con.getHeaderField("Content-Type"); if (contentType == null || !contentType.startsWith("application/x-java-jnlp-file")) { // load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with. try { dom = loadDom(slaveJnlpURL, con); } catch (SAXException e) { throw new IOException( slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType); } catch (IOException e) { throw new IOException( slaveJnlpURL + " doesn't look like a JNLP file; content type was " + contentType); } } else { dom = loadDom(slaveJnlpURL, con); } // exec into the JNLP launcher, to fetch the connection parameter through JNLP. NodeList argElements = dom.getElementsByTagName("argument"); List<String> jnlpArgs = new ArrayList<String>(); for (int i = 0; i < argElements.getLength(); i++) jnlpArgs.add(argElements.item(i).getTextContent()); if (slaveJnlpCredentials != null) { jnlpArgs.add("-credentials"); jnlpArgs.add(slaveJnlpCredentials); } // force a headless mode jnlpArgs.add("-headless"); return jnlpArgs; } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) { // invalid SSL certificate. One reason this happens is when the certificate is self-signed IOException x = new IOException( "Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check."); x.initCause(e); throw x; } else throw e; } catch (IOException e) { System.err.println("Failing to obtain " + slaveJnlpURL); e.printStackTrace(System.err); System.err.println("Waiting 10 seconds before retry"); Thread.sleep(10 * 1000); // retry } } }
From source file:ch.cyberduck.core.cf.CFPath.java
private ResponseOutputStream<String> write(final TransferStatus status, final String md5sum) throws IOException { final HashMap<String, String> metadata = new HashMap<String, String>(); // Default metadata for new files for (String m : Preferences.instance().getList("cf.metadata.default")) { if (StringUtils.isBlank(m)) { log.warn(String.format("Invalid header %s", m)); continue; }//from w w w . ja va2s .c o m if (!m.contains("=")) { log.warn(String.format("Invalid header %s", m)); continue; } int split = m.indexOf('='); String name = m.substring(0, split); if (StringUtils.isBlank(name)) { log.warn(String.format("Missing key in %s", m)); continue; } String value = m.substring(split + 1); if (StringUtils.isEmpty(value)) { log.warn(String.format("Missing value in %s", m)); continue; } metadata.put(name, value); } // Submit store call to background thread final DelayedHttpEntityCallable<String> command = new DelayedHttpEntityCallable<String>() { /** * * @return The ETag returned by the server for the uploaded object */ @Override public String call(AbstractHttpEntity entity) throws IOException { try { return CFPath.this.getSession().getClient().storeObjectAs(CFPath.this.getContainerName(), CFPath.this.getKey(), entity, metadata, md5sum); } catch (HttpException e) { IOException failure = new IOException(e.getMessage()); failure.initCause(e); throw failure; } } @Override public long getContentLength() { return status.getLength() - status.getCurrent(); } }; return this.write(command); }
From source file:org.onecmdb.core.utils.transform.TransformEngine.java
public Set<CiBean> generateInstances(MemoryBeanProvider beanSet, DataSet dataSet, IBeanProvider beanProvider) throws IOException { Set<CiBean> beans = new HashSet<CiBean>(); dataSet.setReport(this.report); if (dataSet.getInstanceSelector() instanceof ForwardInstanceSelector) { for (IAttributeSelector aSelector : dataSet.getAttributeSelector()) { IDataSource source = dataSet.getDataSource(); if (aSelector instanceof ComplexAttributeSelector) { DataSet forwardDataSet = ((ComplexAttributeSelector) aSelector).getDataSet(); forwardDataSet.setDataSource(source); Set<CiBean> fBeans = generateInstances(beanSet, forwardDataSet, beanProvider); beans.addAll(fBeans);/*from w w w .j a va2 s . c o m*/ source.reset(); } } } else { for (IInstance row : dataSet.getInstances()) { try { CiBean bean = generateInstance(beanSet, row, beanProvider); beans.add(bean); HashSet<CiBean> dsBeans = dataSetMap.get(dataSet.getName()); if (dsBeans == null) { dsBeans = new HashSet<CiBean>(); dataSetMap.put(dataSet.getName(), dsBeans); } dsBeans.add(bean); } catch (Throwable t) { IOException e = new IOException("Problem parsing row[" + row.getLocalID() + "]"); e.initCause(t); throw e; } } } return (beans); }
From source file:org.apache.jackrabbit.core.fs.db.OracleFileSystem.java
/** * {@inheritDoc}/*from w ww . ja v a 2 s .c om*/ */ public RandomAccessOutputStream getRandomAccessOutputStream(final String filePath) throws FileSystemException, UnsupportedOperationException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(filePath); final String parentDir = FileSystemPathUtil.getParentDir(filePath); final String name = FileSystemPathUtil.getName(filePath); if (!isFolder(parentDir)) { throw new FileSystemException("path not found: " + parentDir); } if (isFolder(filePath)) { throw new FileSystemException("path denotes folder: " + filePath); } try { TransientFileFactory fileFactory = TransientFileFactory.getInstance(); final File tmpFile = fileFactory.createTransientFile("bin", null, null); // @todo FIXME use java.sql.Blob if (isFile(filePath)) { // file entry exists, spool contents to temp file first InputStream in = getInputStream(filePath); OutputStream out = new FileOutputStream(tmpFile); try { IOUtils.copy(in, out); } finally { out.close(); in.close(); } } return new RandomAccessOutputStream() { private final RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw"); public void close() throws IOException { raf.close(); InputStream in = null; Blob blob = null; try { if (isFile(filePath)) { synchronized (updateDataSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); blob = createTemporaryBlob(in); executeStmt(updateDataSQL, new Object[] { blob, new Long(System.currentTimeMillis()), new Long(length), parentDir, name }); } } else { synchronized (insertFileSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); blob = createTemporaryBlob(in); executeStmt(insertFileSQL, new Object[] { parentDir, name, blob, new Long(System.currentTimeMillis()), new Long(length) }); } } } catch (Exception e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } finally { if (blob != null) { try { freeTemporaryBlob(blob); } catch (Exception e1) { } } IOUtils.closeQuietly(in); // temp file can now safely be removed tmpFile.delete(); } } public void seek(long position) throws IOException { raf.seek(position); } public void write(int b) throws IOException { raf.write(b); } public void flush() /*throws IOException*/ { // nop } public void write(byte[] b) throws IOException { raf.write(b); } public void write(byte[] b, int off, int len) throws IOException { raf.write(b, off, len); } }; } catch (Exception e) { String msg = "failed to open output stream to file: " + filePath; log.error(msg, e); throw new FileSystemException(msg, e); } }
From source file:org.pixmob.freemobile.netstat.SyncService.java
private void run(Intent intent, final SQLiteDatabase db) throws Exception { final long now = dateAtMidnight(System.currentTimeMillis()); Log.i(TAG, "Initializing statistics before uploading"); final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15); final Set<Long> uploadedStats = new HashSet<Long>(15); final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS; // Get pending uploads. Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" }, "stat_timestamp>=? AND stat_timestamp<?", new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null); try {/*from w ww .j a va2 s . c o m*/ while (c.moveToNext()) { final long d = c.getLong(0); final int sync = c.getInt(3); if (SYNC_UPLOADED == sync) { uploadedStats.add(d); } else if (SYNC_PENDING == sync) { final DailyStat s = new DailyStat(); s.orange = c.getInt(1); s.freeMobile = c.getInt(2); stats.put(d, s); } } } finally { c.close(); } // Compute missing uploads. final ContentValues cv = new ContentValues(); db.beginTransaction(); try { for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) { if (stats.get(d) == null && !uploadedStats.contains(d)) { final DailyStat s = computeDailyStat(d); cv.put("stat_timestamp", d); cv.put("orange", s.orange); cv.put("free_mobile", s.freeMobile); cv.put("sync", SYNC_PENDING); db.insertOrThrow("daily_stat", null, cv); stats.put(d, s); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } // Delete old statistics. if (DEBUG) { Log.d(TAG, "Cleaning up upload database"); } db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) }); // Check if there are any statistics to upload. final int statsLen = stats.size(); if (statsLen == 0) { Log.i(TAG, "Nothing to upload"); return; } // Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl( "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) { Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url); } final byte[] rawJson = json.toString().getBytes("UTF-8"); try { client.post(url).content(rawJson, "application/json") .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND) .to(new HttpResponseHandler() { @Override public void onResponse(HttpResponse response) throws Exception { final int sc = response.getStatusCode(); if (HttpURLConnection.HTTP_NOT_FOUND == sc) { // Check if the device has just been // registered. if (deviceWasRegistered) { throw new IOException("Failed to upload statistics"); } else { // Got 404: the device does not exist. // We need to register this device. registerDevice(deviceId); // Restart this service. startService(new Intent(getApplicationContext(), SyncService.class) .putExtra(EXTRA_DEVICE_REG, true)); } } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat", cv, "stat_timestamp=?", new String[] { String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } }
From source file:dk.deck.remoteconsole.SshRemoteConsole.java
/** * Uploads a file to the server using the protocol from scp -t * * @param lfile URL with the file to upload * @param rfile Text location relative to home directory * @param command the scp -t command (with or without sudo) * @throws IOException//from w w w . j a v a 2 s . co m */ @Override public void uploadFile(URL lfile, String rfile, String command) throws IOException { try { log.debug("Upload file " + lfile.getFile() + " to " + rfile); boolean connect = (session == null || !session.isConnected()); if (connect) { connect(); } // exec 'scp -t rfile' remotely Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); int ack = checkAck(in); if (ack != 0) { throw new IllegalStateException("checkAck failed value " + ack); } //out.flush(); InputStream fis = lfile.openStream(); // Messure length long filesize = StreamUtil.messureContentLenth(fis); fis = lfile.openStream(); command = "C0644 " + filesize + " "; if (lfile.getFile().lastIndexOf('/') > 0) { command += lfile.getFile().substring(lfile.getFile().lastIndexOf('/') + 1); } else { command += lfile.getFile(); } command += "\n"; out.write(command.getBytes()); out.flush(); ack = checkAck(in); if (ack != 0) { throw new IllegalStateException("checkAck failed value " + ack); } // send a content of lfile long written = 0; long percent = 0; long lastpercent = -1; byte[] buf = new byte[1024]; while (true) { int len = fis.read(buf, 0, buf.length); if (len <= 0) { break; } written += len; percent = ((written * 100 / filesize)); if (lastpercent != percent) { lastpercent = percent; log.trace("written " + written + "/" + filesize + " bytes " + percent + "%"); } out.write(buf, 0, len); //out.flush(); } fis.close(); fis = null; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); ack = checkAck(in); if (ack != 0) { throw new IllegalStateException("checkAck failed value " + ack); } out.close(); channel.disconnect(); if (connect) { disconnect(); } } catch (JSchException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } }
From source file:org.apache.cassandra.hadoop.cql3.CqlRecordReader.java
public boolean nextKeyValue() throws IOException { if (!rowIterator.hasNext()) { logger.trace("Finished scanning {} rows (estimate was: {})", rowIterator.totalRead, totalRowCount); return false; }// w w w . j a v a2 s .com try { currentRow = rowIterator.next(); } catch (Exception e) { // throw it as IOException, so client can catch it and handle it at client side IOException ioe = new IOException(e.getMessage()); ioe.initCause(ioe.getCause()); throw ioe; } return true; }
From source file:dk.deck.remoteconsole.SshRemoteConsole.java
/** * Executes a command on the remote server, via a ssh channel. * * Captures stdout in the result, while stderr is only logged * * @param command The unix command to execute * @param failOnExitNotZero throw an exception if the unix command does not * return zero (0)//from w w w. j a va 2s . c o m * @param disconnectAfterMillis disconnect after a periods (this is usefull * when starting deamons) * @param disconnectAfterContent disconnect after this string has appeard * in output (this is usefull when starting deamons), can be used in * combination * @return a CommandResult entity with the output and errorcode. * @throws IOException on communication errors * @throws IllegalStateException if the exit code check is on * @todo Cleanup and split up into several methods */ public CommandResult executeCommandResult(String command, boolean failOnExitNotZero, long disconnectAfterMillis, String disconnectAfterContent, Writer liveOutput) throws IOException { try { CommandResult result = new CommandResult(); SshRemoteConsole.log.debug("Executing > " + command); boolean connect = session == null || !session.isConnected(); if (connect) { connect(); } try { Channel channel = session.openChannel("exec"); // shell ((ChannelExec) channel).setCommand(command); if (enablePty) { ((ChannelExec) channel).setPty(true); } InputStream error = ((ChannelExec) channel).getErrStream(); // channel.setOutputStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); long start = System.currentTimeMillis(); boolean contentReached = true; if (disconnectAfterContent != null && !disconnectAfterContent.equals("")) { contentReached = false; } StringBuilder output = new StringBuilder(); StringBuilder errorOutput = new StringBuilder(); try { byte[] inTmp = new byte[1024]; byte[] errorTmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(inTmp, 0, 1024); if (i < 0) { break; } output(new String(inTmp, 0, i), liveOutput, output); log.trace(new String(inTmp, 0, i)); } while (error.available() > 0) { int i = error.read(errorTmp, 0, 1024); if (i < 0) { break; } if (output.toString().length() < MAX_CONTENT_LENGTH) { errorOutput.append(new String(errorTmp, 0, i)); } log.debug("ERROR: " + new String(errorTmp, 0, i)); } if (channel.isClosed()) { result.setExitCode(channel.getExitStatus()); if (failOnExitNotZero && channel.getExitStatus() != 0) { log.debug("exit-status: " + channel.getExitStatus()); throw new IllegalStateException( "Exitstatus was: " + channel.getExitStatus() + " output: " + output.toString() + " error-output: " + errorOutput.toString()); } break; } if (disconnectAfterMillis > 0 && contentReached) { long now = System.currentTimeMillis(); if (now - start > disconnectAfterMillis) { log.trace("exiting before command is finished after: " + ((now - start) / 1000) + " seconds."); break; } } // TODO fix possible flaw that clashes with MAX_CONTENT_LENGTH if (!contentReached && (output.toString().contains(disconnectAfterContent) || errorOutput.toString().contains(disconnectAfterContent))) { contentReached = true; start = System.currentTimeMillis(); if (disconnectAfterMillis == 0) { break; } } try { Thread.sleep(1000); } catch (InterruptedException ex) { log.warn("Interrupted in sleep", ex); } } } finally { channel.disconnect(); } result.setOutput(output.toString()); result.setErrorOutput(errorOutput.toString()); } finally { if (connect) { disconnect(); } } return result; } catch (JSchException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } }
From source file:dk.deck.remoteconsole.SshRemoteConsole.java
@Override public void downloadFile(String rfile, OutputStream finalOutput) throws IOException { try {//from w w w .ja va 2 s .c o m log.debug("Download file " + rfile); String command = "scp -f " + rfile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); while (true) { int c = checkAck(in); if (c != 'C') { break; } // read '0644 ' in.read(buf, 0, 5); long filesize = 0L; while (true) { if (in.read(buf, 0, 1) < 0) { // error break; } if (buf[0] == ' ') { break; } filesize = filesize * 10L + (long) (buf[0] - '0'); } String file = null; for (int i = 0;; i++) { in.read(buf, i, 1); if (buf[i] == (byte) 0x0a) { file = new String(buf, 0, i); break; } } //System.out.println("filesize="+filesize+", file="+file); // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); long readed = 0; long percent = 0; long lastpercent = -1; long totalFileSize = filesize; // read a content of lfile int len; while (true) { if (buf.length < filesize) { len = buf.length; } else { len = (int) filesize; } len = in.read(buf, 0, len); if (len < 0) { // error break; } readed += len; percent = ((readed * 100 / filesize)); if (lastpercent != percent) { lastpercent = percent; log.trace("reading " + readed + "/" + totalFileSize + " bytes " + percent + "%"); } finalOutput.write(buf, 0, len); filesize -= len; if (filesize == 0L) { break; } } finalOutput.close(); if (checkAck(in) != 0) { System.exit(0); } // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); } } catch (JSchException ex) { IOException ioe = new IOException(ex.getMessage()); ioe.initCause(ex); throw ioe; } }