List of usage examples for java.net URLConnection getContentLength
public int getContentLength()
From source file:com.adito.extensions.actions.DefaultExtensionsAction.java
/** * Update selected extension/*from w w w. jav a2s . c o m*/ * * @param mapping mapping * @param form form * @param request request * @param response response * @return forward * @throws Exception on any error */ public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); String version = request.getParameter("version"); PolicyUtil.checkPermission(PolicyConstants.EXTENSIONS_RESOURCE_TYPE, PolicyConstants.PERM_CHANGE, getSessionInfo(request).getUser()); URLConnection con = ExtensionStore.getInstance().downloadExtension(id, version); try { InputStream in = con.getInputStream(); ExtensionBundle bundle = ExtensionStore.getInstance().updateExtension(id, in, request, con.getContentLength()); if (bundle.isContainsPlugin()) GlobalWarningManager.getInstance() .addMultipleGlobalWarning(new GlobalWarning(GlobalWarning.MANAGEMENT_USERS, new BundleActionMessage("extensions", "extensionStore.message.extensionUpdatedRestartRequired"), DismissType.DISMISS_FOR_USER)); ActionMessages msgs = new ActionMessages(); msgs.add(Globals.MESSAGE_KEY, new ActionMessage("extensionStore.message.applicationUpdated", bundle.getName())); saveMessages(request, msgs); } catch (CoreException ce) { ActionMessages errs = new ActionMessages(); errs.add(Globals.ERROR_KEY, ce.getBundleActionMessage()); saveErrors(request, errs); } return new RedirectWithMessages(mapping.findForward("refresh"), request); }
From source file:com.adito.extensions.actions.DefaultExtensionsAction.java
/** * Install selected extension/*from w w w. j av a 2 s .co m*/ * * @param mapping mapping * @param form form * @param request request * @param response response * @return forward * @throws Exception on any error */ public ActionForward install(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String id = request.getParameter("id"); String version = request.getParameter("version"); PolicyUtil.checkPermission(PolicyConstants.EXTENSIONS_RESOURCE_TYPE, PolicyConstants.PERM_CHANGE, getSessionInfo(request).getUser()); ActionForward fwd = new RedirectWithMessages(mapping.findForward("refresh"), request); URLConnection con = ExtensionStore.getInstance().downloadExtension(id, version); try { InputStream in = con.getInputStream(); ExtensionBundle bundle = ExtensionStore.getInstance().installExtensionFromStore(id, in, request, con.getContentLength()); ExtensionStore.getInstance().licenseCheck(bundle, request, fwd); ExtensionStore.getInstance().postInstallExtension(bundle, request); ActionMessages msgs = new ActionMessages(); msgs.add(Globals.MESSAGE_KEY, new ActionMessage("extensionStore.message.applicationInstalled", bundle.getName())); saveMessages(request, msgs); } catch (CoreException ce) { ActionMessages errs = new ActionMessages(); errs.add(Globals.ERROR_KEY, ce.getBundleActionMessage()); saveErrors(request, errs); } return new RedirectWithMessages(mapping.findForward("refresh"), request); }
From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java
private Boolean httpDownload(String downloadUrl, String dateiname) { URL url;/*from www . ja v a 2s . c om*/ 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:colectordedatos.iniciocolector.java
public void cargartransacciones() { String strUrl = "http://10.43.11.143:8090/controller/rest/applications/Portales/business-transactions?output=JSON"; try {//from w w w .j a v a 2 s .c o m URL url = new URL(strUrl); URLConnection urlCon = url.openConnection(); InputStream is = urlCon.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader bf = new BufferedReader(isr); String linea = bf.readLine(); StringBuffer sb = new StringBuffer(); int size = urlCon.getContentLength(); while (linea != null) { sb.append(linea.trim()); linea = bf.readLine(); } JSONArray transacciones = new JSONArray(sb.toString()); Object[] idname = new Object[transacciones.length()]; for (int i = 0; i < transacciones.length(); i++) { JSONObject obj = transacciones.getJSONObject(i); idname idname1 = new idname(obj.getString("id"), obj.getString("name")); opciones.addItem(idname1); } } catch (MalformedURLException ex) { Logger.getLogger(iniciocolector.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(iniciocolector.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(resultados.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.keithandthegirl.services.download.DownloadService.java
private void savePodcast(Long id, String title, String urlPath, File output) { Log.v(TAG, "savePodcast : enter"); sendNotification("Downloading Episode: " + title); URL url;//w w w . j a va2 s.c o m URLConnection con; InputStream is; FileOutputStream fos; byte[] buffer = new byte[4096]; try { url = new URL(urlPath); con = url.openConnection(); is = con.getInputStream(); fos = new FileOutputStream(output); boolean notified = false; int length = con.getContentLength(); int total = 0, read = -1; while ((read = is.read(buffer)) != -1) { fos.write(buffer, 0, read); total += read; int percent = (int) FloatMath.ceil(((100 * (float) total) / (float) length)); //Log.v( TAG, "savePodcast : download percent=" + percent + "%" ); if (percent % 5 == 0 && !notified) { progressUpdate(percent); notified = true; } else { notified = false; } } is.close(); fos.close(); result = FragmentActivity.RESULT_OK; ContentValues values = new ContentValues(); values.put(EpisodeConstants.FIELD_FILE, output.getAbsolutePath()); getContentResolver().update(ContentUris.withAppendedId(EpisodeConstants.CONTENT_URI, id), values, null, null); } catch (Exception e) { Log.e(TAG, "savePodcast : error", e); } finally { completed(); } Log.v(TAG, "savePodcast : exit"); }
From source file:io.fabric8.apiman.rest.Kubernetes2ApimanFilter.java
/** * Checks of the descriptionDocument can be obtained from the service. If the * service is still deploying we will hold off and return false. * * @param bean/* ww w . ja va2 s .co m*/ * @return true of the desciptionDocument is ready to be read. */ private boolean isServiceReady(AvailableApiBean bean) { log.debug("DefinitionType: " + bean.getDefinitionType()); URL defUrl = null; if (bean.getDefinitionType() != null && !"None".equals(bean.getDefinitionType().name())) { try { defUrl = new URL(bean.getDefinitionUrl()); URLConnection urlConnection = defUrl.openConnection(); log.info("Trying to obtain descriptionDoc for service " + bean.getName()); urlConnection.setConnectTimeout(250); if (urlConnection.getContentLength() > 0) { log.debug("DefinitionDoc at 'Ready to be read " + urlConnection.getContent()); return true; } else { //try the route defUrl = new URL(bean.getRouteDefinitionUrl()); urlConnection = defUrl.openConnection(); log.info("Trying to obtain descriptionDoc for service " + bean.getName()); urlConnection.setConnectTimeout(250); if (urlConnection.getContentLength() > 0) { bean.setDefinitionUrl(defUrl.toExternalForm()); return true; } else { log.info("DefinitionDoc for '" + bean.getName() + "' not ready to be read from " + defUrl.toExternalForm()); } return false; } } catch (Exception e) { log.info("DefinitionDoc for '" + bean.getName() + "' can't be read. " + e.getMessage()); return false; } } return true; }
From source file:eu.faircode.netguard.DownloadTask.java
@Override protected Object doInBackground(Object... args) { Log.i(TAG, "Downloading " + url + " into " + file); InputStream in = null;/*from w w w . j a v a2 s . c om*/ OutputStream out = null; URLConnection connection = null; try { connection = url.openConnection(); connection.connect(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) throw new IOException( httpConnection.getResponseCode() + " " + httpConnection.getResponseMessage()); } int contentLength = connection.getContentLength(); Log.i(TAG, "Content length=" + contentLength); in = connection.getInputStream(); out = new FileOutputStream(file); long size = 0; byte buffer[] = new byte[4096]; int bytes; while (!isCancelled() && (bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); size += bytes; if (contentLength > 0) publishProgress((int) (size * 100 / contentLength)); } Log.i(TAG, "Downloaded size=" + size); return null; } catch (Throwable ex) { return ex; } finally { try { if (out != null) out.close(); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } try { if (in != null) in.close(); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect(); } }
From source file:net.ytbolg.mcxa.Updater.java
public void run() { try {/*from www . j av a 2 s.c o m*/ URLConnection u = (new URL(Updater.DownloadURL)).openConnection(); HttpURLConnection huc = (HttpURLConnection) u; InputStream bis = huc.getInputStream(); File f = new File(GameInfo.Rundir + tpf + "MCLaucherXA" + Updater.ver + ".jar"); if (!f.exists()) { f.createNewFile(); } FileOutputStream fos = new FileOutputStream(f); jpb.setMaximum(u.getContentLength()); jpb.setValue(0); int len = 2048; byte[] byt = new byte[len]; int i = 0; while ((len = bis.read(byt)) != -1) { i = i + len; jpb.setValue(i); l.setText(i / 1024 + "/" + (u.getContentLength() / 1024) + "KB"); fos.write(byt, 0, len); } fos.close(); bis.close(); JOptionPane.showMessageDialog(null, Lang.getLang("Up_Box_DownSucc") + "MCLaucherXA" + Updater.ver + ".jar"); b.setEnabled(true); File f2 = new File(GameInfo.Rundir + tpf + "update.note"); if (f2.exists()) { f2.delete(); } f2.createNewFile(); FileWriter fw = new FileWriter(f2); fw.write(System.getProperty("java.class.path")); fw.close(); String fgf = System.getProperty("os.name").equals("Windows") ? "\"" : "'"; Runtime.getRuntime().exec(fgf + GameInfo.JavaPath + fgf + " -jar " + GameInfo.Rundir + tpf + "MCLaucherXA" + Updater.ver + ".jar"); System.exit(0); // new File(System.getProperty("java.class.path")).deleteOnExit(); } catch (Exception ex) { JOptionPane.showMessageDialog(null, Lang.getLang("Up_DownFaild") + "\n" + ex, "", JOptionPane.ERROR_MESSAGE); b.setEnabled(true); } }
From source file:UrlServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet."); if (fileName.indexOf(".pdf") == -1) fileName = fileName + ".pdf"; URL pdfDir = null;// w w w . j av a 2s.c om URLConnection urlConn = null; ServletOutputStream stream = null; BufferedInputStream buf = null; try { pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName); } catch (MalformedURLException mue) { throw new ServletException(mue.getMessage()); } try { stream = response.getOutputStream(); //set response headers response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); urlConn = pdfDir.openConnection(); response.setContentLength((int) urlConn.getContentLength()); buf = new BufferedInputStream(urlConn.getInputStream()); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:org.jenkinsci.modules.optpluginhelper.PluginHelper.java
/** * List all the optional plugins (while populating the staging area with any new ones we discover). * * @return the list of optional plugins available from all the current defined {@link PluginSource} extensions. *//* w ww. j a v a 2s. c o m*/ private List<File> listPlugins() { // TODO figure out what to do if two sources provide different versions of the same plugin, currently undefined List<File> result = new ArrayList<File>(); final Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) { return result; } File baseDir = new File(jenkins.root, OPTIONAL_PLUGIN_DIR); if (baseDir.exists() && !baseDir.isDirectory()) { LOGGER.log(Level.SEVERE, "Optional plugin working directory {0} exists and is not a directory", baseDir); return result; } if (!baseDir.isDirectory()) { if (!baseDir.mkdirs()) { LOGGER.log(Level.SEVERE, "Could not create optional plugin working directory {0}", baseDir); return result; } } for (URL resource : PluginSource.allPlugins()) { try { final String externalForm = resource.toExternalForm(); ExtractedPluginMetadata metadata = extractedPluginMetadataMap.get(externalForm); if (metadata != null) { File archive = new File(baseDir, metadata.shortName + ".jpi"); if (archive.isFile() && archive.length() == metadata.length && Util.getDigestOf(archive).equals(metadata.digest)) { result.add(archive); continue; } } final URLConnection connection = resource.openConnection(); long lastModified = connection.getLastModified(); long size = connection.getContentLength(); String path = resource.getPath(); String fileName = FilenameUtils.getBaseName(path); boolean nameCheck = false; if (StringUtils.isBlank(fileName)) { nameCheck = true; fileName = Util.getDigestOf(resource.toString()); } File file = new File(baseDir, fileName + ".jpi"); if (file.isFile() && (file.lastModified() == lastModified || lastModified == 0) && file.length() == size) { final String fileDigest = Util.getDigestOf(file); final String resourceDigest; final InputStream stream = connection.getInputStream(); try { resourceDigest = Util.getDigestOf(stream); } finally { IOUtils.closeQuietly(stream); } if (fileDigest.equals(resourceDigest)) { result.add(file); extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file)); continue; } } FileUtils.copyURLToFile(resource, file); if (nameCheck) { final String shortName = jenkins.getPluginManager().getPluginStrategy().getShortName(file); if (!fileName.equals(shortName)) { File newFile = new File(baseDir, shortName + ".jpi"); if (!newFile.isFile() || !Util.getDigestOf(newFile).equals(Util.getDigestOf(file))) { FileUtils.moveFile(file, newFile); } file = newFile; } } if (lastModified != 0) { if (!file.setLastModified(lastModified)) { LOGGER.log(Level.FINE, "Couldn't set last modified on {0}", file); } } result.add(file); extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file)); } catch (IOException e) { LOGGER.log(Level.WARNING, String.format("Could not process optional plugin from %s", resource), e); } } LOGGER.log(Level.FINE, "List of plugins: " + result); return result; }