Creates and returns a boundary for multipart request.

@return Created boundary.
182287
public static final String createBoundary() {
		final StringBuilder builder = new StringBuilder(BOUNDARY_PREFIX);
		builder.append((int) System.currentTimeMillis());
		return builder.toString();
	}
1344071
public function multipart()
    {

        if (empty($this->_multiparts)) {

            $this->_multiparts = array();

            if (!$this->isContentType('multipart/mixed')) {
                throw new Exception('Response is not multipart');
            }

            // Step 1. Get boundary

            preg_match('/boundary=([^";]+)/i', $this->getContentType(), $matches);

            if (empty($matches[1])) {
                throw new Exception('Boundary not found');
            }

            $boundary = $matches[1];

            // Step 2. Split by boundary and remove first and last parts if needed

            $parts = explode('--' . $boundary . '', $this->text()); //TODO Handle as stream

            if (empty(trim($parts[0]))) {
                array_shift($parts);
            }

            if (trim($parts[count($parts) - 1]) == '--') {
                array_pop($parts);
            }

            if (count($parts) == 0) {
                throw new Exception('No parts found');
            }

            // Step 3. Create status info object

            $statusInfoPart = array_shift($parts);
            $statusInfoObj = new self(null,
                self::createResponse(trim($statusInfoPart), $this->response()->getStatusCode())
            );
            $statusInfo = $statusInfoObj->json()->response;

            // Step 4. Parse all parts into Response objects

            foreach ($parts as $i => $part) {

                $partInfo = $statusInfo[$i];

                $this->_multiparts[] = new self(null, self::createResponse(trim($part), $partInfo->status));

            }

        }

        return $this->_multiparts;

    }
913290
public JTSGeometryExpression<Geometry> boundary() {
        if (boundary == null) {
            boundary = JTSGeometryExpressions.geometryOperation(SpatialOps.BOUNDARY, mixin);
        }
        return boundary;
    }
285109
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
        MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
        for (Entry<String, Object> param : formParams.entrySet()) {
            if (param.getValue() instanceof File) {
                File file = (File) param.getValue();
                Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\"");
                MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file));
                mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file));
            } else {
                Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"");
                mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue())));
            }
        }
        return mpBuilder.build();
    }
351147
public function boundary($boundary = null)
    {
        if (!func_num_args()) {
            if (!$this->isMultipart()) {
                return;
            }
            if ($this->_boundary === null) {
                $this->_boundary = sha1(uniqid('', true));
            }
            return $this->_boundary;
        }
        $this->_boundary = $boundary;
        return $this;
    }
286193
protected function set_boundaries()
	{
		$uniq_id = md5(uniqid(microtime(true)));

		// Message part boundary, (separates message and attachments).
		$this->boundaries[0] = 'B1_'.$uniq_id;

		// Message body boundary (separates message, alt message)
		$this->boundaries[1] = 'B2_'.$uniq_id;

		$this->boundaries[2] = 'B3_'.$uniq_id;
	}
904405
def parse_multipart_formdata(reader, boundary, cb):
    

    breader = BoundaryReader(reader, boundary)
    # The BoundaryReader expects a new line before the boundary string,
    # We make sure the new line exists
    breader.put(b'\r\n')
    # Clean up garbage before the first boundary
    _dummy_data = yield from breader.read()
    logger('parse_multipart_formdata').debug('_dummy_data = %r', _dummy_data)
    del _dummy_data

    breader = BoundaryReader(reader, boundary)
    line = yield from breader.readline()
    while line:
        headers = []
        while line.strip():
            header = parse_http_header(line)
            headers.append(header)
            line = yield from breader.readline()

        yield from cb(headers, breader)

        yield from breader.read()
        breader = BoundaryReader(reader, boundary)
        line = yield from breader.readline()
1126909
protected function getBoundary($boundary, $charSet, $contentType, $encoding)
    {
        $result = '';
        if ('' == $charSet) {
            $charSet = $this->CharSet;
        }
        if ('' == $contentType) {
            $contentType = $this->ContentType;
        }
        if ('' == $encoding) {
            $encoding = $this->Encoding;
        }
        $result .= $this->textLine('--' . $boundary);
        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
        $result .= static::$LE;
        // RFC1341 part 5 says 7bit is assumed if not specified
        if ('7bit' != $encoding) {
            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
        }
        $result .= static::$LE;

        return $result;
    }
