List of usage examples for java.net MalformedURLException toString
public String toString()
From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java
/** * Called by the Android system in response to a request to run the sync adapter. The work * required to read data from the network, parse it, and store it in the content provider is * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter * run on a background thread. For this reason, blocking I/O and other long-running tasks can be * run <em>in situ</em>, and you don't have to set up a separate thread for them. . * * <p>This is where we actually perform any work required to perform a sync. * {@link AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread, * so it is safe to peform blocking I/O here. * * <p>The syncResult argument allows you to pass information back to the method that triggered * the sync./*from w w w . j a va 2 s . c o m*/ */ @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { Log.d("SyncAdapter", "onPerformSync"); Log.i(TAG, "Beginning network synchronization"); try { final URL location = new URL(FEED_URL); InputStream stream = null; try { Log.i(TAG, "Streaming data from network: " + location); // stream = downloadUrl(location); // updateLocalFeedData(stream, syncResult); // TODO Auto-generated method stub prefs = mcontext.getSharedPreferences("com.roamprocess1.roaming4world", Context.MODE_PRIVATE); stored_user_mobile_no = "com.roamprocess1.roaming4world.user_mobile_no"; stored_user_country_code = "com.roamprocess1.roaming4world.user_country_code"; stored_user_bal = "com.roamprocess1.roaming4world.user_bal"; stored_min_call_credit = "com.roamprocess1.roaming4world.min_call_credit"; stored_server_ipaddress = "com.roamprocess1.roaming4world.server_ip"; signUpProcess = "com.roamprocess1.roaming4world.signUpProcess"; resultIntent = new Intent(mcontext, SipHome.class); mNotificationManager = (NotificationManager) mcontext .getSystemService(Context.NOTIFICATION_SERVICE); selfNumber = prefs.getString(stored_user_country_code, "") + prefs.getString(stored_user_mobile_no, ""); if (getConnectivityStatus(mcontext) != SipHome.TYPE_NOT_CONNECTED) { updateUserContacts(); updateUserImages(); updateOfflineMissedCalls(); } // Makes sure that the InputStream is closed after the app is // finished using it. } finally { // mcontext.startActivity(new Intent(mcontext , SipHome.class)); if (stream != null) { stream.close(); } } } catch (MalformedURLException e) { Log.wtf(TAG, "Feed URL is malformed", e); syncResult.stats.numParseExceptions++; return; } catch (IOException e) { Log.e(TAG, "Error reading from network: " + e.toString()); syncResult.stats.numIoExceptions++; return; } Log.i(TAG, "Network synchronization complete"); }
From source file:com.newrelic.agent.transport.DataSenderImpl.java
private ReadResult send(String method, String encoding, String uri, JSONStreamAware params, int timeoutInMillis)/* 857: */ throws Exception /* 858: */ {//from ww w .j a v a 2 s . co m /* 859: */ try /* 860: */ { /* 861:653 */ return connectAndSend(method, encoding, uri, params, timeoutInMillis); /* 862: */ } /* 863: */ catch (MalformedURLException e) /* 864: */ { /* 865:655 */ Agent.LOG.log(Level.SEVERE, "You have requested a connection to New Relic via a protocol which is unavailable in your runtime: {0}", new Object[] { e.toString() }); /* 866: */ /* 867: */ /* 868: */ /* 869:659 */ throw new ForceDisconnectException(e.toString()); /* 870: */ } /* 871: */ catch (SocketException e) /* 872: */ { /* 873:661 */ if ((e.getCause() instanceof NoSuchAlgorithmException)) /* 874: */ { /* 875:662 */ String msg = MessageFormat.format( "You have requested a connection to New Relic via an algorithm which is unavailable in your runtime: {0} This may also be indicative of a corrupted keystore or trust store on your server.", new Object[] { e.getCause().toString() }); /* 876: */ /* 877: */ /* 878:665 */ Agent.LOG.error(msg); /* 879: */ } /* 880: */ else /* 881: */ { /* 882:668 */ Agent.LOG.log(Level.INFO, "A socket exception was encountered while sending data to New Relic ({0}). Please check your network / proxy settings.", new Object[] { e.toString() }); /* 883:672 */ if (Agent.LOG.isLoggable(Level.FINE)) { /* 884:673 */ Agent.LOG.log(Level.FINE, "Error sending JSON({0}): {1}", new Object[] { method, DataSenderWriter.toJSONString(params) }); /* 885: */ } /* 886:676 */ Agent.LOG.log(Level.FINEST, e, e.toString(), new Object[0]); /* 887: */ } /* 888:678 */ throw e; /* 889: */ } /* 890: */ catch (HttpError e) /* 891: */ { /* 892:707 */ throw e; /* 893: */ } /* 894: */ catch (Exception e) /* 895: */ { /* 896:709 */ Agent.LOG.log(Level.INFO, "Remote {0} call failed : {1}.", new Object[] { method, e.toString() }); /* 897:710 */ if (Agent.LOG.isLoggable(Level.FINE)) { /* 898:711 */ Agent.LOG.log(Level.FINE, "Error sending JSON({0}): {1}", new Object[] { method, DataSenderWriter.toJSONString(params) }); /* 899: */ } /* 900:713 */ Agent.LOG.log(Level.FINEST, e, e.toString(), new Object[0]); /* 901:714 */ throw e; /* 902: */ } /* 903: */ }
From source file:org.apache.maven.plugin.resources.remote.ProcessRemoteResourcesMojo.java
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException { if (skip) {/* ww w.j av a 2 s. co m*/ getLog().info("Skipping remote resources execution."); return; } if (StringUtils.isEmpty(encoding)) { getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!"); } if (runOnlyAtExecutionRoot && !project.isExecutionRoot()) { getLog().info( "Skipping remote-resource generation in this project because it's not the Execution Root"); return; } if (resolveScopes == null) { if (excludeScope == null || "".equals(excludeScope)) { resolveScopes = new String[] { this.includeScope }; } else { resolveScopes = new String[] { Artifact.SCOPE_TEST }; } } velocity = new VelocityEngine(); velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this); velocity.setProperty("resource.loader", "classpath"); velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); velocity.init(); if (supplementalModels == null) { File sups = new File(appendedResourcesDirectory, "supplemental-models.xml"); if (sups.exists()) { try { supplementalModels = new String[] { sups.toURI().toURL().toString() }; } catch (MalformedURLException e) { // ignore getLog().debug("URL issue with supplemental-models.xml: " + e.toString()); } } } addSupplementalModelArtifacts(); locator.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath()); if (appendedResourcesDirectory != null) { locator.addSearchPath(FileResourceLoader.ID, appendedResourcesDirectory.getAbsolutePath()); } locator.addSearchPath("url", ""); locator.setOutputDirectory(new File(project.getBuild().getDirectory())); if (includeProjectProperties) { final Properties projectProperties = project.getProperties(); for (Object key : projectProperties.keySet()) { properties.put(key.toString(), projectProperties.get(key).toString()); } } ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); validate(); List<File> resourceBundleArtifacts = downloadBundles(resourceBundles); supplementModels = loadSupplements(supplementalModels); VelocityContext context = new VelocityContext(properties); configureVelocityContext(context); RemoteResourcesClassLoader classLoader = new RemoteResourcesClassLoader(null); initalizeClassloader(classLoader, resourceBundleArtifacts); Thread.currentThread().setContextClassLoader(classLoader); processResourceBundles(classLoader, context); try { if (outputDirectory.exists()) { // ---------------------------------------------------------------------------- // Push our newly generated resources directory into the MavenProject so that // these resources can be picked up by the process-resources phase. // ---------------------------------------------------------------------------- Resource resource = new Resource(); resource.setDirectory(outputDirectory.getAbsolutePath()); // MRRESOURCES-61 handle main and test resources separately if (attachToMain) { project.getResources().add(resource); } if (attachToTest) { project.getTestResources().add(resource); } // ---------------------------------------------------------------------------- // Write out archiver dot file // ---------------------------------------------------------------------------- File dotFile = new File(project.getBuild().getDirectory(), ".plxarc"); FileUtils.mkdir(dotFile.getParentFile().getAbsolutePath()); FileUtils.fileWrite(dotFile.getAbsolutePath(), outputDirectory.getName()); } } catch (IOException e) { throw new MojoExecutionException("Error creating dot file for archiving instructions.", e); } } finally { Thread.currentThread().setContextClassLoader(origLoader); } }
From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob2.java
@Override public String call() throws IOException { String response = ""; ReviewInput reviewInput = createReview(); String reviewEndpoint = resolveEndpointURL(); HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint); if (httpPost == null) { return response; }//from www. j ava2s . com CredentialsProvider credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(AuthScope.ANY, credentials); HttpHost proxy = null; if (httpProxy != null && !httpProxy.isEmpty()) { try { URL url = new URL(httpProxy); proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); } catch (MalformedURLException e) { logger.error("Could not parse proxy URL, attempting without proxy.", e); if (altLogger != null) { altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage()); } } } HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultCredentialsProvider(credProvider); if (proxy != null) { builder.setProxy(proxy); } CloseableHttpClient httpClient = builder.build(); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase()); if (altLogger != null) { altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase()); } } } catch (Exception e) { logger.error("Failed to submit result to Gerrit", e); if (altLogger != null) { altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString()); } } return response; }
From source file:org.opendatakit.services.sync.service.logic.HttpRestProtocolWrapper.java
public CloseableHttpResponse httpClientExecute(HttpRequestBase request, List<Integer> handledReturnCodes) throws HttpClientWebException { CloseableHttpResponse response = null; String authenticationType = sc.getAuthenticationType(); boolean isGoogleAccount = false; if (sc.getString(R.string.credential_type_google_account).equals(authenticationType)) { isGoogleAccount = true;//from ww w . j a va 2 s . c o m request.addHeader("Authorization", "Bearer " + accessToken); } // we set success to true when we return the response. // When we exit the outer try, if success is false, // consume any response entity and close the response. boolean success = false; try { try { if (localContext != null) { response = httpClient.execute(request, localContext); } else { response = httpClient.execute(request); } if (isGoogleAccount && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { request.removeHeaders("Authorization"); updateAccessToken(); request.addHeader("Authorization", "Bearer " + accessToken); // re-issue the request with new access token if (localContext != null) { response = httpClient.execute(request, localContext); } else { response = httpClient.execute(request); } } } catch (MalformedURLException e) { log.e(LOGTAG, "Bad client config -- malformed URL"); log.printStackTrace(e); // bad client config throw new BadClientConfigException("malformed URL", e, request, response); } catch (UnknownHostException e) { log.e(LOGTAG, "Bad client config -- Unknown host"); log.printStackTrace(e); // bad client config throw new BadClientConfigException("Unknown Host", e, request, response); } catch (ClientProtocolException e) { log.e(LOGTAG, "Bad request construction - " + e.toString()); log.printStackTrace(e); // bad request construction throw new ServerDetectedVersionMismatchedClientRequestException( "Bad request construction - " + e.toString(), e, request, response); } catch (UnknownServiceException e) { log.e(LOGTAG, "Bad request construction - " + e.toString()); log.printStackTrace(e); // bad request construction throw new ServerDetectedVersionMismatchedClientRequestException( "Bad request construction - " + e.toString(), e, request, response); } catch (InvalidAuthTokenException e) { log.e(LOGTAG, "updating of Google access token failed"); log.printStackTrace(e); // problem interacting with Google to update Auth token. // this should be treated as an authentication failure throw new AccessDeniedReauthException("updating of Google access token failed", e, request, response); } catch (Exception e) { log.e(LOGTAG, "Network failure - " + e.toString()); log.printStackTrace(e); // network transmission or SSL or other comm failure throw new NetworkTransmissionException("Network failure - " + e.toString(), e, request, response); } // if we do not find our header in the response, then this is most likely a // wifi network login screen. if (response.getHeaders(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER) == null) { throw new NotOpenDataKitServerException(request, response); } int statusCode = response.getStatusLine().getStatusCode(); if (handledReturnCodes.contains(statusCode)) { success = true; return response; } String errorText = "Unexpected server response statusCode: " + Integer.toString(statusCode); if (statusCode >= 200 && statusCode < 300) { log.e(LOGTAG, errorText); // server returned an unexpected success response -- // mismatched client and server implementations throw new ClientDetectedVersionMismatchedServerResponseException(errorText, request, response); } if (statusCode == HttpStatus.SC_UNAUTHORIZED) { log.e(LOGTAG, errorText); // server rejected our request -- mismatched client and server implementations throw new AccessDeniedException(errorText, request, response); } if (statusCode >= 400 && statusCode < 500) { log.e(LOGTAG, errorText); // server rejected our request -- mismatched client and server implementations throw new ServerDetectedVersionMismatchedClientRequestException(errorText, request, response); } if (statusCode >= 500 && statusCode < 600) { log.e(LOGTAG, errorText); // internal error within the server -- admin should check server logs throw new InternalServerFailureException(errorText, request, response); } log.e(LOGTAG, errorText); // some sort of 300 (or impossible) response that we were // not expecting and don't know how to handle throw new UnexpectedServerRedirectionStatusCodeException(errorText, request, response); } finally { if (response != null && !success) { EntityUtils.consumeQuietly(response.getEntity()); try { response.close(); } catch (IOException e) { log.e(LOGTAG, "failed to close response"); log.printStackTrace(e); } } } }
From source file:org.opendatakit.aggregate.odktables.api.perf.AggregateSynchronizer.java
/** * * @param entry//from w ww . j ava 2s. c om * @return */ private boolean compareAndDownloadFile(String tableId, OdkTablesFileManifestEntry entry) { String basePath = ODKFileUtils.getAppFolder(appName); SyncETagsUtils seu = new SyncETagsUtils(); // if the file is a placeholder on the server, then don't do anything... if (entry.contentLength == 0) { return false; } // now we need to look through the manifest and see where the files are // supposed to be stored. Make sure you don't return a bad string. if (entry.filename == null || entry.filename.equals("")) { logger.info("returned a null or empty filename"); return false; } else { URI uri = null; URL urlFile = null; try { logger.info("[downloadFile] downloading at url: " + entry.downloadUrl); urlFile = new URL(entry.downloadUrl); uri = urlFile.toURI(); } catch (MalformedURLException e) { logger.error(e.toString()); e.printStackTrace(); ; return false; } catch (URISyntaxException e) { logger.error(e.toString()); e.printStackTrace(); ; return false; } // filename is the unrooted path of the file, so prepend the basepath. String path = basePath + File.separator + entry.filename; // Before we try dl'ing the file, we have to make the folder, // b/c otherwise if the folders down to the path have too many non- // existent folders, we'll get a FileNotFoundException when we open // the FileOutputStream. File newFile = new File(path); String folderPath = newFile.getParent(); ODKFileUtils.createFolder(folderPath); if (!newFile.exists()) { // the file doesn't exist on the system // filesToDL.add(newFile); try { int statusCode = downloadFile(newFile, uri); if (statusCode == HttpStatus.SC_OK) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), entry.md5hash); return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); ; logger.error("trouble downloading file for first time"); return false; } } else { boolean hasUpToDateEntry = true; String md5hash = seu.getFileSyncETag(context, appName, uri, tableId, newFile.lastModified()); if (md5hash == null) { // file exists, but no record of what is on the server // compute local value hasUpToDateEntry = false; md5hash = ODKFileUtils.getMd5Hash(appName, newFile); } // so as it comes down from the manifest, the md5 hash includes a // "md5:" prefix. Add that and then check. if (!md5hash.equals(entry.md5hash)) { hasUpToDateEntry = false; // it's not up to date, we need to download it. try { int statusCode = downloadFile(newFile, uri); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), md5hash); return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); ; // TODO throw correct exception logger.error("trouble downloading new version of existing file"); return false; } } else { if (!hasUpToDateEntry) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), md5hash); } // no change return false; } } } }
From source file:gov.usda.DataCatalogClient.Dataset.java
private void setLandingPage(String landingPage) { if (landingPage != null && !landingPage.isEmpty()) { try {// w w w . j a v a 2 s. c o m this.landingPage = new URL(landingPage); } catch (MalformedURLException e) { dsEx.addError("Landing Page is invalid URL." + e.toString()); } } }
From source file:org.opendatakit.sync.aggregate.AggregateSynchronizer.java
/** * * @param entry/*from w w w . j av a 2s . com*/ * @return */ private boolean compareAndDownloadFile(String tableId, OdkTablesFileManifestEntry entry) { String basePath = ODKFileUtils.getAppFolder(appName); SyncETagsUtils seu = new SyncETagsUtils(); // if the file is a placeholder on the server, then don't do anything... if (entry.contentLength == 0) { return false; } // now we need to look through the manifest and see where the files are // supposed to be stored. Make sure you don't return a bad string. if (entry.filename == null || entry.filename.equals("")) { log.i(LOGTAG, "returned a null or empty filename"); return false; } else { URI uri = null; URL urlFile = null; try { log.i(LOGTAG, "[downloadFile] downloading at url: " + entry.downloadUrl); urlFile = new URL(entry.downloadUrl); uri = urlFile.toURI(); } catch (MalformedURLException e) { log.e(LOGTAG, e.toString()); log.printStackTrace(e); return false; } catch (URISyntaxException e) { log.e(LOGTAG, e.toString()); log.printStackTrace(e); return false; } // filename is the unrooted path of the file, so prepend the // basepath. String path = basePath + File.separator + entry.filename; // Before we try dl'ing the file, we have to make the folder, // b/c otherwise if the folders down to the path have too many non- // existent folders, we'll get a FileNotFoundException when we open // the FileOutputStream. File newFile = new File(path); String folderPath = newFile.getParent(); ODKFileUtils.createFolder(folderPath); if (!newFile.exists()) { // the file doesn't exist on the system // filesToDL.add(newFile); try { int statusCode = downloadFile(newFile, uri); if (statusCode == HttpStatus.SC_OK) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), entry.md5hash); return true; } else { return false; } } catch (Exception e) { log.printStackTrace(e); log.e(LOGTAG, "trouble downloading file for first time"); return false; } } else { boolean hasUpToDateEntry = true; String md5hash = seu.getFileSyncETag(context, appName, uri, tableId, newFile.lastModified()); if (md5hash == null) { // file exists, but no record of what is on the server // compute local value hasUpToDateEntry = false; md5hash = ODKFileUtils.getMd5Hash(appName, newFile); } // so as it comes down from the manifest, the md5 hash includes // a // "md5:" prefix. Add that and then check. if (!md5hash.equals(entry.md5hash)) { hasUpToDateEntry = false; // it's not up to date, we need to download it. try { int statusCode = downloadFile(newFile, uri); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), md5hash); return true; } else { return false; } } catch (Exception e) { log.printStackTrace(e); // TODO throw correct exception log.e(LOGTAG, "trouble downloading new version of existing file"); return false; } } else { if (!hasUpToDateEntry) { seu.updateFileSyncETag(context, appName, uri, tableId, newFile.lastModified(), md5hash); } // no change return false; } } } }
From source file:com.easy.facebook.android.apicall.GraphApi.java
public String createFriendList(String frirndListName) throws EasyFacebookError { String frirndListID = ""; Bundle params = new Bundle(); params.putString("format", "json"); params.putString("access_token", facebook.getAccessToken()); params.putString("name", frirndListName); String jsonResponse;/*from ww w.ja v a 2 s . c om*/ try { jsonResponse = Util.openUrl("https://graph.facebook.com/me/friendlists", "POST", params); JSONObject json = new JSONObject(jsonResponse); if (json.has("id")) frirndListID = json.get("id").toString(); } catch (MalformedURLException e) { throw new EasyFacebookError(e.toString(), "MalformedURLException"); } catch (IOException e) { throw new EasyFacebookError(e.toString(), "IOException"); } catch (JSONException e) { throw new EasyFacebookError(e.toString(), "JSONException"); } return frirndListID; }
From source file:com.easy.facebook.android.apicall.GraphApi.java
public String addMemberToFriendList(String frirndListID, String friendID) throws EasyFacebookError { Bundle params = new Bundle(); params.putString("format", "json"); params.putString("access_token", facebook.getAccessToken()); String jsonResponse = null;//from w w w . j ava2 s . c o m try { jsonResponse = Util.openUrl("https://graph.facebook.com/" + frirndListID + "/members/" + friendID, "POST", params); JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse); if (!objectJSONErrorCheck.isNull("error")) { throw new EasyFacebookError(jsonResponse); } } catch (MalformedURLException e) { throw new EasyFacebookError(e.toString(), "MalformedURLException"); } catch (IOException e) { throw new EasyFacebookError(e.toString(), "IOException"); } catch (JSONException e) { throw new EasyFacebookError(e.toString(), "JSONException"); } return jsonResponse; }