List of usage examples for org.apache.commons.httpclient URIException getMessage
public String getMessage()
From source file:org.archive.wayback.util.htmllex.ParseContext.java
/** * Resolve possibly-relative {@code url} with {@code baseUrl} set to * this object. //from ww w . ja va 2 s .com * <p>Caveat: this method no longer unescape HTML entities in {@code url}. * HTML entities must be all unescaped before calling method.</p> * @param url which should be resolved * @return absolute URL. * @throws URISyntaxException if the input URL is malformed */ public String resolve(String url) throws URISyntaxException { int hashIdx = url.indexOf('#'); String frag = ""; if (hashIdx != -1) { frag = url.substring(hashIdx); url = url.substring(0, hashIdx); } if (baseUrl == null) { // TODO: log ? return url + frag; } try { url = UsableURIFactory.getInstance(baseUrl, url).toString() + frag; } catch (URIException e) { LOGGER.warning("FAILED RESOLVE: base(" + baseUrl + ") frag(" + url + ") error(" + e.getMessage() + ")"); url = url + frag; } return url; }
From source file:org.asimba.util.saml2.confederation.SAML2Confederation.java
/** * Helper to establish the full source of the MetadataProvider for a requestor or idp * @param sSourceRef ID of the requestor or IDP; if null, the generic source is used * @return Full qualified path to the metadata-source for the provided entity * @throws OAException/*from www. ja v a2 s. c om*/ */ protected String getParamSourceRef(MetadataSourceDefinition oMSDef, String sSourceRef) throws OAException { try { if (sSourceRef == null) { return oMSDef._sGenericSourceLocation; } else { // Establish location: String sEncodedSourceReg = URIUtil.encodeQuery(sSourceRef); String re = "${sourceref}"; String search = "\\" + re.replace("{", "\\{").replace("}", "\\}"); return oMSDef._sSpecificSourceLocation.replaceAll(search, sEncodedSourceReg); } } catch (URIException ue) { _oLogger.error("Exception occurred when encoding URI: " + ue.getMessage()); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:org.eclipse.mylyn.internal.oslc.core.client.AbstractOslcClient.java
protected void handleReturnCode(int code, HttpMethodBase method) throws CoreException { try {//from www. jav a 2s . com if (code == java.net.HttpURLConnection.HTTP_OK) { return;// Status.OK_STATUS; } else if (code == java.net.HttpURLConnection.HTTP_MOVED_TEMP || code == java.net.HttpURLConnection.HTTP_CREATED) { // A new resource created... return;// Status.OK_STATUS; } else if (code == java.net.HttpURLConnection.HTTP_UNAUTHORIZED || code == java.net.HttpURLConnection.HTTP_FORBIDDEN) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Unable to log into server, ensure repository credentials are correct.")); //$NON-NLS-1$ } else if (code == java.net.HttpURLConnection.HTTP_PRECON_FAILED) { // Mid-air collision throw new CoreException( new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Mid-air collision occurred.")); //$NON-NLS-1$ } else if (code == java.net.HttpURLConnection.HTTP_CONFLICT) { throw new CoreException( new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "A conflict occurred.")); //$NON-NLS-1$ } else { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Unknown error occurred. Http Code: " + code + " Request: " + method.getURI() //$NON-NLS-1$//$NON-NLS-2$ + " Response: " //$NON-NLS-1$ + method.getResponseBodyAsString())); } } catch (URIException e) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$ + e.getMessage())); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, IOslcCoreConstants.ID_PLUGIN, "Network Error: " //$NON-NLS-1$ + e.getMessage())); } }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * //ww w . j a va2s . co m * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.exist.xquery.modules.httpclient.BaseHTTPClientFunction.java
/** * Takes the HTTP Response Body from the HTTP Method and attempts to insert it into the response tree we are building. * * <p>Conversion Preference - 1) Try and parse as XML, if successful returns a Node 2) Try and parse as HTML returning as XML compatible HTML, if * successful returns a Node 3) Return as base64Binary encoded data</p> * * @param context The context of the calling XQuery * @param method The HTTP Request Method * @param builder The MemTreeBuilder that is being used * * @throws IOException /*from w w w. j av a2s.co m*/ * @throws XPathException */ private void insertResponseBody(final XQueryContext context, final HttpMethod method, final MemTreeBuilder builder, final Map<String, Boolean> parserFeatures, final Map<String, String> parserProperties) throws IOException, XPathException { NodeImpl responseNode = null; final InputStream bodyAsStream = method.getResponseBodyAsStream(); // check if there is a response body if (bodyAsStream != null) { CachingFilterInputStream cfis = null; FilterInputStreamCache cache = null; try { //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt) cache = FilterInputStreamCacheFactory .getCacheInstance(new FilterInputStreamCacheFactory.FilterInputStreamCacheConfiguration() { @Override public String getCacheClass() { return (String) context.getBroker().getConfiguration() .getProperty(Configuration.BINARY_CACHE_CLASS_PROPERTY); } }); cfis = new CachingFilterInputStream(cache, bodyAsStream); //mark the start of the stream cfis.mark(Integer.MAX_VALUE); // determine the type of the response document final Header responseContentType = method.getResponseHeader("Content-Type"); final MimeType responseMimeType = getResponseMimeType(responseContentType); if (responseContentType != null) { builder.addAttribute(new QName("mimetype", null, null), responseContentType.getValue()); } //try and parse the response as XML try { //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread final InputStream shieldedInputStream = new CloseShieldInputStream(cfis); responseNode = (NodeImpl) ModuleUtils.streamToXML(context, shieldedInputStream); builder.addAttribute(new QName("type", null, null), "xml"); responseNode.copyTo(null, new DocumentBuilderReceiver(builder)); } catch (final SAXException se) { // could not parse to xml // not an error in itself, it will be treated either as HTML, // text or binary here below final String msg = "Request for URI '" + method.getURI().toString() + "' Could not parse http response content as XML (will try html, text or fallback to binary): " + se.getMessage(); if (logger.isDebugEnabled()) { logger.debug(msg, se); } else { logger.info(msg); } } catch (final IOException ioe) { final String msg = "Request for URI '" + method.getURI().toString() + "' Could not read http response content: " + ioe.getMessage(); logger.error(msg, ioe); throw new XPathException(msg, ioe); } if (responseNode == null) { //response is NOT parseable as XML //is it a html document? if (responseMimeType.getName().equals(MimeType.HTML_TYPE.getName())) { //html document try { //reset the stream to the start, as we need to reuse since attempting to parse to XML cfis.reset(); //parse html to xml(html) //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread final InputStream shieldedInputStream = new CloseShieldInputStream(cfis); responseNode = (NodeImpl) ModuleUtils .htmlToXHtml(context, method.getURI().toString(), new InputSource(shieldedInputStream), parserFeatures, parserProperties) .getDocumentElement(); builder.addAttribute(new QName("type", null, null), "xhtml"); responseNode.copyTo(null, new DocumentBuilderReceiver(builder)); } catch (final URIException ue) { throw new XPathException(this, ue.getMessage(), ue); } catch (final SAXException se) { //could not parse to xml(html) logger.debug( "Could not parse http response content from HTML to XML: " + se.getMessage(), se); } } } if (responseNode == null) { //reset the stream to the start, as we need to reuse since attempting to parse to HTML->XML cfis.reset(); if (responseMimeType.getName().startsWith("text/")) { // Assume it's a text body and URL encode it builder.addAttribute(new QName("type", null, null), "text"); builder.addAttribute(new QName("encoding", null, null), "URLEncoded"); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte buf[] = new byte[4096]; int read = -1; while ((read = cfis.read(buf)) > -1) { baos.write(buf); } builder.characters(URLEncoder.encode(EncodingUtil.getString(baos.toByteArray(), ((HttpMethodBase) method).getResponseCharSet()), "UTF-8")); baos.close(); } else { // Assume it's a binary body and Base64 encode it builder.addAttribute(new QName("type", null, null), "binary"); builder.addAttribute(new QName("encoding", null, null), "Base64Encoded"); BinaryValue binary = null; try { binary = BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), cfis); builder.characters(binary.getStringValue()); } finally { // free resources if (binary != null) { binary.destroy(context, null); } } } } } finally { if (cache != null) { try { cache.invalidate(); } catch (final IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } if (cfis != null) { try { cfis.close(); } catch (final IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } } } }
From source file:org.glite.slcs.shibclient.ShibbolethClient.java
/** * Processes the IdP response as a Browser/POST * //from w w w .j a va 2 s .c o m * @param idp * The {@link IdentityProvider}. * @param idpSSOResponseURI * The IdP SSO reponse {@link URI}. * @return the SP URI to go to * @throws RemoteException */ private URI processIdPBrowserPOST(IdentityProvider idp, URI idpSSOResponseURI, InputStream htmlStream) throws RemoteException { // return value URI browserPostResponseURI = null; RemoteException remoteException = null; try { Source source = new Source(htmlStream); List<Element> forms = source.findAllElements(Tag.FORM); if (!forms.isEmpty()) { // check if form contains a valid SAML Browser/POST for (Element form : forms) { String spSAMLURL = form.getAttributeValue("ACTION"); LOG.debug("SAML Browser/POST URL=" + spSAMLURL); if (spSAMLURL == null) { // no SAML post URL found String htmlBody = inputStreamToString(htmlStream); LOG.error("No SAML Browser/POST FORM ACTION found: " + idpSSOResponseURI + ": " + htmlBody); remoteException = new RemoteException("No SAML Browser/POST FORM ACTION found: " + idpSSOResponseURI + ". Please see the log file."); break; // exit loop } // create POST method PostMethod postSPSAMLMethod = new PostMethod(spSAMLURL); // add all HIDDEN fields to POST List<FormControl> formControls = form.findFormControls(); for (FormControl control : formControls) { FormControlType type = control.getFormControlType(); if (type.equals(FormControlType.HIDDEN)) { String name = control.getName(); Collection<CharSequence> values = control.getValues(); for (CharSequence value : values) { LOG.debug("HIDDEN " + name + "=" + value); // add all hidden fields postSPSAMLMethod.addParameter(name, (String) value); } } } // execute the SAML post LOG.info("POST SPSAMLMethod: " + postSPSAMLMethod.getURI()); int spSAMLResponseStatus = executeMethod(postSPSAMLMethod); LOG.debug(postSPSAMLMethod.getStatusLine()); // status must be 302 and redirect Location Header location = postSPSAMLMethod.getResponseHeader("Location"); if (spSAMLResponseStatus == 302 && location != null) { String url = location.getValue(); browserPostResponseURI = new URI(url, false); LOG.debug("Redirect: " + browserPostResponseURI); } else { LOG.error( "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location); remoteException = new RemoteException( "Unexpected SP response: Status=" + spSAMLResponseStatus + " Location=" + location); } LOG.trace("postSPSAMLMethod.releaseConnection()"); postSPSAMLMethod.releaseConnection(); } // forms loop } else { // no SAML post found String htmlBody = inputStreamToString(htmlStream); LOG.error("No SAML Browser/POST profile found: " + idpSSOResponseURI + ": " + htmlBody); remoteException = new RemoteException( "No SAML Browser/POST profile found: " + idpSSOResponseURI + ". Please see the log file."); } } catch (URIException e) { e.printStackTrace(); remoteException = new RemoteException(e.getMessage(), e); } catch (IOException e) { e.printStackTrace(); remoteException = new RemoteException(e.getMessage(), e); } if (browserPostResponseURI == null) { if (remoteException != null) { throw remoteException; } } return browserPostResponseURI; }
From source file:org.jasig.portlet.calendar.adapter.exchange.CommonsHttpConnection.java
public URI getUri() throws URISyntaxException { try {/* w ww.j a va2 s. c o m*/ return new URI(postMethod.getURI().toString()); } catch (URIException ex) { throw new URISyntaxException("", ex.getMessage()); } }
From source file:org.kuali.kra.lookup.S2sOpportunityLookupableHelperServiceImpl.java
public Collection performLookup(LookupForm lookupForm, Collection resultTable, boolean bounded) { Collection displayList;//from w w w . j ava 2s. co m displayList = super.performLookup(lookupForm, resultTable, bounded); ResultRow row; for (Iterator iter = resultTable.iterator(); iter.hasNext();) { row = (ResultRow) iter.next(); List<Column> columns = row.getColumns(); if (!lookupForm.getBackLocation().contains("proposalDevelopmentGrantsGov")) { String cfdaNumber = columns.get(0).getPropertyValue(); String closingDate = columns.get(1).getPropertyValue(); String competetionId = columns.get(2).getPropertyValue(); String instructionUrl = columns.get(3).getPropertyValue(); String openingDate = columns.get(4).getPropertyValue(); String oppurtunityId = columns.get(5).getPropertyValue(); String oppurtunityTitle = columns.get(6).getPropertyValue(); String schemaUrl = columns.get(7).getPropertyValue(); String createProposalUrl = null; try { String encodedUrl = URIUtil.encodeQuery(lookupForm.getBackLocation() + "?channelTitle=CreateProposal&channelUrl=proposalDevelopmentProposal.do?methodToCall=docHandler&command=initiate&docTypeName=ProposalDevelopmentDocument" + "&createProposalFromGrantsGov=true" + "&document.developmentProposalList[0].s2sOpportunity.cfdaNumber=" + cfdaNumber + "&document.developmentProposalList[0].s2sOpportunity.opportunityId=" + oppurtunityId + "&document.developmentProposalList[0].s2sOpportunity.opportunityTitle=" + oppurtunityTitle + "&document.developmentProposalList[0].s2sOpportunity.closingDate=" + closingDate + "&document.developmentProposalList[0].s2sOpportunity.openingDate=" + openingDate + "&document.developmentProposalList[0].s2sOpportunity.instructionUrl=" + instructionUrl + "&document.developmentProposalList[0].s2sOpportunity.competetionId=" + competetionId + "&document.developmentProposalList[0].s2sOpportunity.schemaUrl=" + schemaUrl); createProposalUrl = "<a href=" + encodedUrl + ">Create Proposal</a>"; row.setReturnUrl(createProposalUrl); } catch (URIException e) { LOG.error(e.getMessage(), e); } } for (Iterator iterator = columns.iterator(); iterator.hasNext();) { Column col = (Column) iterator.next(); if (StringUtils.equalsIgnoreCase(col.getColumnTitle(), "Instruction Page") || StringUtils.equalsIgnoreCase(col.getColumnTitle(), "Schema URL")) { col.setPropertyURL(col.getPropertyValue()); } } } return displayList; }
From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java
private String getFirstLiteralOfProperty(String ns) { NodeIterator it = this.model.listObjectsOfProperty(this.model.getProperty(ns)); if (it.hasNext()) { try {/*from w w w.java2 s .com*/ return URIUtil.encodeQuery(it.next().asLiteral().getLexicalForm(), "UTF-8"); } catch (URIException e) { LOG.error(super.subject + " " + e.getMessage(), e); } catch (LiteralRequiredException le) { LOG.warn(le.getMessage(), le); } } return null; }
From source file:org.openhab.binding.garadget.internal.Connection.java
/** * Send a command to the Particle REST API (convenience function). * * @param device/*from w w w . j a v a 2 s .c o m*/ * the device context, or <code>null</code> if not needed for this command. * @param funcName * the function name to call, or variable/field to retrieve if <code>command</code> is * <code>null</code>. * @param user * the user name to use in Basic Authentication if the funcName would require Basic Authentication. * @param pass * the password to use in Basic Authentication if the funcName would require Basic Authentication. * @param command * the command to send to the API. * @param proc * a callback object that receives the status code and response body, or <code>null</code> if not * needed. */ public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) { String url = null; String httpMethod = null; String content = null; String contentType = null; Properties headers = new Properties(); logger.trace("sendCommand: funcName={}", funcName); switch (funcName) { case "createToken": httpMethod = HTTP_POST; url = TOKEN_URL; content = command; contentType = APPLICATION_FORM_URLENCODED; break; case "deleteToken": httpMethod = HTTP_DELETE; url = String.format(ACCESS_TOKENS_URL, tokens.accessToken); break; case "getDevices": httpMethod = HTTP_GET; url = String.format(GET_DEVICES_URL, tokens.accessToken); break; default: url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken); if (command == null) { // retrieve a variable httpMethod = HTTP_GET; } else { // call a function httpMethod = HTTP_POST; content = command; contentType = APPLICATION_JSON; } break; } HttpClient client = new HttpClient(); // Only perform basic authentication when we aren't using OAuth if (!url.contains("access_token=")) { Credentials credentials = new UsernamePasswordCredentials(user, pass); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } HttpMethod method = createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : headers.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey))); logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey)); } try { // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null)); logger.trace("content='{}', contentType='{}'", content, contentType); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug(e.getMessage()); } } int statusCode = client.executeMethod(method); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { logger.debug("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("Body of response: {}", responseBody); } if (proc != null) { proc.handleResponse(statusCode, responseBody); } } catch (HttpException he) { logger.warn("{}", he); } catch (IOException ioe) { logger.debug("{}", ioe); } finally { method.releaseConnection(); } }