List of usage examples for java.net URLConnection getContentType
public String getContentType()
From source file:com.apache.ivy.BasicURLHandler.java
public URLInfo getURLInfo(URL url, int timeout) { // Install the IvyAuthenticator if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) { IvyAuthenticator.install();//from w w w . j a v a2 s. c o m } URLConnection con = null; try { url = normalizeToURL(url); con = url.openConnection(); con.setRequestProperty("User-Agent", "Apache Ivy/1.0");//+ Ivy.getIvyVersion()); if (con instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) con; if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) { httpCon.setRequestMethod("HEAD"); } if (checkStatusCode(url, httpCon)) { String bodyCharset = getCharSetFromContentType(con.getContentType()); return new URLInfo(true, httpCon.getContentLength(), con.getLastModified(), bodyCharset); } } else { int contentLength = con.getContentLength(); if (contentLength <= 0) { return UNAVAILABLE; } else { // TODO: not HTTP... maybe we *don't* want to default to ISO-8559-1 here? String bodyCharset = getCharSetFromContentType(con.getContentType()); return new URLInfo(true, contentLength, con.getLastModified(), bodyCharset); } } } catch (UnknownHostException e) { // Message.warn("Host " + e.getMessage() + " not found. url=" + url); // Message.info("You probably access the destination server through " // + "a proxy server that is not well configured."); } catch (IOException e) { //Message.error("Server access error at url " + url, e); } finally { disconnect(con); } return UNAVAILABLE; }
From source file:gr.iti.mklab.bubing.parser.ITIHTMLParser.java
public void processImageURL(URI pageUri, URI base, String imageUri, String altText) throws MalformedURLException, IOException { URI url = BURL.parse(imageUri); if (url != null) { URI resolved = base.resolve(url); String resolvedStr = resolved.toString(); //avoid trying to index the same image multiple times if (!ItiAgent.UNIQUE_IMAGE_URLS.mightContain(resolvedStr)) { // Put it in the bloom filter even if it is not saved eventually // to avoid doing the same checks for the same image a second time ItiAgent.UNIQUE_IMAGE_URLS.put(resolvedStr); final URLConnection con = resolved.toURL().openConnection(); if (Utils.checkContentHeaders(con.getContentLength(), con.getContentType())) { InputStream is = con.getInputStream(); BufferedImage image = null; try { image = ImageIO.read(is); } catch (IllegalArgumentException e) { // this exception is probably thrown because of a greyscale jpeg image System.out.println("Exception: " + e.getMessage() + " | Image: " + imageUri); image = ImageIOGreyScale.read(is); // retry with the modified class } catch (MalformedURLException e) { System.out.println("Malformed url exception. Url: " + imageUri); }/*from ww w. j av a2 s . co m*/ if (Utils.checkImage(image)) { Image item = new Image(); item.setUrl(resolvedStr); item.setTitle(altText); item.setWidth(image.getWidth()); item.setHeight(image.getHeight()); item.setWebPageUrl(pageUri.toString()); item.setLastModifiedDate(new Date(con.getLastModified())); item.setObjectId(new ObjectId()); try { VisualIndexer.getInstance().indexAndStore(image, item); } catch (Exception e) { System.out.println("HTMLImageParser parse exeption: " + e); } } } } } }
From source file:com.seajas.search.contender.scripting.XmlHtmlReader.java
/** * Creates a Reader using the InputStream of a URLConnection. * <p>/*ww w. j a v a 2 s . co m*/ * If the URLConnection is not of type HttpURLConnection and there is not 'content-type' header in the fetched data it uses the same logic used for files. * <p> * If the URLConnection is a HTTP Url or there is a 'content-type' header in the fetched data it uses the same logic used for an InputStream with content-type. * <p> * It does a lenient charset encoding detection, check the constructor with the lenient parameter for details. * <p> * * @param conn * URLConnection to create a Reader from. * @throws IOException * thrown if there is a problem reading the stream of the URLConnection. * */ public XmlHtmlReader(final URLConnection conn) throws IOException { _defaultEncoding = _staticDefaultEncoding; boolean lenient = true; if (conn instanceof HttpURLConnection) { try { doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); } catch (XmlReaderException ex) { doLenientDetection(conn.getContentType(), ex); } } else if (conn.getContentType() != null) { try { doHttpStream(conn.getInputStream(), conn.getContentType(), lenient); } catch (XmlReaderException ex) { doLenientDetection(conn.getContentType(), ex); } } else { try { doRawStream(conn.getInputStream(), lenient); } catch (XmlReaderException ex) { doLenientDetection(null, ex); } } }
From source file:org.sakaiproject.lessonbuildertool.service.AjaxServer.java
public String getMimeType(String url) { Session s = SessionManager.getCurrentSession(); if (s == null || s.getUserId() == null) { // return ""; }/*www .ja v a2s . c om*/ if (SimplePageBean.getYoutubeKeyFromUrl(url) != null) return "application/youtube"; String mimeType = ""; URLConnection conn = null; try { conn = new URL(new URL(ServerConfigurationService.getServerUrl()), url).openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); conn.connect(); String t = conn.getContentType(); if (t != null && !t.equals("")) { int i = t.indexOf(";"); if (i >= 0) t = t.substring(0, i); t = t.trim(); mimeType = t; } } catch (Exception e) { } finally { if (conn != null) { try { conn.getInputStream().close(); } catch (Exception e) { // log.error("getTypeOfUrl unable to close " + e); } } } if (mimeType == null || mimeType.equals("")) { String name = url; // starts after last / int i = name.lastIndexOf("/"); if (i >= 0) name = name.substring(i + 1); String extension = null; i = name.lastIndexOf("."); if (i > 0) extension = name.substring(i + 1); if (extension == null) return ""; if (SimplePageBean.imageTypes.contains(extension)) { return "image/unknown"; } if (extension.equals("html") || extension.equals("htm")) { return "text/html"; } else if (extension.equals("xhtml") || extension.equals("xht")) { return "application/xhtml+xml"; } else { return ""; } } return mimeType; }
From source file:com.iskyshop.manage.seller.action.OrderSellerAction.java
private TransInfo query_ship_getData(String id) { TransInfo info = new TransInfo(); OrderForm obj = this.orderFormService.getObjById(CommUtil.null2Long(id)); try {// w ww .ja va 2 s . c o m ExpressCompany ec = this.queryExpressCompany(obj.getExpress_info()); URL url = new URL("http://api.kuaidi100.com/api?id=" + this.configService.getSysConfig().getKuaidi_id() + "&com=" + (ec != null ? ec.getCompany_mark() : "") + "&nu=" + obj.getShipCode() + "&show=0&muti=1&order=asc"); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); String type = con.guessContentTypeFromStream(urlStream); String charSet = null; if (type == null) type = con.getContentType(); if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0) return info; if (type.indexOf("charset=") > 0) charSet = type.substring(type.indexOf("charset=") + 8); byte b[] = new byte[10000]; int numRead = urlStream.read(b); String content = new String(b, 0, numRead, charSet); while (numRead != -1) { numRead = urlStream.read(b); if (numRead != -1) { // String newContent = new String(b, 0, numRead); String newContent = new String(b, 0, numRead, charSet); content += newContent; } } info = Json.fromJson(TransInfo.class, content); urlStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info; }
From source file:org.geosdi.geoplatform.gui.server.service.impl.LayerService.java
@Override public boolean checkWmsGetMapUrl(String urlString) throws GeoPlatformException { try {//from w w w .j a v a 2s . co m URL url = new URL(urlString); URLConnection myURLConnection = url.openConnection(); myURLConnection.connect(); logger.debug("#################RESPONSE : {}\n\n", IOUtils.toString(myURLConnection.getInputStream())); String contentType = myURLConnection.getContentType(); logger.info("#####################CONTENT_TYPE : {}\n", contentType); if (!contentType.contains("xml")) { return true; } } catch (IOException ex) { logger.error("Error on executing Check url: {}", ex.getMessage()); throw new GeoPlatformException("Error on executing ParseURLServlet."); } return false; }
From source file:org.apache.cocoon.components.crawler.SimpleCocoonCrawlerImpl.java
/** * Compute list of links from the url./* w w w . j ava 2 s . co m*/ * <p> * Check for include, exclude pattern, content-type, and if url * has been craweled already. * </p> * * @param url Crawl this URL * @return List of URLs, which are links from url, asserting the conditions. * @since */ private List getLinks(URL url) { ArrayList url_links = null; String sURL = url.toString(); if (!isIncludedURL(sURL) || isExcludedURL(sURL)) { return null; } // don't try to get links for url which has been crawled already if (crawled.contains(sURL)) { return null; } // mark it as crawled crawled.add(sURL); // get links of url if (getLogger().isDebugEnabled()) { getLogger().debug("Getting links of URL " + sURL); } BufferedReader br = null; try { sURL = url.getFile(); URL links = new URL(url, sURL + ((sURL.indexOf("?") == -1) ? "?" : "&") + linkViewQuery); URLConnection links_url_connection = links.openConnection(); links_url_connection.setRequestProperty("Accept", accept); links_url_connection.setRequestProperty("User-Agent", userAgent); links_url_connection.connect(); InputStream is = links_url_connection.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String contentType = links_url_connection.getContentType(); if (contentType == null) { if (getLogger().isDebugEnabled()) { getLogger().debug("Ignoring " + sURL + " (no content type)"); } // there is a check on null in the calling method return null; } int index = contentType.indexOf(';'); if (index != -1) { contentType = contentType.substring(0, index); } if (getLogger().isDebugEnabled()) { getLogger().debug("Content-type: " + contentType); } if (contentType.equals(linkContentType)) { url_links = new ArrayList(); // content is supposed to be a list of links, // relative to current URL String line; while ((line = br.readLine()) != null) { final URL newUrl = new URL(url, line); final String sNewUrl = newUrl.toString(); boolean add_url = true; // don't add new_url twice if (add_url) { add_url &= !url_links.contains(sNewUrl); } // don't add new_url if it has been crawled already if (add_url) { add_url &= !crawled.contains(sNewUrl); } // don't add if is not matched by existing include definition if (add_url) { add_url &= isIncludedURL(sNewUrl); } // don't add if is matched by existing exclude definition if (add_url) { add_url &= !isExcludedURL(sNewUrl); } if (add_url) { if (getLogger().isDebugEnabled()) { getLogger().debug("Add URL: " + sNewUrl); } url_links.add(newUrl); } } // now we have a list of URL which should be examined } } catch (IOException ioe) { getLogger().warn("Problems get links of " + url, ioe); } finally { if (br != null) { try { br.close(); br = null; } catch (IOException ignored) { } } } return url_links; }
From source file:org.ecoinformatics.datamanager.download.DownloadHandler.java
/** * Gets content from given source and writes it to DataStorageInterface * to store them. This method will be called by run() * // w w w. java2 s. c om * @param resourceName the URL to the source data to be retrieved */ protected boolean getContentFromSource(String resourceName) { boolean successFlag = false; QualityCheck onlineURLsQualityCheck = null; boolean onlineURLsException = false; // used to determine status of onlineURLs quality check if (resourceName != null) { resourceName = resourceName.trim(); } if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://") || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) { // get the data from a URL int responseCode = 0; String responseMessage = null; try { URL url = new URL(resourceName); boolean isFTP = false; if (entity != null) { String contentType = null; // Find the right MIME type and set it as content type if (resourceName.startsWith("http")) { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.connect(); contentType = httpURLConnection.getContentType(); responseCode = httpURLConnection.getResponseCode(); responseMessage = httpURLConnection.getResponseMessage(); } else if (resourceName.startsWith("file")) { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); contentType = urlConnection.getContentType(); } else { // FTP isFTP = true; contentType = "application/octet-stream"; } entity.setUrlContentType(contentType); } if (!isFTP) { // HTTP(S) or FILE InputStream filestream = url.openStream(); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { filestream.close(); } } else { // FTP String[] urlParts = resourceName.split("/"); String address = urlParts[2]; String dir = "/"; for (int i = 3; i < urlParts.length - 1; i++) { dir += urlParts[i] + "/"; } String fileName = urlParts[urlParts.length - 1]; FTPClient ftpClient = new FTPClient(); ftpClient.connect(address); ftpClient.login(ANONYMOUS, anonymousFtpPasswd); ftpClient.changeWorkingDirectory(dir); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking InputStream filestream = ftpClient.retrieveFileStream(fileName); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { try { filestream.close(); } catch (IOException e) { exception = new DataSourceNotFoundException(String .format("Error closing local file '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } // logout and disconnect if FTP session if (resourceName.startsWith("ftp") && ftpClient != null) { try { ftpClient.enterLocalActiveMode(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { exception = new DataSourceNotFoundException( String.format("Error disconnecting from FTP with resource '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } } } catch (MalformedURLException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); exception = new DataSourceNotFoundException( String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage)); } catch (IOException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); if (responseCode > 0) { eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage); } exception = new DataSourceNotFoundException( String.format("The URL '%s' is not reachable: %s", resourceName, eMessage)); } // Initialize the "Online URLs are live" quality check String qualityCheckIdentifier = "onlineURLs"; QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier); onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate); if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) { String resourceNameEscaped = embedInCDATA(resourceName); if (!onlineURLsException) { onlineURLsQualityCheck.setStatus(Status.valid); onlineURLsQualityCheck.setFound("true"); onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped); } else { onlineURLsQualityCheck.setFailedStatus(); onlineURLsQualityCheck.setFound("false"); String explanation = "Failed to access URL: " + resourceNameEscaped; explanation = explanation + "; " + embedInCDATA(exception.getMessage()); onlineURLsQualityCheck.setExplanation(explanation); } entity.addQualityCheck(onlineURLsQualityCheck); } return successFlag; } else if (resourceName != null && resourceName.startsWith("ecogrid://")) { // get the docid from url int start = resourceName.indexOf("/", 11) + 1; //log.debug("start: " + start); int end = resourceName.indexOf("/", start); if (end == -1) { end = resourceName.length(); } //log.debug("end: " + end); String ecogridIdentifier = resourceName.substring(start, end); // pass this docid and get data item //System.out.println("the endpoint is "+ECOGRIDENDPOINT); //System.out.println("The identifier is "+ecogridIdentifier); //return false; return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier); } else if (resourceName != null && resourceName.startsWith("srb://")) { // get srb docid from the url String srbIdentifier = transformSRBurlToDocid(resourceName); // reset endpoint for srb (This is hack we need to figure ou // elegent way to do this //mEndPoint = Config.getValue("//ecogridService/srb/endPoint"); // pass this docid and get data item //log.debug("before get srb data"); return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier); } else { successFlag = false; return successFlag; } }
From source file:edu.lternet.pasta.dml.download.DownloadHandler.java
/** * Gets content from given source and writes it to DataStorageInterface * to store them. This method will be called by run() * //from ww w. j av a2 s . co m * @param resourceName the URL to the source data to be retrieved */ protected boolean getContentFromSource(String resourceName) { boolean successFlag = false; QualityCheck onlineURLsQualityCheck = null; boolean onlineURLsException = false; // used to determine status of onlineURLs quality check if (resourceName != null) { resourceName = resourceName.trim(); } if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://") || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) { // get the data from a URL int responseCode = 0; String responseMessage = null; try { URL url = new URL(resourceName); boolean isFTP = false; if (entity != null) { String contentType = null; // Find the right MIME type and set it as content type if (resourceName.startsWith("http")) { HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.connect(); contentType = httpURLConnection.getContentType(); responseCode = httpURLConnection.getResponseCode(); responseMessage = httpURLConnection.getResponseMessage(); } else if (resourceName.startsWith("file")) { URLConnection urlConnection = url.openConnection(); urlConnection.connect(); contentType = urlConnection.getContentType(); } else { // FTP isFTP = true; contentType = "application/octet-stream"; } entity.setUrlContentType(contentType); } if (!isFTP) { // HTTP(S) or FILE InputStream filestream = url.openStream(); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { filestream.close(); } } else { // FTP String[] urlParts = resourceName.split("/"); String address = urlParts[2]; String dir = "/"; for (int i = 3; i < urlParts.length - 1; i++) { dir += urlParts[i] + "/"; } String fileName = urlParts[urlParts.length - 1]; FTPClient ftpClient = new FTPClient(); ftpClient.connect(address); ftpClient.login(ANONYMOUS, anonymousFtpPasswd); ftpClient.changeWorkingDirectory(dir); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking InputStream filestream = ftpClient.retrieveFileStream(fileName); try { successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream); } catch (IOException e) { exception = e; String errorMessage = e.getMessage(); if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) { onlineURLsException = true; } } finally { try { filestream.close(); } catch (IOException e) { exception = new DataSourceNotFoundException(String .format("Error closing local file '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } // logout and disconnect if FTP session if (resourceName.startsWith("ftp") && ftpClient != null) { try { ftpClient.enterLocalActiveMode(); ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { exception = new DataSourceNotFoundException( String.format("Error disconnecting from FTP with resource '%s': %s", resourceName, e.getMessage())); onlineURLsException = true; } } } } catch (MalformedURLException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage)); } catch (IOException e) { String eClassName = e.getClass().getName(); String eMessage = String.format("%s: %s", eClassName, e.getMessage()); if (responseCode > 0) { eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage); } onlineURLsException = true; exception = new DataSourceNotFoundException( String.format("The URL '%s' is not reachable: %s", resourceName, eMessage)); } // Initialize the "Online URLs are live" quality check String qualityCheckIdentifier = "onlineURLs"; QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier); onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate); if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) { String resourceNameEscaped = embedInCDATA(resourceName); if (!onlineURLsException) { onlineURLsQualityCheck.setStatus(Status.valid); onlineURLsQualityCheck.setFound("true"); onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped); } else { onlineURLsQualityCheck.setFailedStatus(); onlineURLsQualityCheck.setFound("false"); String explanation = "Failed to access URL: " + resourceNameEscaped; explanation = explanation + "; " + embedInCDATA(exception.getMessage()); onlineURLsQualityCheck.setExplanation(explanation); } entity.addQualityCheck(onlineURLsQualityCheck); } return successFlag; } else if (resourceName != null && resourceName.startsWith("ecogrid://")) { // get the docid from url int start = resourceName.indexOf("/", 11) + 1; //log.debug("start: " + start); int end = resourceName.indexOf("/", start); if (end == -1) { end = resourceName.length(); } //log.debug("end: " + end); String ecogridIdentifier = resourceName.substring(start, end); // pass this docid and get data item //System.out.println("the endpoint is "+ECOGRIDENDPOINT); //System.out.println("The identifier is "+ecogridIdentifier); //return false; return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier); } else if (resourceName != null && resourceName.startsWith("srb://")) { // get srb docid from the url String srbIdentifier = transformSRBurlToDocid(resourceName); // reset endpoint for srb (This is hack we need to figure ou // elegent way to do this //mEndPoint = Config.getValue("//ecogridService/srb/endPoint"); // pass this docid and get data item //log.debug("before get srb data"); return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier); } else { successFlag = false; return successFlag; } }
From source file:org.phaidra.apihooks.APIRESTHooksImpl.java
/** * Runs the hook if enabled in fedora.fcfg. * * @param method The name of the method that calls the hook * @param pid The PID that is being accessed * @param params Method parameters, depend on the method called * @return String Hook verdict. Begins with "OK" if it's ok to proceed. * @throws APIHooksException If the remote call went wrong *///from w w w . j ava2s. com public String runHook(String method, DOWriter w, Context context, String pid, Object[] params) throws APIHooksException { String rval = null; // Only do this if the method is enabled in fedora.fcfg if (getParameter(method) == null) { log.debug("runHook: method |" + method + "| not configured, not calling webservice"); return "OK"; } Iterator i = context.subjectAttributes(); String attrs = ""; while (i.hasNext()) { String name = ""; try { name = (String) i.next(); String[] value = context.getSubjectValues(name); for (int j = 0; j < value.length; j++) { attrs += "&attr=" + URLEncoder.encode(name + "=" + value[j], "UTF-8"); log.debug("runHook: will send |" + name + "=" + value[j] + "| as subject attribute"); } } catch (NullPointerException ex) { log.debug( "runHook: caught NullPointerException while trying to retrieve subject attribute " + name); } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode subject attribute " + name); } } String paramstr = ""; try { for (int j = 0; j < params.length; j++) { paramstr += "¶m" + Integer.toString(j) + "="; if (params[j] != null) { String p = params[j].toString(); paramstr += URLEncoder.encode(p, "UTF-8"); } } } catch (UnsupportedEncodingException ex) { log.debug("runHook: caught UnsupportedEncodingException while trying to encode a parameter"); } String loginId = context.getSubjectValue(Constants.SUBJECT.LOGIN_ID.uri); log.debug("runHook: called for method=|" + method + "|, pid=|" + pid + "|"); try { // TODO: timeout? retries? URL url; URLConnection urlConn; DataOutputStream printout; BufferedReader input; url = new URL(getParameter("restmethod")); urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); printout = new DataOutputStream(urlConn.getOutputStream()); String content = "method=" + URLEncoder.encode(method, "UTF-8") + "&username=" + URLEncoder.encode(loginId, "UTF-8") + "&pid=" + URLEncoder.encode(pid, "UTF-8") + paramstr + attrs; printout.writeBytes(content); printout.flush(); printout.close(); // Get response data. input = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); String str; rval = ""; while (null != ((str = input.readLine()))) { rval += str + "\n"; } input.close(); String ct = urlConn.getContentType(); if (ct.startsWith("text/xml")) { log.debug("runHook: successful REST invocation for method |" + method + "|, returning: " + rval); } else if (ct.startsWith("text/plain")) { log.debug("runHook: successful REST invocation for method |" + method + "|, but hook returned an error: " + rval); throw new Exception(rval); } else { throw new Exception("Invalid content type " + ct); } } catch (Exception ex) { log.error("runHook: error calling REST hook: " + ex.toString()); throw new APIHooksException("Error calling REST hook: " + ex.toString(), ex); } return processResults(rval, w, context); }