List of usage examples for java.net URISyntaxException getMessage
public String getMessage()
From source file:org.openremote.android.console.net.ORConnection.java
/** * TODO//from w w w. j a va2s. c om * * Establish the httpconnection with url for caller and then the caller can deal with the * httprequest result within ORConnectionDelegate instance. if check failed, return null. * * @param context global Android application context * @param httpMethod enum POST or GET * @param url the URL to connect to * @param useHTTPAuth indicates whether the HTTP 'Authentication' header should be added * to the HTTP request * * @return TODO * * @throws IOException if the URL cannot be resolved by DNS (UnknownHostException), * if the URL was not correctly formed (MalformedURLException), * if the connection timed out (SocketTimeoutException), * there was an error in the HTTP protocol (ClientProtocolException), * or any other IO error occured (generic IOException) */ public static HttpResponse checkURLWithHTTPProtocol(Context context, ORHttpMethod httpMethod, String urlString, boolean useHTTPAuth) throws IOException { // TODO : could move this method to ORNetworkCheck class, no one else is using it. // // TODO : use URL in the API instead of string // // Validate the URL by creating a proper URL instance from the string... it will throw // an MalformedURLException (IOException) in case the URL was invalid. // // This can go away when the API is fixed... URL targetURL = new URL(urlString); URI targetURI; try { targetURI = targetURL.toURI(); } catch (URISyntaxException e) { // Not sure if we're ever going to hit this, but in case we do, just convert to // MalformedURLException... throw new MalformedURLException( "Could not convert " + urlString + " to a compliant URI: " + e.getMessage()); } HttpRequestBase request = null; HttpResponse response = null; HttpParams params = new BasicHttpParams(); // TODO : seems like timeouts ought to be externalized... HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); HttpClient client = new DefaultHttpClient(params); switch (httpMethod) { case POST: request = new HttpPost(targetURI); break; case GET: request = new HttpGet(targetURI); break; default: throw new IOException("Unsupported HTTP Method: " + httpMethod); } if (useHTTPAuth) { SecurityUtil.addCredentialToHttpRequest(context, request); } if ("https".equals(targetURL.getProtocol())) { Scheme sch = new Scheme(targetURL.getProtocol(), new SelfCertificateSSLSocketFactory(context), targetURL.getPort()); client.getConnectionManager().getSchemeRegistry().register(sch); } try { response = client.execute(request); } catch (IllegalArgumentException e) { throw new MalformedURLException("Illegal argument: " + e.getMessage()); } return response; }
From source file:edu.jhu.pha.vospace.rest.TransfersController.java
/** * Submit the job to database// www.j a v a2 s . co m * @param xmlNode the job XML document * @param username the username of the job owner * @return the job ID */ public static UUID submitJob(String xmlNode, String username) { StringReader strRead = new StringReader(xmlNode); UUID jobUID = UUID.randomUUID(); try { JobDescription job = new JobDescription(); job.setId(jobUID.toString()); job.setUsername(username); job.setStartTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()); job.setState(JobDescription.STATE.PENDING); SAXBuilder xmlBuilder = new SAXBuilder(); Element nodeElm = xmlBuilder.build(strRead).getRootElement(); List<Element> paramNodes = nodeElm.getChildren(); for (Iterator<Element> it = paramNodes.iterator(); it.hasNext();) { Element param = it.next(); if (param.getName().equals("target")) { try { job.setTarget(param.getValue()); } catch (URISyntaxException e) { logger.error("Error in job parse: " + e.getMessage()); throw new BadRequestException("InvalidURI"); } } else if (param.getName().equals("direction")) { JobDescription.DIRECTION direct = JobDescription.DIRECTION.LOCAL; if (param.getValue().toUpperCase().endsWith("SPACE")) direct = JobDescription.DIRECTION.valueOf(param.getValue().toUpperCase()); job.setDirection(direct); if (direct == JobDescription.DIRECTION.PULLFROMVOSPACE) { job.addProtocol(conf.getString("transfers.protocol.httpget"), conf.getString("application.url") + "/data/" + job.getId()); } else if (direct == JobDescription.DIRECTION.PUSHTOVOSPACE) { job.addProtocol(conf.getString("transfers.protocol.httpput"), conf.getString("application.url") + "/data/" + job.getId()); } else if (direct == JobDescription.DIRECTION.LOCAL) { try { job.setDirectionTarget(param.getValue()); } catch (URISyntaxException e) { logger.error("Error in job parse: " + e.getMessage()); throw new BadRequestException("InvalidURI"); } } } else if (param.getName().equals("view")) { job.addView(param.getValue()); } else if (param.getName().equals("keepBytes")) { job.setKeepBytes(Boolean.parseBoolean(param.getValue())); } else if (param.getName().equals("protocol")) { String protocol = param.getAttributeValue("uri"); String protocolEndpoint = param.getChildText("protocolEndpoint", Namespace.getNamespace(VOS_NAMESPACE)); if (job.getDirection().equals(DIRECTION.PULLFROMVOSPACE) || job.getDirection().equals(DIRECTION.PUSHTOVOSPACE)) { protocolEndpoint = conf.getString("application.url") + "/data/" + job.getId(); } if (null != protocol && null != protocolEndpoint) job.addProtocol(protocol, protocolEndpoint); else throw new BadRequestException("InvalidArgument"); } } JobsProcessor.getDefaultImpl().submitJob(username, job); } catch (JDOMException e) { e.printStackTrace(); throw new InternalServerErrorException(e); } catch (IOException e) { logger.error(e); throw new InternalServerErrorException(e); } catch (IllegalArgumentException e) { logger.error("Error calling the job task: " + e.getMessage()); throw new InternalServerErrorException("InternalFault"); } finally { strRead.close(); } return jobUID; }
From source file:com.bytelightning.opensource.pokerface.ScriptHelperImpl.java
/** * Normalization code courtesy of 'Mike Houston' http://stackoverflow.com/questions/2993649/how-to-normalize-a-url-in-java *//*from ww w .j a v a 2 s. c o m*/ public static String NormalizeURL(final String taintedURL) throws MalformedURLException { final URL url; try { url = new URI(taintedURL).normalize().toURL(); } catch (URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } final String path = url.getPath().replace("/$", ""); final SortedMap<String, String> params = CreateParameterMap(url.getQuery()); final int port = url.getPort(); final String queryString; if (params != null) { // Some params are only relevant for user tracking, so remove the most commons ones. for (Iterator<String> i = params.keySet().iterator(); i.hasNext();) { final String key = i.next(); if (key.startsWith("utm_") || key.contains("session")) i.remove(); } queryString = "?" + Canonicalize(params); } else queryString = ""; return url.getProtocol() + "://" + url.getHost() + (port != -1 && port != 80 ? ":" + port : "") + path + queryString; }
From source file:password.pwm.http.servlet.oauth.OAuthConsumerServlet.java
public static String figureOauthSelfEndPointUrl(final PwmRequest pwmRequest) { final String inputURI, debugSource; {//from www .j av a 2 s . com final String returnUrlOverride = pwmRequest.getConfig() .readAppProperty(AppProperty.OAUTH_RETURN_URL_OVERRIDE); final String siteURL = pwmRequest.getConfig().readSettingAsString(PwmSetting.PWM_SITE_URL); if (returnUrlOverride != null && !returnUrlOverride.trim().isEmpty()) { inputURI = returnUrlOverride; debugSource = "AppProperty(\"" + AppProperty.OAUTH_RETURN_URL_OVERRIDE.getKey() + "\")"; } else if (siteURL != null && !siteURL.trim().isEmpty()) { inputURI = siteURL; debugSource = "SiteURL Setting"; } else { debugSource = "Input Request URL"; inputURI = pwmRequest.getHttpServletRequest().getRequestURL().toString(); } } final String redirect_uri; try { final URI requestUri = new URI(inputURI); redirect_uri = requestUri.getScheme() + "://" + requestUri.getHost() + (requestUri.getPort() > 0 ? ":" + requestUri.getPort() : "") + PwmServletDefinition.OAuthConsumer.servletUrl(); } catch (URISyntaxException e) { throw new IllegalStateException( "unable to parse inbound request uri while generating oauth redirect: " + e.getMessage()); } LOGGER.trace("calculated oauth self end point URI as '" + redirect_uri + "' using method " + debugSource); return redirect_uri; }
From source file:com.joyent.manta.config.ConfigContext.java
/** * Utility method for validating that the configuration has been instantiated * with valid settings./*from w w w . j a v a 2s. co m*/ * * @param config configuration to test * @throws ConfigurationException thrown when validation fails */ static void validate(final ConfigContext config) { List<String> failureMessages = new ArrayList<>(); if (StringUtils.isBlank(config.getMantaUser())) { failureMessages.add("Manta account name must be specified"); } if (StringUtils.isBlank(config.getMantaURL())) { failureMessages.add("Manta URL must be specified"); } else { try { new URI(config.getMantaURL()); } catch (URISyntaxException e) { final String msg = String.format("%s - invalid Manta URL: %s", e.getMessage(), config.getMantaURL()); failureMessages.add(msg); } } if (config.getTimeout() != null && config.getTimeout() < 0) { failureMessages.add("Manta timeout must be 0 or greater"); } if (config.getTcpSocketTimeout() != null && config.getTcpSocketTimeout() < 0) { failureMessages.add("Manta tcp socket timeout must be 0 or greater"); } if (config.getConnectionRequestTimeout() != null && config.getConnectionRequestTimeout() < 0) { failureMessages.add("Manta connection request timeout must be 0 or greater"); } if (config.getExpectContinueTimeout() != null && config.getExpectContinueTimeout() < 1) { failureMessages.add("Manta Expect 100-continue timeout must be 1 or greater"); } final boolean authenticationEnabled = BooleanUtils.isNotTrue(config.noAuth()); if (authenticationEnabled) { if (config.getMantaKeyId() == null) { failureMessages.add("Manta key id must be specified"); } if (config.getMantaKeyPath() == null && config.getPrivateKeyContent() == null) { failureMessages.add("Either the Manta key path must be set or the private " + "key content must be set. Both can't be null."); } if (config.getMantaKeyPath() != null && StringUtils.isBlank(config.getMantaKeyPath())) { failureMessages.add("Manta key path must not be blank"); } if (config.getPrivateKeyContent() != null && StringUtils.isBlank(config.getPrivateKeyContent())) { failureMessages.add("Manta private key content must not be blank"); } } if (config.getSkipDirectoryDepth() != null && config.getSkipDirectoryDepth() < 0) { failureMessages.add("Manta skip directory depth must be 0 or greater"); } if (config.getMetricReporterMode() != null) { if (MetricReporterMode.SLF4J.equals(config.getMetricReporterMode())) { if (config.getMetricReporterOutputInterval() == null) { failureMessages.add("SLF4J metric reporter selected but no output interval was provided"); } else if (config.getMetricReporterOutputInterval() < 1) { failureMessages.add("Metric reporter output interval (ms) must be 1 or greater"); } } } if (BooleanUtils.isTrue(config.isClientEncryptionEnabled())) { encryptionSettings(config, failureMessages); } if (!failureMessages.isEmpty()) { String messages = StringUtils.join(failureMessages, System.lineSeparator()); ConfigurationException e = new ConfigurationException( "Errors when loading Manta SDK configuration:" + System.lineSeparator() + messages); // We don't dump all of the configuration settings, just the important ones e.setContextValue(MapConfigContext.MANTA_URL_KEY, config.getMantaURL()); e.setContextValue(MapConfigContext.MANTA_USER_KEY, config.getMantaUser()); e.setContextValue(MapConfigContext.MANTA_KEY_ID_KEY, config.getMantaKeyId()); e.setContextValue(MapConfigContext.MANTA_NO_AUTH_KEY, config.noAuth()); e.setContextValue(MapConfigContext.MANTA_KEY_PATH_KEY, config.getMantaKeyPath()); final String redactedPrivateKeyContent; if (config.getPrivateKeyContent() == null) { redactedPrivateKeyContent = "null"; } else { redactedPrivateKeyContent = "non-null"; } e.setContextValue(MapConfigContext.MANTA_PRIVATE_KEY_CONTENT_KEY, redactedPrivateKeyContent); e.setContextValue(MapConfigContext.MANTA_CLIENT_ENCRYPTION_ENABLED_KEY, config.isClientEncryptionEnabled()); if (BooleanUtils.isTrue(config.isClientEncryptionEnabled())) { e.setContextValue(MapConfigContext.MANTA_ENCRYPTION_KEY_ID_KEY, config.getEncryptionKeyId()); e.setContextValue(MapConfigContext.MANTA_PERMIT_UNENCRYPTED_DOWNLOADS_KEY, config.permitUnencryptedDownloads()); e.setContextValue(MapConfigContext.MANTA_ENCRYPTION_ALGORITHM_KEY, config.getEncryptionAlgorithm()); e.setContextValue(MapConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_PATH_KEY, config.getEncryptionPrivateKeyPath()); e.setContextValue(MapConfigContext.MANTA_ENCRYPTION_PRIVATE_KEY_BYTES_KEY + "_size", ArrayUtils.getLength(config.getEncryptionPrivateKeyBytes())); } throw e; } }
From source file:org.apache.hadoop.hive.ql.parse.EximUtil.java
public static String relativeToAbsolutePath(HiveConf conf, String location) throws SemanticException { try {/*from ww w . j ava 2 s.com*/ boolean testMode = conf.getBoolVar(HiveConf.ConfVars.HIVETESTMODE); if (testMode) { URI uri = new Path(location).toUri(); FileSystem fs = FileSystem.get(uri, conf); String scheme = fs.getScheme(); String authority = uri.getAuthority(); String path = uri.getPath(); if (!path.startsWith("/")) { path = (new Path(System.getProperty("test.tmp.dir"), path)).toUri().getPath(); } try { uri = new URI(scheme, authority, path, null, null); } catch (URISyntaxException e) { throw new SemanticException(ErrorMsg.INVALID_PATH.getMsg(), e); } return uri.toString(); } else { // no-op for non-test mode for now return location; } } catch (IOException e) { throw new SemanticException(ErrorMsg.IO_ERROR.getMsg() + ": " + e.getMessage(), e); } }
From source file:password.pwm.http.servlet.OAuthConsumerServlet.java
public static String figureOauthSelfEndPointUrl(final PwmRequest pwmRequest) { final HttpServletRequest req = pwmRequest.getHttpServletRequest(); final String redirect_uri; try {/*w w w . java 2 s . c om*/ final URI requestUri = new URI(req.getRequestURL().toString()); redirect_uri = requestUri.getScheme() + "://" + requestUri.getHost() + (requestUri.getPort() > 0 ? ":" + requestUri.getPort() : "") + PwmServletDefinition.OAuthConsumer.servletUrl(); } catch (URISyntaxException e) { throw new IllegalStateException( "unable to parse inbound request uri while generating oauth redirect: " + e.getMessage()); } return redirect_uri; }
From source file:com.fujitsu.dc.core.rs.cell.MessageODataResource.java
/** * To????baseUrl??????./*from w ww . j a va 2 s . co m*/ * @param toValue to??? * @param baseUrl baseUrl */ public static void validateToValue(String toValue, String baseUrl) { if (toValue == null) { return; } // URL?? String checkBaseUrl = null; String[] uriList = toValue.split(","); for (String uriStr : uriList) { try { URI uri = new URI(uriStr); checkBaseUrl = uri.getScheme() + "://" + uri.getHost(); int port = uri.getPort(); if (port != -1) { checkBaseUrl += ":" + Integer.toString(port); } checkBaseUrl += "/"; } catch (URISyntaxException e) { log.info(e.getMessage()); throw DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName()); } if (checkBaseUrl == null || !checkBaseUrl.equals(baseUrl)) { throw DcCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName()); } } }
From source file:io.personium.core.rs.cell.MessageODataResource.java
/** * To????baseUrl??????.// ww w .jav a 2s . c o m * @param toValue to??? * @param baseUrl baseUrl */ public static void validateToValue(String toValue, String baseUrl) { if (toValue == null) { return; } // URL?? String checkBaseUrl = null; String[] uriList = toValue.split(","); for (String uriStr : uriList) { try { URI uri = new URI(uriStr); checkBaseUrl = uri.getScheme() + "://" + uri.getHost(); int port = uri.getPort(); if (port != -1) { checkBaseUrl += ":" + Integer.toString(port); } checkBaseUrl += "/"; } catch (URISyntaxException e) { log.info(e.getMessage()); throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName()); } if (checkBaseUrl == null || !checkBaseUrl.equals(baseUrl)) { throw PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(SentMessage.P_TO.getName()); } } }
From source file:org.apache.jackrabbit.core.value.InternalValue.java
/** * Create a new internal value from the given JCR value. * If the data store is enabled, large binary values are stored in the data store. * * @param value the JCR value// w w w .j a v a 2 s .c o m * @param resolver * @param store the data store * @return the created internal value */ public static InternalValue create(Value value, NamePathResolver resolver, DataStore store) throws ValueFormatException, RepositoryException { switch (value.getType()) { case PropertyType.BINARY: InternalValue result; if (USE_DATA_STORE) { BLOBFileValue blob = null; if (value instanceof BinaryValueImpl) { BinaryValueImpl bin = (BinaryValueImpl) value; DataIdentifier identifier = bin.getDataIdentifier(); if (identifier != null) { // access the record to ensure it is not garbage collected if (store.getRecordIfStored(identifier) != null) { // it exists - so we don't need to stream it again // but we need to create a new object because the original // one might be in a different data store (repository) blob = BLOBInDataStore.getInstance(store, identifier); } } } if (blob == null) { blob = getBLOBFileValue(store, value.getBinary().getStream(), true); } result = new InternalValue(blob); } else if (value instanceof BLOBFileValue) { result = new InternalValue((BLOBFileValue) value); } else { InputStream stream = value.getBinary().getStream(); try { result = createTemporary(stream); } finally { IOUtils.closeQuietly(stream); } } return result; case PropertyType.BOOLEAN: return create(value.getBoolean()); case PropertyType.DATE: return create(value.getDate()); case PropertyType.DOUBLE: return create(value.getDouble()); case PropertyType.DECIMAL: return create(value.getDecimal()); case PropertyType.LONG: return create(value.getLong()); case PropertyType.REFERENCE: return create(new UUID(value.getString())); case PropertyType.WEAKREFERENCE: return create(new UUID(value.getString()), true); case PropertyType.URI: try { return create(new URI(value.getString())); } catch (URISyntaxException e) { throw new ValueFormatException(e.getMessage()); } case PropertyType.NAME: try { if (value instanceof QValueValue) { QValue qv = ((QValueValue) value).getQValue(); if (qv instanceof InternalValue) { return (InternalValue) qv; } else { return create(qv.getName()); } } else { return create(resolver.getQName(value.getString())); } } catch (NameException e) { throw new ValueFormatException(e.getMessage()); } case PropertyType.PATH: try { if (value instanceof QValueValue) { QValue qv = ((QValueValue) value).getQValue(); if (qv instanceof InternalValue) { return (InternalValue) qv; } else { return create(qv.getPath()); } } else { return create(resolver.getQPath(value.getString(), false)); } } catch (MalformedPathException mpe) { throw new ValueFormatException(mpe.getMessage()); } case PropertyType.STRING: return create(value.getString()); default: throw new IllegalArgumentException("illegal value"); } }