List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:eu.operando.operandoapp.OperandoProxyStatus.java
private void DownloadInitialSettings() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (prefs.getBoolean("firstTime", true) && haveNetworkConnection()) { // run one time code here final File tmp = new File(getFilesDir(), "domainfilters_" + System.currentTimeMillis()); try {/*from w ww . ja va 2 s . c o m*/ new DownloadTask(MainActivity.this, new URL(DatabaseHelper.serverUrl + "/blocked_urls"), tmp, new DownloadTask.Listener() { @Override public void onCompleted() { new AsyncTask<Void, Void, Integer>() { ProgressDialog dialog; @Override protected void onPreExecute() { dialog = ProgressDialog.show(MainActivity.this, null, "Applying up to date settings for your convenience, to keep you safe.\nThis might take while..."); dialog.setCancelable(false); } @Override protected Integer doInBackground(Void... params) { new DatabaseHelper(MainActivity.this) .deleteDomainFilterFile(DatabaseHelper.serverUrl); Integer count = 0; BufferedReader br = null; try { br = new BufferedReader(new FileReader(tmp)); String line; while ((line = br.readLine()) != null) { int hash = line.indexOf('#'); if (hash >= 0) line = line.substring(0, hash); line = line.trim(); try { String blockedDomain = line; if (blockedDomain.equals("local") || StringUtils.containsAny(blockedDomain, "localhost", "127.0.0.1", "broadcasthost")) continue; DomainFilter domainFilter = new DomainFilter(); domainFilter.setContent(blockedDomain); domainFilter.setSource(DatabaseHelper.serverUrl); domainFilter.setIsWildcard(false); new DatabaseHelper(MainActivity.this) .createDomainFilter(domainFilter); count++; } catch (Exception e) { Log.i("Error", "Invalid hosts file line: " + line); } } Log.i("Error", count + " entries read"); } catch (IOException ex) { Log.e("Error", ex.toString() + "\n" + Log.getStackTraceString(ex)); } finally { if (br != null) try { br.close(); } catch (IOException exex) { Log.e("Error", exex.toString() + "\n" + Log.getStackTraceString(exex)); } } return count; } @Override protected void onPostExecute(Integer count) { dialog.dismiss(); // mark first time has runned. SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("firstTime", false); editor.commit(); } }.execute(); } @Override public void onCancelled() { if (tmp.exists()) tmp.delete(); } @Override public void onException(Throwable ex) { if (tmp.exists()) tmp.delete(); ex.printStackTrace(); Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }).execute(); } catch (MalformedURLException mue) { mue.getMessage(); } } else if (!haveNetworkConnection()) { Toast.makeText(MainActivity.this, "You don't seem to have a working Internet Connection.", Toast.LENGTH_LONG).show(); } }
From source file:architecture.ee.plugin.impl.PluginManagerImpl.java
public void processSpringConfigs(List<String> springPaths) { if (ApplicationHelper.isSetupComplete()) { pluginDao = getSpringUnManagedDao(); if (!pluginDao.doesPluginTableExist()) { log.warn(//from ww w . java 2s . c om "Plugin table does not exist, this is probably do to an upgrade task not being completed yet."); } else { List<PluginEntityObject> pluginBeans = getPluginBeans(); for (PluginEntityObject bean : pluginBeans) { File currentDir = new File(pluginDirectory, bean.getName()); if (currentDir.exists()) { File springFile = new File(currentDir, "spring.xml"); if (springFile.exists()) try { log.info( String.format("Adding spring.xml for plugin %s to the main spring context.", new Object[] { currentDir.getName() })); springPaths.add(springFile.toURI().toURL().toString()); } catch (MalformedURLException e) { log.error(e.getMessage(), e); } else if (log.isDebugEnabled()) log.debug(String.format("Plugin %s is restartable but does not have a spring config", new Object[] { currentDir.getName() })); } else { log.warn(String.format( "Could not find the local directory for plugin %s. An additional restart will be needed forthe plugin to load correctly", new Object[] { currentDir.getName() })); } } if (Boolean.parseBoolean(System.getProperty("jive.devMode", "false"))) { if (log.isDebugEnabled()) log.debug("Adding dev plugins spring configurations."); List<String> paths = PluginUtils.getDevPluginPaths(); for (String path : paths) { File dir = new File(path); if (dir.exists()) { File springConf = new File(dir, "spring.xml"); if (springConf.exists()) try { springPaths.add(springConf.toURI().toURL().toString()); } catch (MalformedURLException e) { log.error(e.getMessage(), e); } } } } } } }
From source file:com.ichi2.anki.SyncClient.java
public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) { URL url;// w ww.j a va 2s.c o m try { Log.i(AnkiDroidApp.TAG, "Fullup"); url = new URL(AnkiDroidProxy.SYNC_URL + "fullup"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Charset", "UTF-8"); // conn.setRequestProperty("Content-Length", "8494662"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MIME_BOUNDARY); conn.setRequestProperty("Host", AnkiDroidProxy.SYNC_HOST); DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); Log.i(AnkiDroidApp.TAG, "Pass"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"p\"" + END + END + password + END); Log.i(AnkiDroidApp.TAG, "User"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"u\"" + END + END + username + END); Log.i(AnkiDroidApp.TAG, "DeckName"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"d\"" + END + END + deckName + END); Log.i(AnkiDroidApp.TAG, "Deck"); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END); ds.writeBytes("Content-Disposition: form-data; name=\"deck\";filename=\"deck\"" + END); ds.writeBytes("Content-Type: application/octet-stream" + END); ds.writeBytes(END); FileInputStream fStream = new FileInputStream(deckPath); byte[] buffer = new byte[Utils.CHUNK_SIZE]; int length = -1; Deflater deflater = new Deflater(Deflater.BEST_SPEED); DeflaterOutputStream dos = new DeflaterOutputStream(ds, deflater); Log.i(AnkiDroidApp.TAG, "Writing buffer..."); while ((length = fStream.read(buffer)) != -1) { dos.write(buffer, 0, length); Log.i(AnkiDroidApp.TAG, "Length = " + length); } dos.finish(); fStream.close(); ds.writeBytes(END); ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + TWO_HYPHENS + END); Log.i(AnkiDroidApp.TAG, "Closing streams..."); ds.flush(); ds.close(); // Ensure we got the HTTP 200 response code int responseCode = conn.getResponseCode(); if (responseCode != 200) { Log.i(AnkiDroidApp.TAG, "Response code = " + responseCode); // throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, // url)); } else { Log.i(AnkiDroidApp.TAG, "Response code = 200"); } // Read the response InputStream is = conn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int bytesRead; while ((bytesRead = is.read(bytes)) != -1) { baos.write(bytes, 0, bytesRead); } byte[] bytesReceived = baos.toByteArray(); baos.close(); is.close(); String response = new String(bytesReceived); Log.i(AnkiDroidApp.TAG, "Finished!"); } catch (MalformedURLException e) { Log.i(AnkiDroidApp.TAG, "MalformedURLException = " + e.getMessage()); } catch (IOException e) { Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage()); } }
From source file:gov.nih.nci.caintegrator.application.download.caarray.CaArrayFileDownloadManager.java
protected CaArrayFileDownloadManager(String caarrayUrl, String username, String password, String inputDirectory, String outputZipDirectory, String directoryInZip) throws MalformedURLException, LoginException, ServerConnectionException { try {/*from ww w . ja v a 2 s . c o m*/ this.caarrayUrl = new URL(caarrayUrl); } catch (MalformedURLException e) { reportError("URL was invalid: " + caarrayUrl, e); throw e; } if (username != null) this.username = username.trim(); if (password != null) this.password = password.trim(); if (inputDirectory != null) this.inputDirectory = inputDirectory.trim(); if (outputZipDirectory != null) this.outputZipDirectory = outputZipDirectory.trim(); //try { try { connectToCaArrayServer(); } catch (LoginException e) { reportError(e.getMessage(), e); e.printStackTrace(System.err); throw e; } catch (ServerConnectionException e) { reportError(e.getMessage(), e); e.printStackTrace(System.err); throw e; } importer = new CaArrayFileDownloader(inputDirectory, outputZipDirectory, directoryInZip); }
From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java
private void fetchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fetchButtonActionPerformed try {//from w ww . j a v a 2s . co m Request request = _requestPanel.getRequest(); if (request == null) { _logger.warning("Request was null in fetch request"); return; } String name = nameTextField.getText(); String regex = regexTextField.getText(); int count = ((Integer) sampleSpinner.getValue()).intValue(); try { _sa.fetch(request, name, regex, count); } catch (PatternSyntaxException pse) { JOptionPane.showMessageDialog(this, pse.getMessage(), "Pattern Syntax Exception", JOptionPane.WARNING_MESSAGE); } } catch (MalformedURLException mue) { JOptionPane.showMessageDialog(this, new String[] { "The URL requested is malformed", mue.getMessage() }, "Malformed URL", JOptionPane.ERROR_MESSAGE); } catch (ParseException pe) { JOptionPane.showMessageDialog(this, new String[] { "The request is malformed", pe.getMessage() }, "Malformed Request", JOptionPane.ERROR_MESSAGE); } }
From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String postResponse;//from w w w . ja va 2s .co m String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = MIntel.getInstance().getHttpContext(); HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) { return mResults; } publishProgress(c.getPosition() + 1, c.getCount()); String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } ContentValues cv = new ContentValues(); URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(final Long... values) { mResults = new HashMap<String, String>(); String postResponse;//w ww. j ava 2 s. co m String selection = BaseColumns._ID + "=?"; final String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + BaseColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. final HttpContext localContext = MIntel.getInstance().getHttpContext(); final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); final Map<URI, URI> uriRemap = new HashMap<URI, URI>(); final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) return mResults; publishProgress(c.getPosition() + 1, c.getCount()); final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String id = c.getString(c.getColumnIndex(BaseColumns._ID)); final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { final SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } final ContentValues cv = new ContentValues(); URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { final Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); final URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (final ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file final File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory final File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files final List<File> files = new ArrayList<File>(); for (final File f : allFiles) { final String fileName = f.getName(); final int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); final MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post final MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { final File f = files.get(j); final String fileName = f.getName(); final int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { final StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (final Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); final int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } final HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (final IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:net.di2e.ecdr.commons.CDRMetacard.java
@Override public byte[] getThumbnail() { byte[] thumbnail = null; // We can't call getData here because it will get in an endless loop because of the explicit checks in // getAttribute (for THUMBNAIL), so instead we check the values ourselves then try to pull from the link (on // demand)/*from w w w.j av a2s . c om*/ Attribute thumbnailAttribute = (wrappedMetacard != null) ? wrappedMetacard.getAttribute(THUMBNAIL) : map.get(THUMBNAIL); if (thumbnailAttribute == null || getAttributeValue(thumbnailAttribute, byte[].class) == null) { URI thumbnailURI = getThumbnailURL(); if (thumbnailURI != null) { try (InputStream in = thumbnailURI.toURL().openStream()) { thumbnail = IOUtils.toByteArray(in); setAttribute(new AttributeImpl(Metacard.THUMBNAIL, thumbnail)); } catch (MalformedURLException e) { LOGGER.warn("Cannot read thumbnail due to invalid thumbnail URL[" + thumbnailURI + "]: " + e.getMessage(), e); } catch (IOException e) { LOGGER.warn("Could not read thumbnail from remote URL[" + thumbnailURI + "] due to: " + e.getMessage(), e); } } } else { thumbnail = getAttributeValue(thumbnailAttribute, byte[].class); } return thumbnail; }
From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java
public void downloadFile(URL url, File outFile) throws IOException, EndUserException { URLConnection conn = null;/* w w w . j a v a 2s . c om*/ try { Map<String, String> cookies = isSecurityAware() ? ServerContext.getRequestOwner().getIdentityCookies() : null; conn = URLDownload.makeConnection(url, cookies); conn.setRequestProperty("Accept", "*/*"); URLDownload.getDataToFile(conn, outFile); } catch (MalformedURLException e) { LOGGER.error(e, "Bad URL"); throw makeException(e, "WISE Query Failed - bad url."); } catch (FailedRequestException e) { LOGGER.error(e, e.toString()); if (conn != null && conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int respCode = httpConn.getResponseCode(); String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode); throw new EndUserException("Search Failed: " + desc, e.getDetailMessage(), e); } else { throw makeException(e, "Query Failed - network error."); } } catch (IOException e) { if (conn != null && conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int respCode = httpConn.getResponseCode(); String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode); throw new EndUserException("Search Failed: " + desc, e.getMessage(), e); } else { throw makeException(e, "Query Failed - network error."); } } }