834919
protected function getBoundary()
    {
        $pos = strpos($this->contentType, "boundary=");
        if ($pos === false) {
            throw new DecodeException(
                "missing value for 'boundary' in content-type header"
            );
        }
        return "--" . substr($this->contentType, $pos + 9);
    }
1338160
public MultipartFormDataParser createMultipartFormDataParser() {
        MultipartFormDataParser parser = new MemoryMultipartFormDataParser();
        if (maxRequestSize > -1L) {
            parser.setMaxRequestSize(maxRequestSize);
        }
        if (maxFileSize > -1L) {
            parser.setMaxFileSize(maxFileSize);
        }
        parser.setAllowedFileExtensions(allowedFileExtensions);
        parser.setDeniedFileExtensions(deniedFileExtensions);
        return parser;
    }
824588
private Multipart createMultiPart() throws MessagingException {
		Multipart multipart = new MimeMultipart("alternative");
		if (textPart != null) {
			// add text first, to give priority to html
			multipart.addBodyPart((BodyPart) createTextMimePart());
		}
		if (htmlPart != null) {
			multipart.addBodyPart((BodyPart) createHtmlMimePart());
		}
		return multipart;
	}
676633
def encode_multipart(data, files):
    
    body = BytesIO()
    boundary = choose_boundary()
    part_boundary = b('--%s\r\n' % boundary)
    writer = codecs.lookup('utf-8')[3]

    if isinstance(data, dict):
        for name, values in data.items():
            if not isinstance(values, (list, tuple, set)):
                # behave like urllib.urlencode(dict, 1)
                values = (values, )
            for value in values:
                body.write(part_boundary)
                writer(body).write('Content-Disposition: form-data; '
                                   'name="%s"\r\n' % name)
                body.write(b'Content-Type: text/plain\r\n\r\n')
                if isinstance(value, int):
                    value = str(value)
                if py3k and isinstance(value, str):
                    writer(body).write(value)
                else:
                    body.write(value)
                body.write(b'\r\n')

    for fieldname, f in files.items():
        if isinstance(f, tuple):
            filename, f = f
        elif hasattr(f, 'name'):
            filename = basename(f.name)
        else:
            filename = None
            raise UrlfetchException("file must has filename")

        if hasattr(f, 'read'):
            value = f.read()
        elif isinstance(f, basestring):
            value = f
        else:
            value = str(f)

        body.write(part_boundary)
        if filename:
            writer(body).write('Content-Disposition: form-data; name="%s"; '
                               'filename="%s"\r\n' % (fieldname, filename))
            body.write(b'Content-Type: application/octet-stream\r\n\r\n')
        else:
            writer(body).write('Content-Disposition: form-data; name="%s"'
                               '\r\n' % name)
            body.write(b'Content-Type: text/plain\r\n\r\n')

        if py3k and isinstance(value, str):
            writer(body).write(value)
        else:
            body.write(value)
        body.write(b'\r\n')

    body.write(b('--' + boundary + '--\r\n'))

    content_type = 'multipart/form-data; boundary=%s' % boundary

    return content_type, body.getvalue()
