List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:fr.cls.atoll.motu.api.rest.MotuRequest.java
/** * Executes the request and returns the result as a stream. The stream contains: - the extracted netcdf * file if mode is 'console' - the url the extracted netcdf file if mode is 'url' url - the url of the XML * status file if mode is 'status' (this file contains the status of the request : INPROGRESS or * ERROR+error message or DONE)./*w w w . j ava 2 s . c om*/ * * This function must be used * * @return the result of the request as a stream * * @throws MotuRequestException the motu request exception */ public InputStream executeV2() throws MotuRequestException { if (LOG.isDebugEnabled()) { LOG.debug("executeV2() - entering"); } // First set the default cookie manager. // Must be set before the first http request. // This is essential for cookie session managment with CAS authentication cookieStore.removeAll(); CookieManager cm = new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL); CookieHandler.setDefault(cm); URL url = null; // Get the authentication mode parameter String authModeString = (String) motuRequestParameters .getParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE); AuthenticationMode authMode = null; if (!AssertionUtils.isNullOrEmpty(authModeString)) { authMode = AuthenticationMode.fromValue((String) motuRequestParameters .getParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE)); } // Authentication mode is not an extraction criteria, remove it now motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE); // Get login / password parameters, String login = (String) motuRequestParameters.getParameter(MotuRequestParametersConstant.PARAM_LOGIN); String password = (String) motuRequestParameters.getParameter(MotuRequestParametersConstant.PARAM_PWD); // Login/password are not extraction criteria, remove them now motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_LOGIN); motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_PWD); // String requestParams = null; String targetUrl = getRequestUrl(); // Check is authentication mode is set or not // if not set, guess the authentication mode boolean guessAuthentication = (authMode == null) && (!AssertionUtils.isNullOrEmpty(login)); if (guessAuthentication) { UserBase user = new UserBase(); if (!AssertionUtils.isNullOrEmpty(login)) { user.setLogin(login); if (AssertionUtils.isNullOrEmpty(password)) { password = ""; } user.setPwd(password); } try { RestUtil.checkAuthenticationMode(servletUrl, user); authMode = user.getAuthenticationMode(); } catch (MotuCasException e) { String msg = String.format("Unable to check authentication mode from url '%s'. Reason is:\n %s", servletUrl, e.notifyException()); throw new MotuRequestException(msg, e); } catch (IOException e) { String msg = String.format("Unable to check authentication mode from url '%s'. Reason is:\n %s", servletUrl, e.getMessage()); throw new MotuRequestException(msg, e); } } try { if (authMode == AuthenticationMode.CAS) { // Add CAS ticket to the query parameters // If url is CASified then a CAS ticket is added to the returned url. // If url is not CASified then the original url is returned. // If login or password is null or empty, then the original url is returned. targetUrl = AssertionUtils.addCASTicket(targetUrl, login, password, null); } url = new URL(targetUrl); } catch (MalformedURLException e) { LOG.error("executeV2()", e); throw new MotuRequestException("Invalid url", e); } catch (MotuCasBadRequestException e) { LOG.error("executeV2()", e); throw new MotuRequestException("Invalid url", e); } catch (IOException e) { LOG.error("executeV2()", e); throw new MotuRequestException("Invalid url", e); } LOG.info("URL=" + targetUrl); HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(connectTimeout); if ((authMode == AuthenticationMode.BASIC) && (!AssertionUtils.isNullOrEmpty(login)) && (!AssertionUtils.isNullOrEmpty(password))) { // Set basic authentication StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(login); stringBuffer.append(":"); stringBuffer.append(password); byte[] encoding = new org.apache.commons.codec.binary.Base64() .encode(stringBuffer.toString().getBytes()); urlConnection.setRequestProperty("Authorization", "Basic " + new String(encoding)); } } catch (IOException ex) { LOG.error("executeV2()", ex); throw new MotuRequestException("Request connection failed", ex); } try { InputStream returnInputStream = urlConnection.getInputStream(); if (LOG.isDebugEnabled()) { LOG.debug("executeV2() - exiting"); } return returnInputStream; } catch (IOException ex) { LOG.error("executeV2()", ex); MotuRequestException motuRequestException; try { motuRequestException = new MotuRequestException("Request failed - errorCode: " + urlConnection.getResponseCode() + ", errorMsg: " + urlConnection.getResponseMessage(), ex); } catch (IOException e) { LOG.error("executeV2()", e); motuRequestException = new MotuRequestException("Request connection failed", ex); } throw motuRequestException; } }
From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java
private static HeliosData loadHelios() throws IOException { System.out.println("Finding Helios implementation"); HeliosData data = new HeliosData(); boolean needsToDownload = !IMPL_FILE.exists(); if (!needsToDownload) { try (JarFile jarFile = new JarFile(IMPL_FILE)) { ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF"); if (entry == null) { needsToDownload = true;// w ww .java 2 s. co m } else { Manifest manifest = new Manifest(jarFile.getInputStream(entry)); String ver = manifest.getMainAttributes().getValue("Implementation-Version"); try { data.buildNumber = Integer.parseInt(ver); data.version = manifest.getMainAttributes().getValue("Version"); data.mainClass = manifest.getMainAttributes().getValue("Main-Class"); } catch (NumberFormatException e) { needsToDownload = true; } } } catch (IOException e) { needsToDownload = true; } } if (needsToDownload) { URL latestJar = new URL(LATEST_JAR); System.out.println("Downloading latest Helios implementation"); FileOutputStream out = new FileOutputStream(IMPL_FILE); HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection(); if (connection.getResponseCode() == 200) { int contentLength = connection.getContentLength(); if (contentLength > 0) { InputStream stream = connection.getInputStream(); byte[] buffer = new byte[1024]; int amnt; AtomicInteger total = new AtomicInteger(); AtomicBoolean stop = new AtomicBoolean(false); Thread progressBar = new Thread() { public void run() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); JLabel label = new JLabel(); label.setText("Downloading latest Helios build"); panel.add(label); GridLayout layout = new GridLayout(); layout.setColumns(1); layout.setRows(3); panel.setLayout(layout); JProgressBar pbar = new JProgressBar(); pbar.setMinimum(0); pbar.setMaximum(100); panel.add(pbar); JTextArea textArea = new JTextArea(1, 3); textArea.setOpaque(false); textArea.setEditable(false); textArea.setText("Downloaded 00.00MB/00.00MB"); panel.add(textArea); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); while (!stop.get()) { SwingUtilities.invokeLater( () -> pbar.setValue((int) (100.0 * total.get() / contentLength))); textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/" + bytesToMeg(contentLength) + "MB"); try { Thread.sleep(100); } catch (InterruptedException ignored) { } } frame.dispose(); } }; progressBar.start(); while ((amnt = stream.read(buffer)) != -1) { out.write(buffer, 0, amnt); total.addAndGet(amnt); } stop.set(true); return loadHelios(); } else { throw new IOException("Content-Length set to " + connection.getContentLength()); } } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date throw new RuntimeException("Bootstrapper out of date!"); } else { throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage()); } } return data; }
From source file:fyp.project.uploadFile.UploadFile.java
public int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;/*w w w .j a v a 2 s. com*/ DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName.substring(fileName.lastIndexOf("/")) + "\"" + lineEnd); m_log.log(Level.INFO, "Content-Disposition: form-data; name=\"file\";filename=\"{0}\"{1}", new Object[] { fileName.substring(fileName.lastIndexOf("/")), lineEnd }); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.log(Level.INFO, "Upload file to server" + "HTTP Response is : {0}: {1}", new Object[] { serverResponseMessage, serverResponseCode }); // close streams m_log.log(Level.INFO, "Upload file to server{0} File is written", fileName); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); m_log.log(Level.ALL, "Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { e.printStackTrace(); } //this block will give the response of upload link return serverResponseCode; // like 200 (Ok) }
From source file:imapi.OnlineDatabaseActions.java
int checkIfDBisAvailable() { ApiConstants.TargetSourceChoice targetChoice = this.currentDB.getDBChoice(); System.out.println("\n=======================================\n"); System.out.println("Checking if online database " + targetChoice.toString() + " is available."); String baseURL = ""; switch (targetChoice) { case BRITISH_MUSEUM_COLLECTION: case CLAROS: { try {// w w w . j a v a2s .co m baseURL = this.currentDB.getDbSparqlEndpoint(); String USER_AGENT = "Mozilla/5.0"; HttpURLConnection con = (HttpURLConnection) (new URL(baseURL)).openConnection(); // optional default is GET con.setRequestMethod("GET"); con.setRequestProperty("HTTP", "1.1"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); if (responseCode != 200) { System.out.println("Seems that online database: " + targetChoice.toString() + " at url: " + baseURL + " is unavailable."); System.out.println("Please try again later or change user configuration xml file to " + ApiConstants.TargetSourceChoice.FILE_COMPARISON.toString() + "."); System.out.println("Response Code: " + responseCode); System.out.println("ReasonPhrase returned." + con.getResponseMessage()); return ApiConstants.IMAPIFailCode; } if (IMAPIClass.DEBUG) { System.out.println("responce code = 200!"); } if (targetChoice == ApiConstants.TargetSourceChoice.CLAROS) { System.out.println("\n\nWARNING: " + targetChoice.toString() + " database does not support inference.\n" + "Classes and properties should be set to the exact properties used in the database.\n" + "i.e. If asking for E39_Actor this database will not also qualify the E21_Person instances \n" + " as it should since E21 is subClassOf E39.\n" + " and if asking for P1 predicate this database will not also qualify the P131 predicates \n" + " as it should since P131 is subPropertyOf P1.\n\n"); } /* HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(baseURL); post.setHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(post); int responseCode = response.getStatusLine().getStatusCode();//con.getResponseCode(); if (responseCode != 200) { System.out.println("Response Code: " + responseCode); System.out.println("ReasonPhrase returned." + response.getStatusLine().getReasonPhrase()); return ApiConstants.IMAPIFailCode; }*/ } catch (IOException ex) { System.out.println("Seems that online database: " + targetChoice.toString() + " at url: " + baseURL + " is unavailable."); Utilities.handleException(ex); //Logger.getLogger(IMAPIClass.class.getName()).log(Level.SEVERE, null, ex); return ApiConstants.IMAPIFailCode; } break; } default: { return ApiConstants.IMAPIFailCode; } } System.out.println("\n=======================================\n"); System.out.println("Online database " + targetChoice.toString() + " is available."); return ApiConstants.IMAPISuccessCode; }
From source file:com.google.ytd.SubmitActivity.java
private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException { int chunk = end - start + 1; int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; FileInputStream fileStream = new FileInputStream(file); HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem if (isFirstRequest()) { Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded)); urlConnection.setRequestMethod("POST"); } else {/*ww w. ja v a 2s . co m*/ urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.", (int) totalBytesUploaded)); } urlConnection.setDoOutput(true); urlConnection.setFixedLengthStreamingMode(chunk); urlConnection.setRequestProperty("Content-Type", "video/3gpp"); urlConnection.setRequestProperty("Content-Range", String.format("bytes %d-%d/%d", start, end, file.length())); Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range")); OutputStream outStreamWriter = urlConnection.getOutputStream(); fileStream.skip(start); int bytesRead; int totalRead = 0; while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) { outStreamWriter.write(buffer, 0, bytesRead); totalRead += bytesRead; this.totalBytesUploaded += bytesRead; double percent = (totalBytesUploaded / currentFileSize) * 99; /* Log.d(LOG_TAG, String.format( "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize, totalBytesUploaded, percent)); */ dialog.setProgress((int) percent); if (totalRead == (end - start + 1)) { break; } } outStreamWriter.close(); int responseCode = urlConnection.getResponseCode(); Log.d(LOG_TAG, "responseCode=" + responseCode); Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage()); try { if (responseCode == 201) { String videoId = parseVideoId(urlConnection.getInputStream()); String latLng = null; if (this.videoLocation != null) { latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(), this.videoLocation.getLongitude()); } submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName, SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken, latLng, this.tags); dialog.setProgress(100); return videoId; } else if (responseCode == 200) { Set<String> keySet = urlConnection.getHeaderFields().keySet(); String keys = urlConnection.getHeaderFields().keySet().toString(); Log.d(LOG_TAG, String.format("Headers keys %s.", keys)); for (String key : keySet) { Log.d(LOG_TAG, String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key))); } Log.w(LOG_TAG, "Received 200 response during resumable uploading"); throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { if ((responseCode + "").startsWith("5")) { String error = String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage()); Log.w(LOG_TAG, error); // TODO - this exception will trigger retry mechanism to kick in // TODO - even though it should not, consider introducing a new type so // TODO - resume does not kick in upon 5xx throw new IOException(error); } else if (responseCode == 308) { // OK, the chunk completed succesfully Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode, urlConnection.getResponseMessage())); } else { // TODO - this case is not handled properly yet Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode, urlConnection.getResponseMessage(), uploadUrl)); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; }
From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java
/** * @param fileName// w w w .j a v a 2 s . co m * @param urlStr * @param isSiteFile * @param propChgListener */ public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile, final PropertyChangeListener propChgListener) { final String prgName = HttpLargeFileTransfer.class.toString(); final File file = new File(fileName); if (file.exists()) { final long fileSize = file.length(); if (fileSize > 0) { SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() { protected String errorMsg = null; protected FileInputStream fis = null; protected OutputStream fos = null; protected int nChunks = 0; /* (non-Javadoc) * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Integer doInBackground() throws Exception { try { Thread.sleep(100); fis = new FileInputStream(file); nChunks = (int) (fileSize / MAX_CHUNK_SIZE); if (fileSize % MAX_CHUNK_SIZE > 0) { nChunks++; } byte[] buf = new byte[BUFFER_SIZE]; long bytesRemaining = fileSize; String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random())); URL url = new URL(urlStr); UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks); for (int i = 0; i < nChunks; i++) { firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i); if (i == nChunks - 1) { Thread.sleep(500); int x = 0; x++; } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE : bytesRemaining); bytesRemaining -= chunkSize; conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Content-Length", String.valueOf(chunkSize)); conn.setRequestProperty(CLIENT_ID_HEADER, clientID); conn.setRequestProperty(FILE_NAME_HEADER, fileName); conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks)); conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i)); conn.setRequestProperty(SERVICE_NUMBER, "10"); conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile)); fos = conn.getOutputStream(); //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE)); int cnt = 0; int bytesRead = 0; while (bytesRead < chunkSize) { int read = fis.read(buf); if (read == -1) { break; } else if (read > 0) { bytesRead += read; fos.write(buf, 0, read); } cnt++; //firePropertyChange(prgName, cnt-1, cnt); } fos.close(); if (conn.getResponseCode() != HttpServletResponse.SC_OK) { System.err.println( conn.getResponseMessage() + " " + conn.getResponseCode() + " "); BufferedReader in = new BufferedReader( new InputStreamReader(conn.getErrorStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = in.readLine()) != null) { sb.append(line); sb.append("\n"); } System.out.println(sb.toString()); in.close(); } else { System.err.println("OK"); } //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks); firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i); } } catch (IOException ex) { errorMsg = ex.toString(); } //firePropertyChange(prgName, 0, 100); return null; } @Override protected void done() { super.done(); UIRegistry.getStatusBar().setProgressDone(prgName); UIRegistry.clearSimpleGlassPaneMsg(); if (StringUtils.isNotEmpty(errorMsg)) { UIRegistry.showError(errorMsg); } if (propChgListener != null) { propChgListener.propertyChange( new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1)); } } }; final JStatusBar statusBar = UIRegistry.getStatusBar(); statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true); UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24); backupWorker.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(final PropertyChangeEvent evt) { System.out.println(evt.getPropertyName() + " " + evt.getNewValue()); if (prgName.equals(evt.getPropertyName())) { Integer value = (Integer) evt.getNewValue(); if (value == Integer.MAX_VALUE) { statusBar.setIndeterminate(prgName, true); UIRegistry.writeSimpleGlassPaneMsg( getLocalizedMessage("Transfering data into the database."), 24); } else { statusBar.setValue(prgName, value); } } } }); backupWorker.execute(); } else { // file doesn't exist } } else { // file doesn't exist } }
From source file:com.BeatYourRecord.SubmitActivity.java
private ResumeInfo resumeFileUpload(String uploadUrl) throws IOException, ParserConfigurationException, SAXException, Internal500ResumeException { HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl); urlConnection.setRequestProperty("Content-Range", "bytes */*"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT"); urlConnection.setFixedLengthStreamingMode(0); HttpURLConnection.setFollowRedirects(false); urlConnection.connect();/*w ww . j a v a 2 s . c o m*/ int responseCode = urlConnection.getResponseCode(); if (responseCode >= 300 && responseCode < 400) { int nextByteToUpload; String range = urlConnection.getHeaderField("Range"); if (range == null) { Log.d(LOG_TAG, String.format("PUT to %s did not return 'Range' header.", uploadUrl)); nextByteToUpload = 0; } else { Log.d(LOG_TAG, String.format("Range header is '%s'.", range)); String[] parts = range.split("-"); if (parts.length > 1) { nextByteToUpload = Integer.parseInt(parts[1]) + 1; } else { nextByteToUpload = 0; } } return new ResumeInfo(nextByteToUpload); } else if (responseCode >= 200 && responseCode < 300) { return new ResumeInfo(parseVideoId(urlConnection.getInputStream())); } else if (responseCode == 500) { // TODO this is a workaround for current problems with resuming uploads while switching transport (Wifi->EDGE) throw new Internal500ResumeException( String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } else { throw new IOException(String.format("Unexpected response for PUT to %s: %s " + "(code %d)", uploadUrl, urlConnection.getResponseMessage(), responseCode)); } }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ===================================================================================== initialize(request);//from ww w . j a va2 s.c om int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } Credential credential = null; Connection c = null; try { //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } /// uuid: celui de la ressource /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String origin = request.getRequestURL().toString(); /// Rcupration des paramtres String url = request.getPathInfo(); String[] token = url.split("/"); String uuid = token[1]; String size = request.getParameter("size"); if (size == null) size = "S"; String lang = request.getParameter("lang"); if (lang == null) { lang = "fr"; } /// Vrification des droits d'accs if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid); } String data; String fileid = ""; try { data = dataProvider.getResNode(uuid, userId, groupId); /// Parse les donnes DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader("<node>" + data + "</node>")); Document doc = documentBuilder.parse(is); DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0"); LSSerializer serial = impl.createLSSerializer(); serial.getDomConfig().setParameter("xml-declaration", false); /// Cherche si on a dj envoy quelque chose XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//filename[@lang=\"" + lang + "\"]"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); String filename = ""; if (nodelist.getLength() > 0) filename = nodelist.item(0).getTextContent(); if (!"".equals(filename)) { /// Already have one, per language String filterId = "//fileid[@lang='" + lang + "']"; NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET); if (idlist.getLength() != 0) { Element fileNode = (Element) idlist.item(0); fileid = fileNode.getTextContent(); } } } catch (Exception e2) { e2.printStackTrace(); } int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch if (last < 0) last = 0; fileid = fileid.substring(last); /// request.getHeader("REFERRER"); /// criture des donnes String urlTarget = "http://" + server + "/" + fileid; // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs"; // Unpack form, fetch binary data and send // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) /* ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); //*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); String json = ""; HttpURLConnection connection = null; // Parse the request try { List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if ("uploadfile".equals(item.getFieldName())) { // Send raw data InputStream inputData = item.getInputStream(); /* URL urlConn = new URL(urlTarget); connection = (HttpURLConnection) urlConn.openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); /// We don't want to cache data connection.setInstanceFollowRedirects(false); /// Let client follow any redirection String method = request.getMethod(); connection.setRequestMethod(method); String context = request.getContextPath(); connection.setRequestProperty("app", context); //*/ String fileName = item.getName(); long filesize = item.getSize(); String contentType = item.getContentType(); // /* connection = CreateConnection(urlTarget, request); connection.setRequestProperty("filename", uuid); connection.setRequestProperty("content-type", "application/octet-stream"); connection.setRequestProperty("content-length", Long.toString(filesize)); //*/ connection.connect(); OutputStream outputData = connection.getOutputStream(); IOUtils.copy(inputData, outputData); /// Those 2 lines are needed, otherwise, no request sent int code = connection.getResponseCode(); String msg = connection.getResponseMessage(); InputStream objReturn = connection.getInputStream(); StringWriter idResponse = new StringWriter(); IOUtils.copy(objReturn, idResponse); fileid = idResponse.toString(); connection.disconnect(); /// Construct Json StringWriter StringOutput = new StringWriter(); JsonWriter writer = new JsonWriter(StringOutput); writer.beginObject(); writer.name("files"); writer.beginArray(); writer.beginObject(); writer.name("name").value(fileName); writer.name("size").value(filesize); writer.name("type").value(contentType); writer.name("url").value(origin); writer.name("fileid").value(fileid); // writer.name("deleteUrl").value(ref); // writer.name("deleteType").value("DELETE"); writer.endObject(); writer.endArray(); writer.endObject(); writer.close(); json = StringOutput.toString(); /* DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { datawriter.write(buffer, 0, dataSize); } datawriter.flush(); datawriter.close(); //*/ // outputData.close(); // inputData.close(); break; } } } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } /* HttpURLConnection connection = CreateConnection( urlTarget, request ); connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); /// So we can forward some Set-Cookie String ref = request.getHeader("referer"); /// Prend le JSON du fileserver InputStream in = connection.getInputStream(); InitAnswer(connection, response, ref); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder builder = new StringBuilder(); for( String line = null; (line = reader.readLine()) != null; ) builder.append(line).append("\n"); //*/ /// Envoie la mise jour au backend /* try { PostForm.updateResource(session.getId(), backend, uuid, lang, json); } catch( Exception e ) { e.printStackTrace(); } //*/ connection.disconnect(); /// Renvoie le JSON au client response.setContentType("application/json"); PrintWriter respWriter = response.getWriter(); respWriter.write(json); // RetrieveAnswer(connection, response, ref); dataProvider.disconnect(); }
From source file:com.hichinaschool.flashcards.async.Connection.java
/** * Downloads any missing media files according to the mediaURL deckvar. * //from w ww .j a v a 2 s. c o m * @param data * @return The return type contains data.resultType and an array of Integer in data.data. data.data[0] is the number * of total missing media, data.data[1] is the number of downloaded ones. */ private Payload doInBackgroundDownloadMissingMedia(Payload data) { // Log.i(AnkiDroidApp.TAG, "DownloadMissingMedia"); HashMap<String, String> missingPaths = new HashMap<String, String>(); HashMap<String, String> missingSums = new HashMap<String, String>(); Decks deck = (Decks) data.data[0]; data.result = deck; // pass it to the return object so we close the deck in the deck picker String syncName = "";// deck.getDeckName(); data.success = false; data.data = new Object[] { 0, 0, 0 }; // if (!deck.hasKey("mediaURL")) { // data.success = true; // return data; // } String urlbase = "";// deck.getVar("mediaURL"); if (urlbase.equals("")) { data.success = true; return data; } String mdir = "";// deck.mediaDir(true); int totalMissing = 0; int missing = 0; int grabbed = 0; Cursor cursor = null; try { cursor = null;// deck.getDB().getDatabase().rawQuery("SELECT filename, originalPath FROM media", null); String path = null; String f = null; while (cursor.moveToNext()) { f = cursor.getString(0); path = mdir + "/" + f; File file = new File(path); if (!file.exists()) { missingPaths.put(f, path); missingSums.put(f, cursor.getString(1)); // Log.i(AnkiDroidApp.TAG, "Missing file: " + f); } } } finally { if (cursor != null) { cursor.close(); } } totalMissing = missingPaths.size(); data.data[0] = new Integer(totalMissing); if (totalMissing == 0) { data.success = true; return data; } publishProgress(Boolean.FALSE, new Integer(totalMissing), new Integer(0), syncName); URL url = null; HttpURLConnection connection = null; String path = null; String sum = null; int readbytes = 0; byte[] buf = new byte[4096]; for (String file : missingPaths.keySet()) { try { android.net.Uri uri = android.net.Uri.parse(Uri.encode(urlbase, ":/@%") + Uri.encode(file)); url = new URI(uri.toString()).toURL(); connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() == 200) { path = missingPaths.get(file); InputStream is = connection.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 4096); FileOutputStream fos = new FileOutputStream(path); while ((readbytes = bis.read(buf, 0, 4096)) != -1) { fos.write(buf, 0, readbytes); // Log.i(AnkiDroidApp.TAG, "Downloaded " + readbytes + " file: " + path); } fos.close(); // Verify with checksum sum = missingSums.get(file); if (true) {// sum.equals("") || sum.equals(Utils.fileChecksum(path))) { grabbed++; } else { // Download corrupted, delete file // Log.i(AnkiDroidApp.TAG, "Downloaded media file " + path + " failed checksum."); File f = new File(path); f.delete(); missing++; } } else { Log.e(AnkiDroidApp.TAG, "Connection error (" + connection.getResponseCode() + ") while retrieving media file " + urlbase + file); Log.e(AnkiDroidApp.TAG, "Connection message: " + connection.getResponseMessage()); if (missingSums.get(file).equals("")) { // Ignore and keep going missing++; } else { data.success = false; data.data = new Object[] { file }; return data; } } connection.disconnect(); } catch (URISyntaxException e) { Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e)); } catch (MalformedURLException e) { Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e)); Log.e(AnkiDroidApp.TAG, "MalformedURLException while download media file " + path); if (missingSums.get(file).equals("")) { // Ignore and keep going missing++; } else { data.success = false; data.data = new Object[] { file }; return data; } } catch (IOException e) { Log.e(AnkiDroidApp.TAG, Log.getStackTraceString(e)); Log.e(AnkiDroidApp.TAG, "IOException while download media file " + path); if (missingSums.get(file).equals("")) { // Ignore and keep going missing++; } else { data.success = false; data.data = new Object[] { file }; return data; } } finally { if (connection != null) { connection.disconnect(); } } publishProgress(Boolean.TRUE, new Integer(totalMissing), new Integer(grabbed + missing), syncName); } data.data[1] = new Integer(grabbed); data.data[2] = new Integer(missing); data.success = true; return data; }
From source file:com.wso2telco.dep.mediator.RequestExecutor.java
/** * Make tokenrequest./*from w w w . j a v a 2s . c om*/ * * @param tokenurl * the tokenurl * @param urlParameters * the url parameters * @param authheader * the authheader * @return the string */ protected String makeTokenrequest(String tokenurl, String urlParameters, String authheader, MessageContext messageContext) { ICallresponse icallresponse = null; String retStr = ""; URL neturl; HttpURLConnection connection = null; log.info("url : " + tokenurl + " | urlParameters : " + urlParameters + " | authheader : " + authheader + " Request ID: " + UID.getRequestID(messageContext)); if ((tokenurl != null && tokenurl.length() > 0) && (urlParameters != null && urlParameters.length() > 0) && (authheader != null && authheader.length() > 0)) { try { byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(tokenurl); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authheader); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connection.setUseCaches(false); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(postData); wr.flush(); wr.close(); if ((connection.getResponseCode() != 200) && (connection.getResponseCode() != 201) && (connection.getResponseCode() != 400) && (connection.getResponseCode() != 401)) { log.info("connection.getResponseMessage() : " + connection.getResponseMessage()); throw new RuntimeException("Failed : HTTP error code : " + connection.getResponseCode()); } InputStream is = null; if ((connection.getResponseCode() == 200) || (connection.getResponseCode() == 201)) { is = connection.getInputStream(); } else { is = connection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(is)); String output; while ((output = br.readLine()) != null) { retStr += output; } br.close(); } catch (Exception e) { log.error("[WSRequestService ], makerequest, " + e.getMessage(), e); return null; } finally { if (connection != null) { connection.disconnect(); } } } else { log.error("Token refresh details are invalid."); } return retStr; }