List of usage examples for java.net URLConnection setAllowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
From source file:org.talend.mdm.commmon.util.datamodel.management.SecurityEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId != null) { Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)"); //$NON-NLS-1$ Matcher match = httpUrl.matcher(systemId); if (match.matches()) { StringBuilder buffer = new StringBuilder(); String credentials = Base64.encodeBase64String("admin:talend".getBytes()); //$NON-NLS-1$ URL url = new URL(systemId); URLConnection conn = url.openConnection(); conn.setAllowUserInteraction(true); conn.setDoOutput(true);// w w w . j a va2 s .c om conn.setDoInput(true); conn.setRequestProperty("Authorization", "Basic " + credentials); //$NON-NLS-1$ conn.setRequestProperty("Expect", "100-continue"); //$NON-NLS-1$ InputStreamReader doc = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(doc); String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); } return new InputSource(new StringReader(buffer.toString())); } else { int mark = systemId.indexOf("file:///"); //$NON-NLS-1$ String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0)); //$NON-NLS-1$ File file = new File(path); return new InputSource(file.toURL().openStream()); } } return null; }
From source file:com.amalto.core.util.SecurityEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId != null) { Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)"); Matcher match = httpUrl.matcher(systemId); if (match.matches()) { StringBuilder buffer = new StringBuilder(); String credentials = new String(Base64.encodeBase64("admin:talend".getBytes())); URL url = new URL(systemId); URLConnection conn = url.openConnection(); conn.setAllowUserInteraction(true); conn.setDoOutput(true);// ww w. ja v a 2s .c o m conn.setDoInput(true); conn.setRequestProperty("Authorization", "Basic " + credentials); conn.setRequestProperty("Expect", "100-continue"); InputStreamReader doc = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(doc); String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); } return new InputSource(new StringReader(buffer.toString())); } else { int mark = systemId.indexOf("file:///"); String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0)); File file = new File(path); return new InputSource(file.toURL().openStream()); } } return null; }
From source file:ar.com.zauber.common.image.impl.JREImageRetriver.java
/** * @param uc {@link URLConnection} a preparar. *///w w w. j av a2s.c o m private void prepare(final URLConnection uc) { uc.setAllowUserInteraction(false); uc.setReadTimeout(timeout * 1000); if (userAgent != null) { uc.setRequestProperty("User-Agent", userAgent); } }
From source file:org.imsglobal.simplelti.SimpleLTIUtil.java
public static Properties doLaunch(String lti2EndPoint, Properties newMap) { M_log.warning("Warning: SimpleLTIUtil using deprecated non-POST launch to -" + lti2EndPoint); Properties retProp = new Properties(); retProp.setProperty("status", "fail"); String postData = ""; // Yikes - iterating through properties is nasty for (Object okey : newMap.keySet()) { if (!(okey instanceof String)) continue; String key = (String) okey; if (key == null) continue; String value = newMap.getProperty(key); if (value == null) continue; if (value.equals("")) continue; value = encodeFormText(value);//www . j a v a 2 s . c o m if (postData.length() > 0) postData = postData + "&"; postData = postData + encodeFormText(key) + "=" + value; } if (postData != null) retProp.setProperty("_post_data", postData); dPrint("LTI2 POST=" + postData); String postResponse = null; URLConnection urlc = null; try { // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html URL url = new URL(lti2EndPoint); InputStream inp = null; // make connection, use post mode, and send query urlc = url.openConnection(); urlc.setDoOutput(true); urlc.setAllowUserInteraction(false); PrintStream ps = new PrintStream(urlc.getOutputStream()); ps.print(postData); ps.close(); dPrint("Post Complete"); inp = urlc.getInputStream(); // Retrieve result BufferedReader br = new BufferedReader(new InputStreamReader(inp)); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); postResponse = sb.toString(); if (postResponse == null) { setErrorMessage(retProp, "Launch REST Web Service returned nothing"); return retProp; } } catch (Exception e) { // Retrieve error stream if it exists if (urlc != null && urlc instanceof HttpURLConnection) { try { HttpURLConnection urlh = (HttpURLConnection) urlc; BufferedReader br = new BufferedReader(new InputStreamReader(urlh.getErrorStream())); String str; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str); sb.append("\n"); } br.close(); postResponse = sb.toString(); dPrint("LTI ERROR response=" + postResponse); } catch (Exception f) { dPrint("LTI Exception in REST call=" + e); // e.printStackTrace(); setErrorMessage(retProp, "Failed REST service call. Exception=" + e); postResponse = null; return retProp; } } else { dPrint("LTI General Failure" + e.getMessage()); // e.printStackTrace(); } } if (postResponse != null) retProp.setProperty("_post_response", postResponse); dPrint("LTI2 Response=" + postResponse); // Check to see if we received anything - and then parse it Map<String, String> respMap = null; if (postResponse == null) { setErrorMessage(retProp, "Web Service Returned Nothing"); return retProp; } else { if (postResponse.indexOf("<?xml") != 0) { int pos = postResponse.indexOf("<launchResponse"); if (pos > 0) { M_log.warning("Warning: Dropping first " + pos + " non-XML characters of response to find <launchResponse"); postResponse = postResponse.substring(pos); } } respMap = XMLMap.getMap(postResponse); } if (respMap == null) { String errorOut = postResponse; if (errorOut.length() > 500) { errorOut = postResponse.substring(0, 500); } M_log.warning("Error Parsing Web Service XML:\n" + errorOut + "\n"); setErrorMessage(retProp, "Error Parsing Web Service XML"); return retProp; } // We will tolerate this one backwards compatibility String launchUrl = respMap.get("/launchUrl"); String launchWidget = null; if (launchUrl == null) { launchUrl = respMap.get("/launchResponse/launchUrl"); } if (launchUrl == null) { launchWidget = respMap.get("/launchResponse/widget"); /* Remove until we have jTidy 0.8 or later in the repository if ( launchWidget != null && launchWidget.length() > 0 ) { M_log.warning("Pre Tidy:\n"+launchWidget); Tidy tidy = new Tidy(); tidy.setIndentContent(true); tidy.setSmartIndent(true); tidy.setPrintBodyOnly(true); tidy.setTidyMark(false); // tidy.setQuiet(true); // tidy.setShowWarnings(false); InputStream is = new ByteArrayInputStream(launchWidget.getBytes()); OutputStream os = new ByteArrayOutputStream(); tidy.parse(is,os); String tidyOutput = os.toString(); M_log.warning("Post Tidy:\n"+tidyOutput); if ( tidyOutput != null && tidyOutput.length() > 0 ) launchWidget = os.toString(); } */ } dPrint("launchUrl = " + launchUrl); dPrint("launchWidget = " + launchWidget); if (launchUrl == null && launchWidget == null) { String eMsg = respMap.get("/launchResponse/code") + ":" + respMap.get("/launchResponse/description"); setErrorMessage(retProp, "Error on Launch:" + eMsg); return retProp; } if (launchUrl != null) retProp.setProperty("launchurl", launchUrl); if (launchWidget != null) retProp.setProperty("launchwidget", launchWidget); String postResp = respMap.get("/launchResponse/type"); if (postResp != null) retProp.setProperty("type", postResp); retProp.setProperty("status", "success"); return retProp; }
From source file:MainClass.java
private byte[] loadClassData(String name) throws ClassNotFoundException { byte[] buffer; InputStream theClassInputStream = null; int bufferLength = 128; try {/*from ww w . j av a 2s. c o m*/ URL classURL = new URL(url, name + ".class"); URLConnection uc = classURL.openConnection(); uc.setAllowUserInteraction(false); try { theClassInputStream = uc.getInputStream(); } catch (NullPointerException e) { System.err.println(e); throw new ClassNotFoundException(name + " input stream problem"); } int contentLength = uc.getContentLength(); // A lot of web servers don't send content-lengths // for .class files if (contentLength == -1) { buffer = new byte[bufferLength * 16]; } else { buffer = new byte[contentLength]; } int bytesRead = 0; int offset = 0; while (bytesRead >= 0) { bytesRead = theClassInputStream.read(buffer, offset, bufferLength); if (bytesRead == -1) break; offset += bytesRead; if (contentLength == -1 && offset == buffer.length) { // grow the array byte temp[] = new byte[offset * 2]; System.arraycopy(buffer, 0, temp, 0, offset); buffer = temp; } else if (offset > buffer.length) { throw new ClassNotFoundException(name + " error reading data into the array"); } } if (offset < buffer.length) { // shrink the array byte temp[] = new byte[offset]; System.arraycopy(buffer, 0, temp, 0, offset); buffer = temp; } // Make sure all the bytes were received if (contentLength != -1 && offset != contentLength) { throw new ClassNotFoundException("Only " + offset + " bytes received for " + name + "\n Expected " + contentLength + " bytes"); } } catch (Exception e) { throw new ClassNotFoundException(name + " " + e); } finally { try { if (theClassInputStream != null) theClassInputStream.close(); } catch (IOException e) { } } return buffer; }
From source file:util.connection.AnonymousClient.java
public String download(URL source) throws IOException { // set the request URL URL request = new URL(source, source.getFile(), handler); // send request and receive response log.info("download (start) from source=" + source); URLConnection connection = request.openConnection(); connection.setDoOutput(true);/*from ww w. ja v a 2 s.c om*/ connection.setDoInput(true); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.connect(); String responsebody = IOUtils.toString(connection.getInputStream(), "UTF-8"); // read the response netLayer.clear(); netLayer.waitUntilReady(); return responsebody; }
From source file:com.wavemaker.runtime.ws.SyndFeedService.java
/** * Reads from the InputStream of the specified URL and builds the feed object from the returned XML. * /*from w ww . j a v a 2s. c o m*/ * @param feedURL The URL to read feed from. * @param httpBasicAuthUsername The username for HTTP Basic Authentication. * @param httpBasicAuthPassword The password for HTTP Basic Authentication. * @param connectionTimeout HTTP connection timeout. * @return A feed object. */ @ExposeToClient public Feed getFeedWithHttpConfig(String feedURL, String httpBasicAuthUsername, String httpBasicAuthPassword, int connectionTimeout) { URL url = null; try { url = new URL(feedURL); } catch (MalformedURLException e) { throw new WebServiceInvocationException(e); } SyndFeedInput input = new SyndFeedInput(); try { URLConnection urlConn = url.openConnection(); if (urlConn instanceof HttpURLConnection) { urlConn.setAllowUserInteraction(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(true); urlConn.setUseCaches(false); urlConn.setRequestProperty(USER_AGENT_KEY, USER_AGENT_VALUE); urlConn.setConnectTimeout(connectionTimeout); if (httpBasicAuthUsername != null && httpBasicAuthUsername.length() > 0) { String auth = httpBasicAuthPassword == null ? httpBasicAuthUsername : httpBasicAuthUsername + ":" + httpBasicAuthPassword; urlConn.setRequestProperty(BASIC_AUTH_KEY, BASIC_AUTH_VALUE_PREFIX + Base64.encodeBase64URLSafeString(auth.getBytes())); } } SyndFeed feed = input.build(new XmlReader(urlConn)); return FeedBuilder.getFeed(feed); } catch (IllegalArgumentException e) { throw new WebServiceInvocationException(e); } catch (FeedException e) { throw new WebServiceInvocationException(e); } catch (IOException e) { throw new WebServiceInvocationException(e); } }
From source file:org.pentaho.reporting.libraries.resourceloader.loader.URLResourceData.java
private void readMetaData() throws IOException { if (metaDataOK) { if ((System.currentTimeMillis() - lastDateMetaDataRead) < URLResourceData.getFixedCacheDelay()) { return; }/*ww w .j a v a 2 s . c o m*/ if (isFixBrokenWebServiceDateHeader()) { return; } } final URLConnection c = url.openConnection(); c.setDoOutput(false); c.setAllowUserInteraction(false); if (c instanceof HttpURLConnection) { final HttpURLConnection httpURLConnection = (HttpURLConnection) c; httpURLConnection.setRequestMethod("HEAD"); } c.connect(); readMetaData(c); c.getInputStream().close(); }
From source file:org.pentaho.reporting.libraries.resourceloader.loader.URLResourceData.java
public InputStream getResourceAsStream(final ResourceManager caller) throws ResourceLoadingException { try {// w w w. ja v a 2 s .com final URLConnection c = url.openConnection(); c.setDoOutput(false); c.setAllowUserInteraction(false); c.connect(); if (isFixBrokenWebServiceDateHeader() == false) { readMetaData(c); } return c.getInputStream(); } catch (IOException e) { throw new ResourceLoadingException("Failed to open URL connection", e); } }
From source file:WebCrawler.java
public void run() { String strURL = "http://www.google.com"; String strTargetType = "text/html"; int numberSearched = 0; int numberFound = 0; if (strURL.length() == 0) { System.out.println("ERROR: must enter a starting URL"); return;/*from w w w. ja va 2s . co m*/ } vectorToSearch = new Vector(); vectorSearched = new Vector(); vectorMatches = new Vector(); vectorToSearch.addElement(strURL); while ((vectorToSearch.size() > 0) && (Thread.currentThread() == searchThread)) { strURL = (String) vectorToSearch.elementAt(0); System.out.println("searching " + strURL); URL url = null; try { url = new URL(strURL); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } vectorToSearch.removeElementAt(0); vectorSearched.addElement(strURL); try { URLConnection urlConnection = url.openConnection(); urlConnection.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); String type = urlConnection.guessContentTypeFromStream(urlStream); if (type == null) break; if (type.compareTo("text/html") != 0) break; byte b[] = new byte[5000]; int numRead = urlStream.read(b); String content = new String(b, 0, numRead); while (numRead != -1) { if (Thread.currentThread() != searchThread) break; numRead = urlStream.read(b); if (numRead != -1) { String newContent = new String(b, 0, numRead); content += newContent; } } urlStream.close(); if (Thread.currentThread() != searchThread) break; String lowerCaseContent = content.toLowerCase(); int index = 0; while ((index = lowerCaseContent.indexOf("<a", index)) != -1) { if ((index = lowerCaseContent.indexOf("href", index)) == -1) break; if ((index = lowerCaseContent.indexOf("=", index)) == -1) break; if (Thread.currentThread() != searchThread) break; index++; String remaining = content.substring(index); StringTokenizer st = new StringTokenizer(remaining, "\t\n\r\">#"); String strLink = st.nextToken(); URL urlLink; try { urlLink = new URL(url, strLink); strLink = urlLink.toString(); } catch (MalformedURLException e) { System.out.println("ERROR: bad URL " + strLink); continue; } if (urlLink.getProtocol().compareTo("http") != 0) break; if (Thread.currentThread() != searchThread) break; try { URLConnection urlLinkConnection = urlLink.openConnection(); urlLinkConnection.setAllowUserInteraction(false); InputStream linkStream = urlLink.openStream(); String strType = urlLinkConnection .guessContentTypeFromStream(linkStream); linkStream.close(); if (strType == null) break; if (strType.compareTo("text/html") == 0) { if ((!vectorSearched.contains(strLink)) && (!vectorToSearch.contains(strLink))) { vectorToSearch.addElement(strLink); } } if (strType.compareTo(strTargetType) == 0) { if (vectorMatches.contains(strLink) == false) { System.out.println(strLink); vectorMatches.addElement(strLink); numberFound++; if (numberFound >= SEARCH_LIMIT) break; } } } catch (IOException e) { System.out.println("ERROR: couldn't open URL " + strLink); continue; } } } catch (IOException e) { System.out.println("ERROR: couldn't open URL " + strURL); break; } numberSearched++; if (numberSearched >= SEARCH_LIMIT) break; } if (numberSearched >= SEARCH_LIMIT || numberFound >= SEARCH_LIMIT) System.out.println("reached search limit of " + SEARCH_LIMIT); else System.out.println("done"); searchThread = null; }