List of usage examples for java.net URISyntaxException getMessage
public String getMessage()
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMReference.java
public DOMReference(String uri, String type, DigestMethod dm, List<? extends Transform> appliedTransforms, Data result, List<? extends Transform> transforms, String id, byte[] digestValue, Provider provider) { if (dm == null) { throw new NullPointerException("DigestMethod must be non-null"); }// w w w .j av a2 s . c om if (appliedTransforms == null) { this.allTransforms = new ArrayList<Transform>(); } else { this.allTransforms = new ArrayList<Transform>(appliedTransforms); for (int i = 0, size = this.allTransforms.size(); i < size; i++) { if (!(this.allTransforms.get(i) instanceof Transform)) { throw new ClassCastException("appliedTransforms[" + i + "] is not a valid type"); } } } if (transforms == null) { this.transforms = Collections.emptyList(); } else { this.transforms = new ArrayList<Transform>(transforms); for (int i = 0, size = this.transforms.size(); i < size; i++) { if (!(this.transforms.get(i) instanceof Transform)) { throw new ClassCastException("transforms[" + i + "] is not a valid type"); } } this.allTransforms.addAll(this.transforms); } this.digestMethod = dm; this.uri = uri; if ((uri != null) && (!uri.equals(""))) { try { new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage()); } } this.type = type; this.id = id; if (digestValue != null) { this.digestValue = (byte[]) digestValue.clone(); this.digested = true; } this.appliedTransformData = result; this.provider = provider; }
From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;// ww w . j a va 2 s . com int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("User-Agent", "Android-GData"); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (DEBUG) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:jp.yojio.triplog.Common.DataApi.gdata.AndroidGDataClient.java
private InputStream createAndExecuteMethod(HttpRequestCreator creator, String uriString, String authToken) throws HttpException, IOException { HttpResponse response = null;//from w w w. ja va 2 s . c o m int status = 500; int redirectsLeft = MAX_REDIRECTS; URI uri; try { uri = new URI(uriString); } catch (URISyntaxException use) { Log.w(TAG, "Unable to parse " + uriString + " as URI.", use); throw new IOException("Unable to parse " + uriString + " as URI: " + use.getMessage()); } // we follow redirects ourselves, since we want to follow redirects even on // POSTs, which // the HTTP library does not do. following redirects ourselves also allows // us to log // the redirects using our own logging. while (redirectsLeft > 0) { HttpUriRequest request = creator.createRequest(uri); request.addHeader("Accept-Encoding", "gzip"); // only add the auth token if not null (to allow for GData feeds that do // not require // authentication.) if (!TextUtils.isEmpty(authToken)) { request.addHeader("Authorization", "GoogleLogin auth=" + authToken); } if (LOCAL_LOGV) { for (Header h : request.getAllHeaders()) { Log.v(TAG, h.getName() + ": " + h.getValue()); } Log.d(TAG, "Executing " + request.getRequestLine().toString()); } response = null; try { response = httpClient.execute(request); } catch (IOException ioe) { Log.w(TAG, "Unable to execute HTTP request." + ioe); throw ioe; } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { Log.w(TAG, "StatusLine is null."); throw new NullPointerException("StatusLine is null -- should not happen."); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, response.getStatusLine().toString()); for (Header h : response.getAllHeaders()) { Log.d(TAG, h.getName() + ": " + h.getValue()); } } status = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); if ((status >= 200) && (status < 300) && entity != null) { return getUngzippedContent(entity); } // TODO: handle 301, 307? // TODO: let the http client handle the redirects, if we can be sure we'll // never get a // redirect on POST. if (status == 302) { // consume the content, so the connection can be closed. entity.consumeContent(); Header location = response.getFirstHeader("Location"); if (location == null) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Redirect requested but no Location " + "specified."); } break; } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Following redirect to " + location.getValue()); } try { uri = new URI(location.getValue()); } catch (URISyntaxException use) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Unable to parse " + location.getValue() + " as URI.", use); throw new IOException("Unable to parse " + location.getValue() + " as URI."); } break; } --redirectsLeft; } else { break; } } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Received " + status + " status code."); } String errorMessage = null; HttpEntity entity = response.getEntity(); try { if (response != null && entity != null) { InputStream in = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesRead = -1; while ((bytesRead = in.read(buf)) != -1) { baos.write(buf, 0, bytesRead); } // TODO: use appropriate encoding, picked up from Content-Type. errorMessage = new String(baos.toByteArray()); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, errorMessage); } } } finally { if (entity != null) { entity.consumeContent(); } } String exceptionMessage = "Received " + status + " status code"; if (errorMessage != null) { exceptionMessage += (": " + errorMessage); } throw new HttpException(exceptionMessage, status, null /* InputStream */); }
From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModule.java
@Override public void initialize() throws InitializationException { String configuredURL = this.configuration.getProperty(CONFIGURATION_KEY); if (StringUtils.isBlank(configuredURL)) { throw new InitializationException(this.getClass().getSimpleName() + " requires a valid URL to be configured in xwiki.properties under the " + CONFIGURATION_KEY + " key"); }/* w ww .java2 s . c om*/ try { this.remoteServiceURL = new URI(configuredURL); } catch (URISyntaxException ex) { throw new InitializationException( "Invalid URL configured for " + this.getClass().getSimpleName() + ": " + configuredURL, ex); } LRUCacheConfiguration config = new LRUCacheConfiguration("RemoteAuthorizationService", 1000, 60); try { this.cache = this.factory.newCache(config); } catch (CacheException ex) { throw new InitializationException("Failed to create authorization cache: " + ex.getMessage(), ex); } }
From source file:edu.jhu.pha.vospace.meta.MySQLMetaStore2.java
@Override public List<VospaceId> search(final VospaceId identifier, final String searchPattern, final int fileLimit, final boolean includeDeleted) { String request = "select container, path from nodes where " + (includeDeleted ? "" : "deleted = 0 and ") + " current_rev = 1 and owner = ? and container = ? and path like ? and path regexp ? order by path limit ?"; return DbPoolServlet.goSql("search request", request, new SqlWorker<List<VospaceId>>() { @Override//from ww w . jav a 2 s. com public List<VospaceId> go(Connection conn, PreparedStatement stmt) throws SQLException { ArrayList<VospaceId> result = new ArrayList<VospaceId>(); stmt.setString(1, owner); stmt.setString(2, identifier.getNodePath().getContainerName()); stmt.setString(3, identifier.getNodePath().getNodeRelativeStoragePath() + "%"); stmt.setString(4, "^" + identifier.getNodePath().getNodeRelativeStoragePath() + ".*" + searchPattern + ".*"); stmt.setInt(5, fileLimit); ResultSet rs = stmt.executeQuery(); while (rs.next()) { try { NodePath npath = new NodePath("/" + rs.getString(1) + "/" + rs.getString(2)); result.add(new VospaceId(npath)); } catch (URISyntaxException e) { logger.error("Error in child URI: " + e.getMessage()); } } return result; } }); }
From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java
private FutureConnection createConnection(String host, String clientId, int keepAlive) { try {//from w w w. j a v a 2s.co m MQTT client = new MQTT(); client.setHost(host); client.setClientId(clientId); client.setKeepAlive((short) keepAlive); if (host != null && (host.trim().toLowerCase().startsWith("ssl://"))) { SSLContext context = SSLUtil.getContext(); if (context != null) { client.setSslContext(context); } } return client.futureConnection(); } catch (URISyntaxException e) { getLogger().error(e.getMessage()); return null; } }
From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java
private FutureConnection createConnection(String host, String clientId, String user, String password, int keepAlive) { try {//from ww w. j a v a 2s. com MQTT client = new MQTT(); client.setHost(host); client.setUserName(user); client.setPassword(password); client.setClientId(clientId); client.setKeepAlive((short) keepAlive); if (host != null && (host.trim().toLowerCase().startsWith("ssl://"))) { SSLContext context = SSLUtil.getContext(); if (context != null) { client.setSslContext(context); } } return client.futureConnection(); } catch (URISyntaxException e) { getLogger().error(e.getMessage()); return null; } }
From source file:de.unibi.cebitec.bibiserv.web.beans.runinthecloud.BashExecutor.java
/** * Parse toolID from RequestHeader.//from w w w . j av a 2 s . c o m * * @return toolID */ private String getToolID() { /** * Get Tool-ID. */ URI requestURL = null; FacesContext ctx; HttpServletRequest req; try { ctx = FacesContext.getCurrentInstance(); req = (HttpServletRequest) ctx.getExternalContext().getRequest(); requestURL = new URI(req.getHeader("referer")); /** * referer e.g. http://localhost:9080/dialign?id=ritc */ return requestURL.getPath().substring(1); // getPath()=='/dialign' } catch (URISyntaxException ue) { log.error(ue.getMessage(), ue); return "error"; } }
From source file:org.openremote.modeler.beehive.Beehive30API.java
/** * Downloads a user artifact archive from Beehive server and stores it to a local resource * cache. //from ww w . j a va 2 s.c o m * * @param userAccount reference to information about user and account being accessed * @param cache the cache to store the user resources to * * @throws ConfigurationException * If designer configuration error prevents the service from executing * normally. Often a fatal error type that should be logged/notified to * admins, configuration corrected and application re-deployed. * * @throws NetworkException * If (possibly recoverable) network errors occured during the service * operation. Network errors may be recoverable in which case this operation * could be re-attempted. See {@link NetworkException.Severity} for an * indication of the network error type. * * @throws CacheOperationException * If there was a failure in writing the downloaded resources to cache. * * */ @Override public void downloadResources(UserAccount userAccount, ResourceCache cache) throws ConfigurationException, NetworkException, CacheOperationException { // TODO : // - Must use HTTPS // Construct the request... HttpClient httpClient = new DefaultHttpClient(); URI beehiveArchiveURI; try { beehiveArchiveURI = new URI(config.getBeehiveRESTRootUrl() + "user/" + userAccount.getUsernamePassword().getUsername() + "/openremote.zip"); } catch (URISyntaxException e) { throw new ConfigurationException("Incorrect Beehive REST URL defined in config.properties : {0}", e, e.getMessage()); } HttpGet httpGet = new HttpGet(beehiveArchiveURI); // Authenticate... addHTTPAuthenticationHeader(httpGet, userAccount.getUsernamePassword().getUsername(), userAccount.getUsernamePassword().getPassword()); // Collect some network statistics... long starttime = System.currentTimeMillis(); // HTTP GET to Beehive... HttpResponse response; try { response = httpClient.execute(httpGet); } catch (IOException e) { throw new NetworkException( "Network error while downloading account (OID = {0}) archive from Beehive " + "(URL : {1}) : {2}", e, userAccount.getAccount().getOid(), beehiveArchiveURI, e.getMessage()); } // Make sure we got a response and a proper HTTP return code... if (response == null) { throw new NetworkException(NetworkException.Severity.SEVERE, "Beehive did not respond to HTTP GET request, URL : {0} {1}", beehiveArchiveURI, printUser(userAccount)); } StatusLine statusLine = response.getStatusLine(); if (statusLine == null) { throw new NetworkException(NetworkException.Severity.SEVERE, "There was no status from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI, printUser(userAccount)); } int httpResponseCode = statusLine.getStatusCode(); // Deal with the HTTP OK (200) case. if (httpResponseCode == HttpURLConnection.HTTP_OK) { HttpEntity httpEntity = response.getEntity(); if (httpEntity == null) { throw new NetworkException(NetworkException.Severity.SEVERE, "No content received from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI, printUser(userAccount)); } // Download to cache... BufferedInputStream httpInput; try { CacheWriteStream cacheStream = cache.openWriteStream(); httpInput = new BufferedInputStream(httpEntity.getContent()); byte[] buffer = new byte[4096]; int bytecount = 0, len; long contentLength = httpEntity.getContentLength(); try { while ((len = httpInput.read(buffer)) != -1) { try { cacheStream.write(buffer, 0, len); } catch (IOException e) { throw new CacheOperationException("Writing archive to cache failed : {0}", e, e.getMessage()); } bytecount += len; } // MUST mark complete for cache to accept the incoming archive... cacheStream.markCompleted(); } finally { try { cacheStream.close(); } catch (Throwable t) { serviceLog.warn("Unable to close resource archive cache stream : {0}", t, t.getMessage()); } if (httpInput != null) { try { httpInput.close(); } catch (Throwable t) { serviceLog.warn("Unable to close HTTP input stream from Beehive URL ''{0}'' : {1}", t, beehiveArchiveURI, t.getMessage()); } } } if (contentLength >= 0) { if (bytecount != contentLength) { serviceLog.warn( "Expected content length was {0} bytes but wrote {1} bytes to cache stream ''{2}''.", contentLength, bytecount, cacheStream); } } // Record network performance stats... long endtime = System.currentTimeMillis(); float kbytes = ((float) bytecount) / 1000; float seconds = ((float) (endtime - starttime)) / 1000; float kbpersec = kbytes / seconds; String kilobytes = new DecimalFormat("###########0.00").format(kbytes); String nettime = new DecimalFormat("##########0.000").format(seconds); String persectime = new DecimalFormat("##########0.000").format(kbpersec); downloadPerfLog.info("Downloaded " + kilobytes + " kilobytes in " + nettime + " seconds (" + persectime + "kb/s)"); } catch (IOException e) { // HTTP request I/O error... throw new NetworkException("Download of Beehive archive failed : {0}", e, e.getMessage()); } } // Assuming 404 indicates a new user... quietly return, nothing to download... // TODO : MODELER-286 else if (httpResponseCode == HttpURLConnection.HTTP_NOT_FOUND) { serviceLog.info("No user data found. Return code 404. Assuming new user account..."); return; } else { // TODO : // // Currently assumes any other HTTP return code is a standard network error. // This could be improved by handling more specific error codes (some are // fatal, some are recoverable) such as 500 Internal Error (permanent) or // 307 Temporary Redirect // // TODO : // // Should handle authentication errors in their own branch, not in this generic block throw new NetworkException( "Failed to download Beehive archive from URL ''{0}'' {1}, " + "HTTP Response code: {2}", beehiveArchiveURI, printUser(userAccount), httpResponseCode); } }
From source file:org.hfoss.posit.android.sync.Communicator.java
/** * A wrapper(does some cleanup too) for sending HTTP GET requests to the URI * /*from w ww . j av a 2s . c om*/ * @param Uri * @return the request from the remote server */ public static String doHTTPGET(String Uri) { BasicHttpParams mHttpParams = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(mHttpParams, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(mHttpParams, SOCKET_TIMEOUT); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); ThreadSafeClientConnManager mConnectionManager = new ThreadSafeClientConnManager(mHttpParams, registry); DefaultHttpClient mHttpClient = new DefaultHttpClient(mConnectionManager, mHttpParams); if (Uri == null) throw new NullPointerException("The URL has to be passed"); String responseString = null; HttpGet httpGet = new HttpGet(); try { httpGet.setURI(new URI(Uri)); } catch (URISyntaxException e) { Log.e(TAG, "doHTTPGet " + e.getMessage()); e.printStackTrace(); return "[Error] " + e.getMessage(); } Log.i(TAG, "doHTTPGet Uri = " + Uri); ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { responseString = mHttpClient.execute(httpGet, responseHandler); } catch (ClientProtocolException e) { Log.e(TAG, "ClientProtocolException" + e.getMessage()); return "[Error] " + e.getMessage(); } catch (SocketTimeoutException e) { Log.e(TAG, "[Error: SocketTimeoutException]" + e.getMessage()); return "[Error] " + e.getMessage(); } catch (IOException e) { Log.e(TAG, e.getMessage()); return "[Error] " + e.getMessage(); } catch (Exception e) { Log.e(TAG, e.getMessage() + "what"); return "[Error] " + e.getMessage(); } Log.i(TAG, "doHTTPGet Response: " + responseString); return responseString; }