List of usage examples for java.net URLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:net.daboross.bukkitdev.skywars.SkyWarsPlugin.java
@Override public InputStream getResourceAsStream(final String filename) throws IOException { // copied from JavaPlugin.java, and modified to actually give useful errors. Validate.notNull(filename, "Filename cannot be null"); URL url = getClassLoader().getResource(filename); if (url == null) { throw new FileNotFoundException("No resource '" + filename + "' found."); }//w w w. j av a2 s .com URLConnection connection = url.openConnection(); connection.setUseCaches(false); return connection.getInputStream(); }
From source file:org.infoglue.common.util.RemoteCacheUpdater.java
/** * This method post information to an URL and returns a string.It throws * an exception if anything goes wrong.//from ww w .j ava 2s . c om * (Works like most 'doPost' methods) * * @param urlAddress The address of the URL you would like to post to. * @param inHash The parameters you would like to post to the URL. * @return The result of the postToUrl method as a string. * @exception java.lang.Exception */ private String postToUrl(String urlAddress, Hashtable inHash) throws Exception { URL url = new URL(urlAddress); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(3000); urlConn.setReadTimeout(3000); urlConn.setAllowUserInteraction(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintWriter printout = new PrintWriter(urlConn.getOutputStream(), true); String argString = ""; if (inHash != null) { argString = toEncodedString(inHash); } printout.print(argString); printout.flush(); printout.close(); InputStream inStream = null; inStream = urlConn.getInputStream(); InputStreamReader inStreamReader = new InputStreamReader(inStream); BufferedReader buffer = new BufferedReader(inStreamReader); StringBuffer strbuf = new StringBuffer(); String line; while ((line = buffer.readLine()) != null) { strbuf.append(line); } String readData = strbuf.toString(); buffer.close(); return readData; }
From source file:org.safecreative.api.SafeCreativeAPI.java
public String call(String params) { String uri = baseUrl + API_ENDPOINT; OutputStream os = null;/*ww w . j av a 2s . c o m*/ String response = null; try { log.debug(String.format("api request: \n%s?%s\n", uri, params)); URL url = new URL(uri); URLConnection conn = url.openConnection(); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=" + DEFAULT_ENCODING); conn.setDoOutput(true); conn.setUseCaches(false); os = conn.getOutputStream(); os.write(params.getBytes(DEFAULT_ENCODING)); response = readString(conn.getInputStream()); log.debug(String.format("api response:\n %s\n", response)); if (isError(response) && INVALID_TIME_ERROR.equals(getErrorCode(response))) { log.warn("Client time needs resyncing"); timeOffset = null; } return response; } catch (Throwable e) { throw new RuntimeException(ApiException.wrap(e, uri + "?" + params, response)); } finally { IOHelper.closeQuietly(os); } }
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
private Boolean httpDownload(String downloadUrl, String dateiname) { URL url;// w w w . ja v a 2 s . c o m URLConnection conn; String fileName; Message msg; try { url = new URL(downloadUrl); conn = url.openConnection(); conn.setUseCaches(false); int fileSize = conn.getContentLength(); fileName = KleFuEntry.DOWNLOAD_LOCAL_DIRECTORY; File file = new File(fileName); file.mkdirs(); fileName = fileName + dateiname; // notify download start int fileSizeInKB = (int) (fileSize / 1024); msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_DOWNLOAD_STARTED, fileSizeInKB, 0, fileName); activityHandler.sendMessage(msg); BufferedInputStream inStream = new BufferedInputStream(conn.getInputStream()); File outFile = new File(fileName); FileOutputStream fileStream = new FileOutputStream(outFile); BufferedOutputStream outStream = new BufferedOutputStream(fileStream, KleFuEntry.DOWNLOAD_BUFFER_SIZE); byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE]; int bytesRead = 0, totalRead = 0; while (!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0) { outStream.write(data, 0, bytesRead); // update progress bar totalRead += bytesRead; int totalReadInKB = totalRead / 1024; msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0); activityHandler.sendMessage(msg); } outStream.close(); fileStream.close(); inStream.close(); if (isInterrupted()) { // the download was canceled, so let's delete the partially downloaded file outFile.delete(); return false; } else { return true; } } catch (Exception e) { String errMsg = parentActivity.getString(R.string.error_message_general); msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR, 0, 0, errMsg); activityHandler.sendMessage(msg); return false; } }
From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java
/** * This method sends a request to publisher logout api to invalidate the given sessionID * * @param sessionId String of valid session ID *//*from w ww . j av a 2 s . c o m*/ private void logOut(String sessionId) throws IOException { URLConnection urlConn = null; String logoutEndpoint = getBaseUrl() + PUBLISHER_APIS_LOGOUT_ENDPOINT; //construct APIs session invalidate endpoint try { URL endpointUrl = new URL(logoutEndpoint); urlConn = endpointUrl.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); if (LOG.isDebugEnabled()) { LOG.debug("Invalidating session: " + sessionId); } urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";"); //send SessionId Cookie //send POST output. urlConn.getOutputStream().flush(); } catch (MalformedURLException e) { LOG.error(getLogoutErrorMassage(logoutEndpoint), e); throw e; } catch (IOException e) { LOG.error(getLogoutErrorMassage(logoutEndpoint), e); throw e; } finally { if (urlConn != null) { try { urlConn.getOutputStream().close();//will close the connection as well } catch (IOException e) { LOG.error("Failed to close OutPutStream", e); } } } }
From source file:com.github.thebigs.foscam.recorder.Recorder.java
@Override public void run() { new File(outputDir).mkdirs(); initTotalBytesSaved();//from w w w. j av a2 s .c o m while (!shutdown) { try { URL url = new URL(camUrl); // Open a Connection to the server URLConnection urlc = url.openConnection(); if (urlc == null) { throw new IOException("Unable to make a connection to the image source"); } // Turn off caches to force fresh reload of the jpg urlc.setUseCaches(false); urlc.connect(); // ignored if already connected. InputStream stream = urlc.getInputStream(); // Line 1: "--ipcamera" String delimiter = new String(readLine(stream)); while (!shutdown && !imageListeners.isEmpty()) { // Line 2: "Content-Type: image/jpeg" String contentType = new String(readLine(stream)).split(":")[1].trim(); // Line 3: "Content-Length: 23304" int contentLength = Integer.parseInt(new String(readLine(stream)).split(":")[1].trim()); // Line 4: <Blank Line> readLine(stream); // read image data byte[] imageData = new byte[contentLength]; for (int i = 0; i < contentLength; i++) { int readByte = stream.read(); imageData[i] = (byte) readByte; } Image image = Toolkit.getDefaultToolkit().createImage(imageData); // save the image to the current recording saveImage(image); // notify listeners synchronized (imageListeners) { for (WebCamImageListener l : imageListeners) { l.onImage(image); } } // read stream till next delimiter boolean delimiterFound = false; ByteArrayOutputStream delimiterBuffer = new ByteArrayOutputStream(); while (!delimiterFound) { int nextByte = stream.read(); if (nextByte == 0x2d) { int followingByte = stream.read(); if (followingByte == 0x2d) { // read 8 bytes into the delimiter buffer for (int i = 0; i < 8; i++) { delimiterBuffer.write(stream.read()); } if (new String(delimiterBuffer.toByteArray()).equals("ipcamera")) { delimiterFound = true; // skip CR/LF stream.skip(2); } } } } } } catch (MalformedURLException e) { System.err.println("Unable to parse URL: '" + camUrl + "'"); System.exit(-1); } catch (IOException e) { System.err .println("IO Exception: server not responding at : '" + camUrl + "'. retrying in 1 second"); // sleep for 1 sec try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } if (imageListeners.isEmpty()) { // sleep for 5 secs try { Thread.sleep(5000); } catch (InterruptedException e) { } } } }
From source file:org.infoglue.igide.helper.http.HTTPTextDocumentListenerEngine.java
private void listen() { String errorMessage;/*www .j a va 2 s .co m*/ boolean error; errorMessage = ""; error = false; try { Logger.logConsole("Starting listen thread"); URLConnection urlConn = url.openConnection(); urlConn.setConnectTimeout(3000); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setReadTimeout(0); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(false); if (urlConn.getHeaderFields().toString().indexOf("401 Unauthorized") > -1) { Logger.logConsole("User has no access to the CMS - closing connection"); throw new AccessControlException("User has no access to the CMS - closing connection"); } String boundary = urlConn.getHeaderField("boundary"); DataInputStream input = new DataInputStream(urlConn.getInputStream()); StringBuffer buf = new StringBuffer(); if (listener != null) listener.onConnection(url); String str = null; while ((str = input.readLine()) != null) { if (str.indexOf("XMLNotificationWriter.ping") == -1) { if (str.equals(boundary)) { String message = buf.toString(); // By checking there is more in the String than the XML declaration we assume the message is valid if (message != null && !message.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").equals("")) { if (listener != null) listener.recieveDocument(buf.toString()); else Logger.logConsole((new StringBuilder("NEW DOCUMENT!!\r\n")).append(buf.toString()) .append("\r\n").toString()); } buf = new StringBuffer(); } else { buf.append(str); } } } input.close(); } catch (MalformedURLException me) { error = true; errorMessage = (new StringBuilder("Faulty CMS-url:")).append(url).toString(); if (listener != null) listener.onException(me); else System.err.println((new StringBuilder("MalformedURLException: ")).append(me).toString()); final String errorMessageFinal = errorMessage; Logger.logConsole( (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString()); if (!error) { if (System.currentTimeMillis() - lastRetry > 20000L) { Logger.logConsole("Trying to restart the listener as it was a while since last..."); lastRetry = System.currentTimeMillis(); listen(); } } else { try { if (listener != null) listener.onEndConnection(url); } catch (Exception e) { Logger.logConsole( (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString()); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(viewer.getControl().getShell(), "Error", (new StringBuilder()).append(errorMessageFinal).toString()); } }); } } catch (IOException ioe) { error = true; errorMessage = "Got an I/O-Exception talking to the CMS. Check that it is started and in valid state."; Logger.logConsole((new StringBuilder("ioe: ")).append(ioe.getMessage()).toString()); if (listener != null) listener.onException(ioe); else Logger.logConsole((new StringBuilder("TextDocumentListener cannot connect to: ")) .append(url.toExternalForm()).toString()); final String errorMessageFinal = errorMessage; Logger.logConsole( (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString()); if (!error) { if (System.currentTimeMillis() - lastRetry > 20000L) { Logger.logConsole("Trying to restart the listener as it was a while since last..."); lastRetry = System.currentTimeMillis(); listen(); } } else { try { if (listener != null) listener.onEndConnection(url); } catch (Exception e) { Logger.logConsole( (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString()); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(viewer.getControl().getShell(), "Error", (new StringBuilder()).append(errorMessageFinal).toString()); } }); } } catch (AccessControlException ace) { error = true; errorMessage = "The user you tried to connect with did not have the correct access rights. Check that he/she has roles etc enough to access the CMS"; Logger.logConsole((new StringBuilder("ioe: ")).append(ace.getMessage()).toString()); if (listener != null) listener.onException(ace); else Logger.logConsole((new StringBuilder()).append(ace.getMessage()).toString()); final String errorMessageFinal = errorMessage; Logger.logConsole( (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString()); if (!error) { if (System.currentTimeMillis() - lastRetry > 20000L) { Logger.logConsole("Trying to restart the listener as it was a while since last..."); lastRetry = System.currentTimeMillis(); listen(); } } else { try { if (listener != null) listener.onEndConnection(url); } catch (Exception e) { Logger.logConsole( (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString()); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(viewer.getControl().getShell(), "Error", (new StringBuilder()).append(errorMessageFinal).toString()); } }); } } catch (Exception exception) { final String errorMessageFinal = errorMessage; Logger.logConsole( (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString()); if (!error) { if (System.currentTimeMillis() - lastRetry > 20000L) { Logger.logConsole("Trying to restart the listener as it was a while since last..."); lastRetry = System.currentTimeMillis(); listen(); } } else { try { if (listener != null) listener.onEndConnection(url); } catch (Exception e) { Logger.logConsole( (new StringBuilder("Error ending connection:")).append(e.getMessage()).toString()); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(viewer.getControl().getShell(), "Error", (new StringBuilder()).append(errorMessageFinal).toString()); } }); } } catch (Throwable e) { final String errorMessageFinal = errorMessage; Logger.logConsole( (new StringBuilder("The connection was shut. Was it an error:")).append(error).toString()); if (!error) { if (System.currentTimeMillis() - lastRetry > 20000L) { Logger.logConsole("Trying to restart the listener as it was a while since last..."); lastRetry = System.currentTimeMillis(); listen(); } } else { try { if (listener != null) listener.onEndConnection(url); } catch (Exception e2) { Logger.logConsole( (new StringBuilder("Error ending connection:")).append(e2.getMessage()).toString()); } Display.getDefault().asyncExec(new Runnable() { public void run() { MessageDialog.openError(viewer.getControl().getShell(), "Error", (new StringBuilder()).append(errorMessageFinal).toString()); } }); } } }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
/** * Implement a simple proxy//from w w w . j a va2s .c o m * * @param requestedURL the requested URL * @param req the HttpServletRequest * @return */ @GET @Path("proxy") public Response proxy(@QueryParam(SemlibConstants.URL_PARAM) String requestedURL, @Context HttpServletRequest req) { BufferedReader in = null; try { URL url = new URL(requestedURL); URLConnection urlConnection = url.openConnection(); int proxyConnectionTimeout = ConfigManager.getInstance().getProxyAPITimeout(); // Set base properties urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(proxyConnectionTimeout * 1000); // set max response timeout 15 sec String acceptedDataFormat = req.getHeader(SemlibConstants.HTTP_HEADER_ACCEPT); if (StringUtils.isNotBlank(acceptedDataFormat)) { urlConnection.addRequestProperty(SemlibConstants.HTTP_HEADER_ACCEPT, acceptedDataFormat); } // Open the connection urlConnection.connect(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; int statusCode = httpConnection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM) { // Follow the redirect String newLocation = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_LOCATION); httpConnection.disconnect(); if (StringUtils.isNotBlank(newLocation)) { return this.proxy(newLocation, req); } else { return Response.status(statusCode).build(); } } else if (statusCode == HttpURLConnection.HTTP_OK) { // Send the response StringBuilder sbf = new StringBuilder(); // Check if the contentType is supported boolean contentTypeSupported = false; String contentType = httpConnection.getHeaderField(SemlibConstants.HTTP_HEADER_CONTENT_TYPE); List<String> supportedMimeTypes = ConfigManager.getInstance().getProxySupportedMimeTypes(); if (contentType != null) { for (String cMime : supportedMimeTypes) { if (contentType.equals(cMime) || contentType.contains(cMime)) { contentTypeSupported = true; break; } } } if (!contentTypeSupported) { httpConnection.disconnect(); return Response.status(Status.NOT_ACCEPTABLE).build(); } String contentEncoding = httpConnection.getContentEncoding(); if (StringUtils.isBlank(contentEncoding)) { contentEncoding = "UTF-8"; } InputStreamReader inStrem = new InputStreamReader((InputStream) httpConnection.getContent(), Charset.forName(contentEncoding)); in = new BufferedReader(inStrem); String inputLine; while ((inputLine = in.readLine()) != null) { sbf.append(inputLine); sbf.append("\r\n"); } in.close(); httpConnection.disconnect(); return Response.status(statusCode).header(SemlibConstants.HTTP_HEADER_CONTENT_TYPE, contentType) .entity(sbf.toString()).build(); } else { httpConnection.disconnect(); return Response.status(statusCode).build(); } } return Response.status(Status.BAD_REQUEST).build(); } catch (MalformedURLException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.BAD_REQUEST).build(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } } } }
From source file:org.apache.camel.impl.DefaultPackageScanClassResolver.java
protected void find(PackageScanFilter test, String packageName, ClassLoader loader, Set<Class<?>> classes) { if (log.isTraceEnabled()) { log.trace("Searching for: " + test + " in package: " + packageName + " using classloader: " + loader.getClass().getName()); }// ww w . ja v a2 s . co m Enumeration<URL> urls; try { urls = getResources(loader, packageName); if (!urls.hasMoreElements()) { log.trace("No URLs returned by classloader"); } } catch (IOException ioe) { log.warn("Cannot read package: " + packageName, ioe); return; } while (urls.hasMoreElements()) { URL url = null; try { url = urls.nextElement(); if (log.isTraceEnabled()) { log.trace("URL from classloader: " + url); } url = customResourceLocator(url); String urlPath = url.getFile(); urlPath = URLDecoder.decode(urlPath, "UTF-8"); if (log.isTraceEnabled()) { log.trace("Decoded urlPath: " + urlPath + " with protocol: " + url.getProtocol()); } // If it's a file in a directory, trim the stupid file: spec if (urlPath.startsWith("file:")) { // file path can be temporary folder which uses characters that the URLDecoder decodes wrong // for example + being decoded to something else (+ can be used in temp folders on Mac OS) // to remedy this then create new path without using the URLDecoder try { urlPath = new URI(url.getFile()).getPath(); } catch (URISyntaxException e) { // fallback to use as it was given from the URLDecoder // this allows us to work on Windows if users have spaces in paths } if (urlPath.startsWith("file:")) { urlPath = urlPath.substring(5); } } // osgi bundles should be skipped if (url.toString().startsWith("bundle:") || urlPath.startsWith("bundle:")) { log.trace("It's a virtual osgi bundle, skipping"); continue; } // Else it's in a JAR, grab the path to the jar if (urlPath.indexOf('!') > 0) { urlPath = urlPath.substring(0, urlPath.indexOf('!')); } if (log.isTraceEnabled()) { log.trace("Scanning for classes in [" + urlPath + "] matching criteria: " + test); } File file = new File(urlPath); if (file.isDirectory()) { if (log.isTraceEnabled()) { log.trace("Loading from directory using file: " + file); } loadImplementationsInDirectory(test, packageName, file, classes); } else { InputStream stream; if (urlPath.startsWith("http:") || urlPath.startsWith("https:") || urlPath.startsWith("sonicfs:") || isAcceptableScheme(urlPath)) { // load resources using http/https, sonicfs and other acceptable scheme // sonic ESB requires to be loaded using a regular URLConnection if (log.isTraceEnabled()) { log.trace("Loading from jar using url: " + urlPath); } URL urlStream = new URL(urlPath); URLConnection con = urlStream.openConnection(); // disable cache mainly to avoid jar file locking on Windows con.setUseCaches(false); stream = con.getInputStream(); } else { if (log.isTraceEnabled()) { log.trace("Loading from jar using file: " + file); } stream = new FileInputStream(file); } loadImplementationsInJar(test, packageName, stream, urlPath, classes); } } catch (IOException e) { // use debug logging to avoid being to noisy in logs log.debug("Cannot read entries in url: " + url, e); } } }
From source file:com.otisbean.keyring.Ring.java
/** * Export data to the specified file.//from w ww . j a v a 2s . c om * * @param outFile Path to the output file * @throws IOException * @throws GeneralSecurityException */ public void save(String outFile) throws IOException, GeneralSecurityException { log("save(" + outFile + ")"); if (outFile.startsWith("http")) { URL url = new URL(outFile); URLConnection urlConn = url.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream()); String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8"); dos.writeBytes(message); dos.flush(); dos.close(); // the server responds by saying // "OK" or "ERROR: blah blah" BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String s = br.readLine(); if (!s.equals("OK")) { StringBuilder sb = new StringBuilder(); sb.append("Failed to save to URL '"); sb.append(url); sb.append("': "); while ((s = br.readLine()) != null) { sb.append(s); } throw new IOException(sb.toString()); } br.close(); } else { Writer writer = getWriter(outFile); getExportData().writeJSONString(writer); closeWriter(writer, outFile); } }