List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java
/** * Implement support for XForms 1.1 section "11.9.7 Serialization as multipart/form-data". * * @param document XML document to submit * @return MultipartRequestEntity *//*from ww w .j a v a 2s. c o m*/ public static MultipartEntity createMultipartFormData(final Document document) throws IOException { // Visit document final MultipartEntity multipartEntity = new MultipartEntity(); document.accept(new VisitorSupport() { public final void visit(Element element) { try { // Only care about elements // Only consider leaves i.e. elements without children elements final List children = element.elements(); if (children == null || children.size() == 0) { final String value = element.getText(); { // Got one! final String localName = element.getName(); final QName nodeType = InstanceData.getType(element); if (XMLConstants.XS_ANYURI_QNAME.equals(nodeType)) { // Interpret value as xs:anyURI if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:anyURI // Don't close the stream here, as it will get read later when the MultipartEntity // we create here is written to an output stream addPart(multipartEntity, URLFactory.createURL(value).openStream(), element, value); } else { // Value is invalid as per xs:anyURI // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else if (XMLConstants.XS_BASE64BINARY_QNAME.equals(nodeType)) { // Interpret value as xs:base64Binary if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:base64Binary addPart(multipartEntity, new ByteArrayInputStream(NetUtils.base64StringToByteArray(value)), element, null); } else { // Value is invalid as per xs:base64Binary // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else { // Just use the value as is multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } } } catch (IOException e) { throw new OXFException(e); } } }); return multipartEntity; }
From source file:org.openestate.is24.restapi.hc42.HttpComponents42Client.java
@Override protected Response sendXmlAttachmentRequest(URL url, RequestMethod method, String xml, InputStream input, String fileName, String mimeType) throws IOException, OAuthException { if (method == null) method = RequestMethod.POST;//from ww w. j av a 2s . co m if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method)) throw new IllegalArgumentException("Invalid request method!"); xml = (RequestMethod.POST.equals(method) || RequestMethod.PUT.equals(method)) ? StringUtils.trimToNull(xml) : null; HttpUriRequest request = null; if (RequestMethod.POST.equals(method)) { request = new HttpPost(url.toString()); } else if (RequestMethod.PUT.equals(method)) { request = new HttpPut(url.toString()); } else { throw new IOException("Unsupported request method '" + method + "'!"); } MultipartEntity requestMultipartEntity = new MultipartEntity(); request.addHeader(requestMultipartEntity.getContentType()); request.setHeader("Content-Language", "en-US"); request.setHeader("Accept", "application/xml"); // add xml part to the multipart entity if (xml != null) { //StringBody xmlPart = new StringBody( // xml, "application/xml; name=body.xml", Charset.forName( getEncoding() ) ); InputStreamBody xmlPart = new InputStreamBody(new ByteArrayInputStream(xml.getBytes(getEncoding())), "application/xml", "body.xml"); requestMultipartEntity.addPart("metadata", xmlPart); } // add file part to the multipart entity if (input != null) { mimeType = StringUtils.trimToNull(mimeType); if (mimeType == null) mimeType = "application/octet-stream"; fileName = StringUtils.trimToNull(fileName); if (fileName == null) fileName = "upload.bin"; InputStreamBody filePart = new InputStreamBody(input, mimeType, fileName); requestMultipartEntity.addPart("attachment", filePart); } // add multipart entity to the request ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity); // sign request getAuthConsumer().sign(request); // send request HttpResponse response = httpClient.execute(request); // create response return createResponse(response); }
From source file:de.fun2code.google.cloudprint.CloudPrintConnection.java
/** * Submits a new print job.//from ww w . j a va 2 s . co m * * @param printer * Printer to use. * @param document * Document to send. * @param contentType * Mime Type * @param capabilities * Capabilities (optional). * @param listener * Update listener that receives upload notifications in percent. * @return <tt>true</tt> on success, otherwise <tt>false</tt>. * @throws ClientProtocolException * @throws IOException * @throws JSONException */ public boolean submit(Printer printer, File document, String contentType, String capabilities, UploadListener listener) throws ClientProtocolException, IOException, JSONException { if (!document.exists()) { lastResponse.setSuccess(false); lastResponse.setMessage("Document does not exist."); return false; } if (capabilities == null) { capabilities = ""; } HttpPost post = new HttpPost(GCP_BASE_URL + "/" + GCP_CMD_SUBMIT); addGcpHeaders(post); FileBody doc = new CountingFileBody(document, listener); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("content", doc); reqEntity.addPart("output", new StringBody("json", Charset.forName("UTF-8"))); reqEntity.addPart("printerid", new StringBody(printer.getId(), Charset.forName("UTF-8"))); reqEntity.addPart("capabilities", new StringBody(capabilities, Charset.forName("UTF-8"))); reqEntity.addPart("contentType", new StringBody(contentType, Charset.forName("UTF-8"))); reqEntity.addPart("title", new StringBody(document.getName(), Charset.forName("UTF-8"))); post.setEntity(reqEntity); HttpResponse response = httpclient.execute(post); int code = response.getStatusLine().getStatusCode(); String responseStr = EntityUtils.toString(response.getEntity()); if (code == HttpStatus.SC_OK) { JSONObject json = new JSONObject(responseStr); if (json.has("message")) { lastResponse.setMessage(json.getString("message")); } if (json.getBoolean("success")) { lastResponse.setSuccess(true); return true; } else { lastResponse.setSuccess(false); return false; } } else { lastResponse.setSuccess(false); lastResponse.setMessage("HTTP result code: " + code); return false; } }
From source file:uk.ac.bbsrc.tgac.miso.core.manager.ERASubmissionManager.java
/** * Submits the given set of Submittables to the ERA submission service endpoint * * @param submissionData of type Set<Submittable<Document>> * @return Document//from ww w . ja v a 2s . c o m * @throws SubmissionException when an error occurred with the submission process */ public Document submit(Set<Submittable<Document>> submissionData) throws SubmissionException { try { DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); if (submissionEndPoint == null) { throw new SubmissionException( "No submission endpoint configured. Please check your submission.properties file."); } if (submissionData == null || submissionData.size() == 0) { throw new SubmissionException("No submission data set."); } if (accountName == null || dropBox == null || authKey == null) { throw new SubmissionException("An accountName, dropBox and authKey must be supplied!"); } if (centreName == null) { throw new SubmissionException( "No centreName configured. Please check your submission.properties file and specify your Center Name as given by the SRA."); } String curl = "curl -k "; StringBuilder sb = new StringBuilder(); sb.append(curl); String proxyHost = submissionProperties.getProperty("submission.proxyHost"); String proxyUser = submissionProperties.getProperty("submission.proxyUser"); String proxyPass = submissionProperties.getProperty("submission.proxyPass"); if (proxyHost != null && !proxyHost.equals("")) { sb.append("-x ").append(proxyHost); if (proxyUser != null && !proxyUser.equals("")) { sb.append("-U ").append(proxyUser); if (proxyPass != null && !proxyPass.equals("")) { sb.append(":").append(proxyPass); } } } //submit via REST to endpoint try { Map<String, List<Submittable<Document>>> map = new HashMap<String, List<Submittable<Document>>>(); map.put("study", new ArrayList<Submittable<Document>>()); map.put("sample", new ArrayList<Submittable<Document>>()); map.put("experiment", new ArrayList<Submittable<Document>>()); map.put("run", new ArrayList<Submittable<Document>>()); Document submissionXml = docBuilder.newDocument(); String subName = null; String d = df.format(new Date()); submissionProperties.put("submissionDate", d); for (Submittable<Document> s : submissionData) { if (s instanceof Submission) { //s.buildSubmission(); ERASubmissionFactory.generateParentSubmissionXML(submissionXml, (Submission) s, submissionProperties); subName = ((Submission) s).getName(); } else if (s instanceof Study) { map.get("study").add(s); } else if (s instanceof Sample) { map.get("sample").add(s); } else if (s instanceof Experiment) { map.get("experiment").add(s); } else if (s instanceof SequencerPoolPartition) { map.get("run").add(s); } } if (submissionXml != null && subName != null) { String url = getSubmissionEndPoint() + "?auth=ERA%20" + dropBox + "%20" + authKey; HttpClient httpclient = getEvilTrustingTrustManager(new DefaultHttpClient()); HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); String submissionXmlFileName = subName + File.separator + subName + "_submission_" + d + ".xml"; File subtmp = new File(submissionStoragePath + submissionXmlFileName); SubmissionUtils.transform(submissionXml, subtmp, true); reqEntity.addPart("SUBMISSION", new FileBody(subtmp)); for (String key : map.keySet()) { List<Submittable<Document>> submittables = map.get(key); String submittableXmlFileName = subName + File.separator + subName + "_" + key.toLowerCase() + "_" + d + ".xml"; File elementTmp = new File(submissionStoragePath + submittableXmlFileName); Document submissionDocument = docBuilder.newDocument(); ERASubmissionFactory.generateSubmissionXML(submissionDocument, submittables, key, submissionProperties); SubmissionUtils.transform(submissionDocument, elementTmp, true); reqEntity.addPart(key.toUpperCase(), new FileBody(elementTmp)); } httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); try { Document submissionReport = docBuilder.newDocument(); SubmissionUtils.transform(resEntity.getContent(), submissionReport); File savedReport = new File( submissionStoragePath + subName + File.separator + "report_" + d + ".xml"); SubmissionUtils.transform(submissionReport, savedReport); return submissionReport; } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } finally { submissionProperties.remove("submissionDate"); } } else { throw new SubmissionException("Response from submission endpoint (" + url + ") was not OK (200). Was: " + response.getStatusLine().getStatusCode()); } } else { throw new SubmissionException( "Could not find a Submission in the supplied set of Submittables"); } } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } finally { submissionProperties.remove("submissionDate"); } } catch (ParserConfigurationException e) { e.printStackTrace(); } return null; }
From source file:project.cs.netinfservice.netinf.node.resolution.NameResolutionService.java
/** * Creates an HTTP POST representation of a NetInf PUBLISH message. * * @param io// w ww. j a v a 2 s . c o m * The information object to publish * @return * A HttpPost representing the NetInf PUBLISH message * @throws UnsupportedEncodingException * In case the encoding is not supported */ private HttpPost createPublish(InformationObject io) throws UnsupportedEncodingException { // Extracting attributes from IO's identifier String hashAlg = getHashAlg(io.getIdentifier()); String hash = getHash(io.getIdentifier()); String contentType = getContentType(io.getIdentifier()); String meta = getMetadata(io.getIdentifier()); String bluetoothMac = getBluetoothMac(io); String filePath = getFilePath(io); // Creates a new post. Looks like http://host:port/netinfproto/publish HttpPost post = new HttpPost(HTTP + getHost() + ":" + getPort() + "/netinfproto/publish"); // Create a multipart entity MultipartEntity entity = new MultipartEntity(); // ni:///hashAlgorithm;hash?ct=CONTENT_TYPE StringBody uri = new StringBody("ni:///" + hashAlg + ";" + hash + "?ct=" + contentType); entity.addPart("URI", uri); // Create a new message id StringBody msgid = new StringBody(Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX))); entity.addPart("msgid", msgid); // Add a locator if (bluetoothMac != null) { StringBody l = new StringBody(bluetoothMac); entity.addPart("loc1", l); } // Add metadata (ext) if (meta != null) { StringBody ext = new StringBody(meta.toString()); entity.addPart("ext", ext); } // Add fullput and octets if (filePath != null) { StringBody fullPut = new StringBody("true"); entity.addPart("fullPut", fullPut); FileBody octets = new FileBody(new File(filePath)); entity.addPart("octets", octets); } // Add form type StringBody rform = new StringBody("json"); entity.addPart("rform", rform); // // Used to print the message sent to the NRS // try { // entity.writeTo(System.out); // } catch (IOException e) { // Log.e(TAG, "Failed to write MultipartEntity to System.out"); // } // Set attributes to HTTP Post object post.setEntity(entity); // Return HTTP Post object with all attributes return post; }
From source file:com.mpower.mintel.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(Long... values) { mResults = new HashMap<String, String>(); String postResponse;/*from w w w . ja v a 2 s .c o m*/ String selection = InstanceColumns._ID + "=?"; String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + InstanceColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. HttpContext localContext = MIntel.getInstance().getHttpContext(); HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); Map<URI, URI> uriRemap = new HashMap<URI, URI>(); Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) { return mResults; } publishProgress(c.getPosition() + 1, c.getCount()); String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } ContentValues cv = new ContentValues(); URI u = null; try { URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) ; is.close(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files List<File> files = new ArrayList<File>(); for (File f : allFiles) { String fileName = f.getName(); int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { File f = files.get(j); String fileName = f.getName(); int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }
From source file:com.mpower.daktar.android.tasks.InstanceUploaderTask.java
@Override protected HashMap<String, String> doInBackground(final Long... values) { mResults = new HashMap<String, String>(); String postResponse;/*from ww w . j a v a 2 s. co m*/ String selection = BaseColumns._ID + "=?"; final String[] selectionArgs = new String[values.length]; for (int i = 0; i < values.length; i++) { if (i != values.length - 1) { selection += " or " + BaseColumns._ID + "=?"; } selectionArgs[i] = values[i].toString(); } // get shared HttpContext so that authentication and cookies are // retained. final HttpContext localContext = MIntel.getInstance().getHttpContext(); final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT); final Map<URI, URI> uriRemap = new HashMap<URI, URI>(); final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); if (c.getCount() > 0) { c.moveToPosition(-1); next_submission: while (c.moveToNext()) { if (isCancelled()) return mResults; publishProgress(c.getPosition() + 1, c.getCount()); final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String id = c.getString(c.getColumnIndex(BaseColumns._ID)); final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id); String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI)); if (urlString == null) { final SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(MIntel.getInstance()); urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null); urlString = urlString + WebUtils.URL_PART_SUBMISSION; } final ContentValues cv = new ContentValues(); URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final MalformedURLException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final URISyntaxException e) { e.printStackTrace(); mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnsupportedEncodingException e) { e.printStackTrace(); mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } boolean openRosaServer = false; if (uriRemap.containsKey(u)) { // we already issued a head request and got a response, // so we know the proper URL to send the submission to // and the proper scheme. We also know that it was an // OpenRosa compliant server. openRosaServer = true; u = uriRemap.get(u); } else { // we need to issue a head request final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u); // prepare response HttpResponse response = null; try { response = httpclient.execute(httpHead, localContext); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { // we need authentication, so stop and return what // we've // done so far. mAuthRequestingServer = u; return null; } else if (statusCode == 204) { final Header[] locations = response.getHeaders("Location"); if (locations != null && locations.length == 1) { try { final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8")); final URI uNew = url.toURI(); if (u.getHost().equalsIgnoreCase(uNew.getHost())) { openRosaServer = true; // trust the server to tell us a new // location // ... and possibly to use https // instead. uriRemap.put(u, uNew); u = uNew; } else { // Don't follow a redirection attempt to // a different host. // We can't tell if this is a spoof or // not. mResults.put(id, fail + "Unexpected redirection attempt to a different host: " + uNew.toString()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + urlString + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } else { // may be a server that does not handle try { // have to read the stream in order to reuse the // connection final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final IOException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } Log.w(t, "Status code on Head request: " + statusCode); if (statusCode >= 200 && statusCode <= 299) { mResults.put(id, fail + "Invalid status code on Head request. If you have a web proxy, you may need to login to your network. "); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } } catch (final ClientProtocolException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Client Protocol Exception"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final ConnectTimeoutException e) { e.printStackTrace(); Log.e(t, e.getMessage()); mResults.put(id, fail + "Connection Timeout"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final UnknownHostException e) { e.printStackTrace(); mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + "Generic Exception"); Log.e(t, e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } } // At this point, we may have updated the uri to use https. // This occurs only if the Location header keeps the host name // the same. If it specifies a different host name, we error // out. // // And we may have set authentication cookies in our // cookiestore (referenced by localContext) that will enable // authenticated publication to the server. // // get instance file final File instanceFile = new File(instance); if (!instanceFile.exists()) { mResults.put(id, fail + "instance XML file does not exist!"); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue; } // find all files in parent directory final File[] allFiles = instanceFile.getParentFile().listFiles(); // add media files final List<File> files = new ArrayList<File>(); for (final File f : allFiles) { final String fileName = f.getName(); final int dotIndex = fileName.lastIndexOf("."); String extension = ""; if (dotIndex != -1) { extension = fileName.substring(dotIndex + 1); } if (fileName.startsWith(".")) { // ignore invisible files continue; } if (fileName.equals(instanceFile.getName())) { continue; // the xml file has already been added } else if (openRosaServer) { files.add(f); } else if (extension.equals("jpg")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gpp")) { // legacy 0.9x files.add(f); } else if (extension.equals("3gp")) { // legacy 0.9x files.add(f); } else if (extension.equals("mp4")) { // legacy 0.9x files.add(f); } else if (extension.equals("amr")) { // legacy 0.9x files.add(f); } else { Log.w(t, "unrecognized file type " + f.getName()); } } postResponse = ""; boolean first = true; int j = 0; while (j < files.size() || first) { first = false; final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth); final MimeTypeMap m = MimeTypeMap.getSingleton(); long byteCount = 0L; // mime post final MultipartEntity entity = new MultipartEntity(); // add the submission file first... FileBody fb = new FileBody(instanceFile, "text/xml"); entity.addPart("xml_submission_file", fb); Log.i(t, "added xml_submission_file: " + instanceFile.getName()); byteCount += instanceFile.length(); for (; j < files.size(); j++) { final File f = files.get(j); final String fileName = f.getName(); final int idx = fileName.lastIndexOf("."); String extension = ""; if (idx != -1) { extension = fileName.substring(idx + 1); } String contentType = m.getMimeTypeFromExtension(extension); // we will be processing every one of these, so // we only need to deal with the content type // determination... if (extension.equals("xml")) { fb = new FileBody(f, "text/xml"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xml file " + f.getName()); } else if (extension.equals("jpg")) { fb = new FileBody(f, "image/jpeg"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added image file " + f.getName()); } else if (extension.equals("3gpp")) { fb = new FileBody(f, "audio/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("3gp")) { fb = new FileBody(f, "video/3gpp"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("mp4")) { fb = new FileBody(f, "video/mp4"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added video file " + f.getName()); } else if (extension.equals("csv")) { fb = new FileBody(f, "text/csv"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added csv file " + f.getName()); } else if (f.getName().endsWith(".amr")) { fb = new FileBody(f, "audio/amr"); entity.addPart(f.getName(), fb); Log.i(t, "added audio file " + f.getName()); } else if (extension.equals("xls")) { fb = new FileBody(f, "application/vnd.ms-excel"); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added xls file " + f.getName()); } else if (contentType != null) { fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName()); } else { contentType = "application/octet-stream"; fb = new FileBody(f, contentType); entity.addPart(f.getName(), fb); byteCount += f.length(); Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName()); } // we've added at least one attachment to the request... if (j + 1 < files.size()) { if (byteCount + files.get(j + 1).length() > 10000000L) { // the next file would exceed the 10MB // threshold... Log.i(t, "Extremely long post is being split into multiple posts"); try { final StringBody sb = new StringBody("yes", Charset.forName("UTF-8")); entity.addPart("*isIncomplete*", sb); } catch (final Exception e) { e.printStackTrace(); // never happens... } ++j; // advance over the last attachment // added... break; } } } httppost.setEntity(entity); // prepare response and return uploaded HttpResponse response = null; try { response = httpclient.execute(httppost, localContext); final int responseCode = response.getStatusLine().getStatusCode(); // try { // // have to read the stream in order to reuse the // connection // InputStream is = response.getEntity().getContent(); // // read to end of stream... // final long count = 1024L; // while (is.skip(count) == count) // ; // is.close(); // } catch (IOException e) { // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } final HttpEntity httpEntity = response.getEntity(); try { postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim(); } catch (final IOException e) { e.printStackTrace(); } Log.i(t, "Response code:" + responseCode); // verify that the response was a 201 or 202. // If it wasn't, the submission has failed. if (responseCode != 201 && responseCode != 202) { if (responseCode == 200) { mResults.put(id, fail + "Network login failure? Again?"); } else { if (postResponse.length() > 0) { mResults.put(id, postResponse); } else { mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " (" + responseCode + ") at " + urlString); } } cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } catch (final Exception e) { e.printStackTrace(); mResults.put(id, fail + " " + e.getMessage()); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); continue next_submission; } } // if it got here, it must have worked if (postResponse.length() > 0) { // Custom msg from server mResults.put(id, postResponse); } else { // There is no response from server, use default string mResults.put(id, MIntel.getInstance().getString(R.string.success)); } // mResults.put(id, // MIntel.getInstance().getString(R.string.success)); cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED); MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null); } if (c != null) { c.close(); } } // end while return mResults; }