71281
def encode_multipart_formdata(self, fields, files, baseName, verbose=False):
        
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        if verbose is True:
            print(('Encoding ' + baseName + ' for upload...'))
        fin = self._open(files, 'rb')
        fout = self._open(files + '.b64', 'wb')
        fout.write(bytearray('--' + BOUNDARY + CRLF, 'utf-8'))
        fout.write(bytearray('Content-Disposition: form-data'
                             '; name="file"; filename="' + baseName + '"' + CRLF, "utf-8"))
        fout.write(bytearray('Content-Type: application/octet-stream' + CRLF,
                             'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        shutil.copyfileobj(fin, fout)
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.write(bytearray('--' + BOUNDARY + '--' + CRLF, 'utf-8'))
        fout.write(bytearray(CRLF, 'utf-8'))
        fout.close()
        fin.close()
        return content_type
40880
def _encode_multipart(**kw):
    '  '
    boundary = '----------%s' % hex(int(time.time() * 1000))
    data = []
    for k, v in kw.iteritems():
        data.append('--%s' % boundary)
        if hasattr(v, 'read'):
            # file-like object:
            filename = getattr(v, 'name', '')
            content = v.read()
            data.append('Content-Disposition: form-data; name="%s"; filename="hidden"' % k)
            data.append('Content-Length: %d' % len(content))
            data.append('Content-Type: %s\r\n' % _guess_content_type(filename))
            data.append(content)
        else:
            data.append('Content-Disposition: form-data; name="%s"\r\n' % k)
            data.append(v.encode('utf-8') if isinstance(v, unicode) else v)
    data.append('--%s--\r\n' % boundary)
    return '\r\n'.join(data), boundary
9536
def encode_multipart_formdata(fields, files):
    
    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % guess_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
336236
private static MimeMultipart getContentAsMimeMultipart(ContentTypeHeader contentTypeHeader, byte[] rawContent) {
		// Issue 1123 : http://code.google.com/p/mobicents/issues/detail?id=1123 : Multipart type is supported
		String delimiter = contentTypeHeader.getParameter(MULTIPART_BOUNDARY);
		String start = contentTypeHeader.getParameter(MULTIPART_START);

		MimeMultipart mimeMultipart = new MimeMultipart(contentTypeHeader.getContentSubType());
		if (delimiter == null) {
			MimeBodyPart mbp = new MimeBodyPart();
		    DataSource ds = new ByteArrayDataSource(rawContent, contentTypeHeader.getContentSubType());
		    try {
				mbp.setDataHandler(new DataHandler(ds));
				mimeMultipart.addBodyPart(mbp);
			} catch (MessagingException e) {
				throw new IllegalArgumentException("couldn't create the multipart object from the message content " + rawContent, e);
			}
		} else {
			// splitting the body content by delimiter
		    String[] fragments = new String(rawContent).split(MULTIPART_BOUNDARY_DELIM + delimiter);
			for (String fragment: fragments) {
				final String trimmedFragment = fragment.trim();
				// skipping empty fragment and ending fragment looking like --
				if(trimmedFragment.length() > 0 && !MULTIPART_BOUNDARY_DELIM.equals(trimmedFragment)) {
					String fragmentHeaders = null;
					String fragmentBody = fragment;
					// if there is a start, it means that there is probably headers before the content that need to be added to the mime body part
					// so we split headers from body content
					if(start != null && start.length() > 0) {
						int indexOfStart = fragment.indexOf(start);
						if(indexOfStart != -1) {
							fragmentHeaders = fragmentBody.substring(0, indexOfStart + start.length());
							fragmentBody = fragmentBody.substring(indexOfStart + start.length()).trim();
						}
					}
					MimeBodyPart mbp = new MimeBodyPart();
				    try {
				    	String contentType = contentTypeHeader.getContentSubType();
				    	// check if the body content start with a Content-Type header
				    	// if so we strip it from the content body
				    	if(fragmentBody.startsWith(ContentTypeHeader.NAME)) {
				    		int indexOfLineReturn =  fragmentBody.indexOf(LINE_RETURN_DELIM);
				    		contentType = fragmentBody.substring(0, indexOfLineReturn -1).trim();
				    		fragmentBody = fragmentBody.substring(indexOfLineReturn).trim();
				    	}
				    	// setting the content body stripped from the headers
				    	mbp.setContent(fragmentBody, contentType);
				    	// adding the headers to the body part
				    	mbp.addHeaderLine(contentType);
				    	if(fragmentHeaders != null) {
				    		StringTokenizer stringTokenizer = new StringTokenizer(fragmentHeaders, LINE_RETURN_DELIM);
				    		while (stringTokenizer.hasMoreTokens()) {
				    			String token = stringTokenizer.nextToken().trim();
				    			if(token != null && token.length() > 0) {
				    				mbp.addHeaderLine(token);
				    			}
							}
				    	}
						mimeMultipart.addBodyPart(mbp);
					} catch (MessagingException e) {
						throw new IllegalArgumentException("couldn't create the multipart object from the message content " + rawContent, e);
					}
				}
			}
		}
		return mimeMultipart;
	}
550930
public byte[] readBoundary() throws IOException {
		ByteArrayOutputStream boundaryOutput = new ByteArrayOutputStream(1024);
		byte b;
		// skip optional whitespaces
		while ((b = readByte()) <= ' ') {
		}
		boundaryOutput.write(b);

		// now read boundary chars
		while ((b = readByte()) != '\r') {
			boundaryOutput.write(b);
		}
		if (boundaryOutput.size() == 0) {
			throw new IOException("Problems with parsing request: invalid boundary");
		}
		skipBytes(1);
		boundary = new byte[boundaryOutput.size() + 2];
		System.arraycopy(boundaryOutput.toByteArray(), 0, boundary, 2, boundary.length - 2);
		boundary[0] = '\r';
		boundary[1] = '\n';
		return boundary;
	}