类org.apache.http.entity.mime.FormBodyPart源码实例Demo

下面列出了怎么用org.apache.http.entity.mime.FormBodyPart的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void testFileUploadWithEagerParsingAndNonASCIIFilename() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity();

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));

        File uploadfile = new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile());
        FormBodyPart filePart = new FormBodyPart("file", new FileBody(uploadfile, "τεστ", "application/octet-stream", Charsets.UTF_8.toString()));
        filePart.addField("Content-Disposition", "form-data; name=\"file\"; filename*=\"utf-8''%CF%84%CE%B5%CF%83%CF%84.txt\"");
        entity.addPart(filePart);

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
源代码2 项目: jmeter-bzm-plugins   文件: LoadosophiaAPIClient.java
public LoadosophiaUploadResults sendFiles(File targetFile, LinkedList<String> perfMonFiles) throws IOException {
    notifier.notifyAbout("Starting upload to BM.Sense");
    LoadosophiaUploadResults results = new LoadosophiaUploadResults();
    LinkedList<FormBodyPart> partsList = getUploadParts(targetFile, perfMonFiles);

    JSONObject res = queryObject(createPost(address + "api/files", partsList), 201);

    int queueID = Integer.parseInt(res.getString("QueueID"));
    results.setQueueID(queueID);

    int testID = getTestByUpload(queueID);
    results.setTestID(testID);

    setTestTitleAndColor(testID, title.trim(), colorFlag);
    results.setRedirectLink(address + "gui/" + testID + "/");
    return results;
}
 
源代码3 项目: curl-logger   文件: Http2Curl.java
private void handleMultipartEntity(HttpEntity entity, CurlCommand curl) {
  try {
    HttpEntity wrappedEntity = (HttpEntity) getFieldValue(entity, "wrappedEntity");
    RestAssuredMultiPartEntity multiPartEntity = (RestAssuredMultiPartEntity) wrappedEntity;
    MultipartEntityBuilder multipartEntityBuilder = (MultipartEntityBuilder) getFieldValue(
        multiPartEntity, "builder");

    @SuppressWarnings("unchecked")
    List<FormBodyPart> bodyParts = (List<FormBodyPart>) getFieldValue(multipartEntityBuilder,
        "bodyParts");

    bodyParts.forEach(p -> handlePart(p, curl));
  } catch (NoSuchFieldException | IllegalAccessException e) {
    throw new RuntimeException(e);
  }

}
 
源代码4 项目: vespa   文件: HttpServerTest.java
private static FormBodyPart newFileBody(final String parameterName, final String fileName, final String fileContent)
        throws Exception {
    return new FormBodyPart(
            parameterName,
            new StringBody(fileContent, ContentType.TEXT_PLAIN) {
                @Override
                public String getFilename() {
                    return fileName;
                }

                @Override
                public String getTransferEncoding() {
                    return "binary";
                }

                @Override
                public String getMimeType() {
                    return "";
                }

                @Override
                public String getCharset() {
                    return null;
                }
            });
}
 
源代码5 项目: database   文件: TestMultipartContent.java
private HttpEntity getUpdateEntity() {
	final Random r = new Random();
	final byte[] data = new byte[256];
	
       final MultipartEntity entity = new MultipartEntity();
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("remove", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "remove")));
       r.nextBytes(data);
       entity.addPart(new FormBodyPart("add", 
               new ByteArrayBody(
                       data, 
                       "application/xml", 
                       "add")));
	
       return entity;
}
 
源代码6 项目: iaf   文件: MultipartForm.java
void doWriteTo(
	final OutputStream out,
	final boolean writeContent) throws IOException {

	final ByteArrayBuffer boundaryEncoded = encode(this.charset, this.boundary);
	for (final FormBodyPart part: getBodyParts()) {
		writeBytes(TWO_DASHES, out);
		writeBytes(boundaryEncoded, out);
		writeBytes(CR_LF, out);

		formatMultipartHeader(part, out);

		writeBytes(CR_LF, out);

		if (writeContent) {
			part.getBody().writeTo(out);
		}
		writeBytes(CR_LF, out);
	}
	writeBytes(TWO_DASHES, out);
	writeBytes(boundaryEncoded, out);
	writeBytes(TWO_DASHES, out);
	writeBytes(CR_LF, out);
}
 
源代码7 项目: iaf   文件: MultipartForm.java
/**
 * Determines the total length of the multipart content (content length of
 * individual parts plus that of extra elements required to delimit the parts
 * from one another). If any of the @{link BodyPart}s contained in this object
 * is of a streaming entity of unknown length the total length is also unknown.
 * <p>
 * This method buffers only a small amount of data in order to determine the
 * total length of the entire entity. The content of individual parts is not
 * buffered.
 * </p>
 *
 * @return total length of the multipart entity if known, {@code -1} otherwise.
 */
public long getTotalLength() {
	long contentLen = 0;
	for (final FormBodyPart part: getBodyParts()) {
		final ContentBody body = part.getBody();
		final long len = body.getContentLength();
		if (len >= 0) {
			contentLen += len;
		} else {
			return -1;
		}
	}
	final ByteArrayOutputStream out = new ByteArrayOutputStream();
	try {
		doWriteTo(out, false);
		final byte[] extra = out.toByteArray();
		return contentLen + extra.length;
	} catch (final IOException ex) {
		// Should never happen
		return -1;
	}
}
 
源代码8 项目: iaf   文件: HttpSender.java
protected FormBodyPart elementToFormBodyPart(Element element, IPipeLineSession session) {
	String partName = element.getAttribute("name"); //Name of the part
	String partSessionKey = element.getAttribute("sessionKey"); //SessionKey to retrieve data from
	String partMimeType = element.getAttribute("mimeType"); //MimeType of the part
	Object partObject = session.get(partSessionKey);

	if (partObject instanceof InputStream) {
		InputStream fis = (InputStream) partObject;

		return createMultipartBodypart(partSessionKey, fis, partName, partMimeType);
	} else {
		String partValue = (String) session.get(partSessionKey);

		return createMultipartBodypart(partName, partValue, partMimeType);
	}
}
 
源代码9 项目: jmeter-bzm-plugins   文件: HttpUtils.java
/**
 * Create Post Request with FormBodyPart body
 */
public HttpPost createPost(String uri, LinkedList<FormBodyPart> partsList) {
    HttpPost postRequest = new HttpPost(uri);
    MultipartEntity multipartRequest = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (FormBodyPart part : partsList) {
        multipartRequest.addPart(part);
    }
    postRequest.setEntity(multipartRequest);
    return postRequest;
}
 
源代码10 项目: jmeter-bzm-plugins   文件: LoadosophiaAPIClient.java
public String startOnline() throws IOException {
    String uri = address + "api/active/receiver/start";
    LinkedList<FormBodyPart> partsList = new LinkedList<>();
    partsList.add(new FormBodyPart("token", new StringBody(token)));
    partsList.add(new FormBodyPart("projectKey", new StringBody(project)));
    partsList.add(new FormBodyPart("title", new StringBody(title)));
    JSONObject obj = queryObject(createPost(uri, partsList), 201);
    return address + "gui/active/" + obj.optString("OnlineID", "N/A") + "/";
}
 
源代码11 项目: jmeter-bzm-plugins   文件: LoadosophiaAPIClient.java
public void sendOnlineData(JSONArray data) throws IOException {
    String uri = address + "api/active/receiver/data";
    LinkedList<FormBodyPart> partsList = new LinkedList<>();
    String dataStr = data.toString();
    log.debug("Sending active test data: " + dataStr);
    partsList.add(new FormBodyPart("data", new StringBody(dataStr)));
    query(createPost(uri, partsList), 202);
}
 
源代码12 项目: jmeter-bzm-plugins   文件: LoadosophiaAPIClient.java
private LinkedList<FormBodyPart> getUploadParts(File targetFile, LinkedList<String> perfMonFiles) throws IOException {
    if (targetFile.length() == 0) {
        throw new IOException("Cannot send empty file to BM.Sense");
    }

    log.info("Preparing files to send");
    LinkedList<FormBodyPart> partsList = new LinkedList<>();
    partsList.add(new FormBodyPart("projectKey", new StringBody(project)));
    partsList.add(new FormBodyPart("jtl_file", new FileBody(gzipFile(targetFile))));

    Iterator<String> it = perfMonFiles.iterator();
    int index = 0;
    while (it.hasNext()) {
        File perfmonFile = new File(it.next());
        if (!perfmonFile.exists()) {
            log.warn("File not exists, skipped: " + perfmonFile.getAbsolutePath());
            continue;
        }

        if (perfmonFile.length() == 0) {
            log.warn("Empty file skipped: " + perfmonFile.getAbsolutePath());
            continue;
        }

        partsList.add(new FormBodyPart("perfmon_" + index, new FileBody(gzipFile(perfmonFile))));
        index++;
    }
    return partsList;
}
 
源代码13 项目: curl-logger   文件: Http2Curl.java
private void handlePart(FormBodyPart bodyPart, CurlCommand curl) {
  String contentDisposition = bodyPart.getHeader().getFields().stream()
      .filter(f -> f.getName().equals("Content-Disposition"))
      .findFirst()
      .orElseThrow(() -> new RuntimeException("Multipart missing Content-Disposition header"))
      .getBody();

  List<String> elements = Arrays.asList(contentDisposition.split(";"));
  Map<String, String> map = elements.stream().map(s -> s.trim().split("="))
      .collect(Collectors.toMap(a -> a[0], a -> a.length == 2 ? a[1] : ""));

  if (map.containsKey("form-data")) {

    String partName = removeQuotes(map.get("name"));

    StringBuilder partContent = new StringBuilder();
    if (map.get("filename") != null) {
      partContent.append("@").append(removeQuotes(map.get("filename")));
    } else {
      try {
        partContent.append(getContent(bodyPart));
      } catch (IOException e) {
        throw new RuntimeException("Could not read content of the part", e);
      }
    }
    partContent.append(";type=").append(bodyPart.getHeader().getField("Content-Type").getBody());

    curl.addFormPart(partName, partContent.toString());

  } else {
    throw new RuntimeException("Unsupported type " + map.entrySet().stream().findFirst().get());
  }
}
 
源代码14 项目: container   文件: WineryConnector.java
private String uploadCSARToWinery(final File file, final boolean overwrite) throws URISyntaxException, IOException {
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    final ContentBody fileBody = new FileBody(file);
    final ContentBody overwriteBody = new StringBody(String.valueOf(overwrite), ContentType.TEXT_PLAIN);
    final FormBodyPart filePart = FormBodyPartBuilder.create("file", fileBody).build();
    final FormBodyPart overwritePart = FormBodyPartBuilder.create("overwrite", overwriteBody).build();
    builder.addPart(filePart);
    builder.addPart(overwritePart);

    final HttpEntity entity = builder.build();

    final HttpPost wineryPost = new HttpPost();

    wineryPost.setURI(new URI(this.wineryPath));
    wineryPost.setEntity(entity);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final CloseableHttpResponse wineryResp = httpClient.execute(wineryPost);
        String location = getHeaderValue(wineryResp, HttpHeaders.LOCATION);
        wineryResp.close();

        if (Objects.nonNull(location) && location.endsWith("/")) {
            location = location.substring(0, location.length() - 1);
        }
        return location;
    } catch (final IOException e) {
        LOG.error("Exception while uploading CSAR to the Container Repository: ", e);
        return "";
    }
}
 
源代码15 项目: iaf   文件: MultipartForm.java
/**
  * Write the multipart header fields; depends on the style.
  */
protected void formatMultipartHeader(
		final FormBodyPart part,
		final OutputStream out) throws IOException {

		// For strict, we output all fields with MIME-standard encoding.
		final Header header = part.getHeader();
		for (final MinimalField field: header) {
			writeField(field, out);
		}
	}
 
源代码16 项目: iaf   文件: MultipartEntityBuilder.java
public MultipartEntityBuilder addPart(FormBodyPart bodyPart) {
	if (bodyPart == null) {
		return this;
	}
	if (this.bodyParts == null) {
		this.bodyParts = new ArrayList<FormBodyPart>();
	}

	if(mtom) {
		Header header = bodyPart.getHeader();
		String contentID;
		String fileName = bodyPart.getBody().getFilename();
		header.removeFields("Content-Disposition");
		if(fileName == null) {
			contentID = "<"+bodyPart.getName()+">";
		}
		else {
			bodyPart.addField("Content-Disposition", "attachment; name=\""+bodyPart.getName()+"\"; filename=\""+fileName+"\"");
			contentID = "<"+fileName+">";
		}
		bodyPart.addField("Content-ID", contentID);

		if(firstPart == null)
			firstPart = contentID;
	}

	this.bodyParts.add(bodyPart);
	return this;
}
 
源代码17 项目: iaf   文件: MultipartEntityBuilder.java
private MultipartEntity buildEntity() {
	String boundaryCopy = boundary;
	if (boundaryCopy == null && contentType != null) {
		boundaryCopy = contentType.getParameter("boundary");
	}
	if (boundaryCopy == null) {
		boundaryCopy = generateBoundary();
	}
	Charset charsetCopy = charset;
	if (charsetCopy == null && contentType != null) {
		charsetCopy = contentType.getCharset();
	}

	List<NameValuePair> paramsList = new ArrayList<NameValuePair>(5);
	paramsList.add(new BasicNameValuePair("boundary", boundaryCopy));
	if (charsetCopy != null) {
		paramsList.add(new BasicNameValuePair("charset", charsetCopy.name()));
	}

	String subtypeCopy = DEFAULT_SUBTYPE;
	if(mtom) {
		paramsList.add(new BasicNameValuePair("type", "application/xop+xml"));
		paramsList.add(new BasicNameValuePair("start", firstPart));
		paramsList.add(new BasicNameValuePair("start-info", "text/xml"));
		subtypeCopy = MTOM_SUBTYPE;
	}

	NameValuePair[] params = paramsList.toArray(new NameValuePair[paramsList.size()]);
	ContentType contentTypeCopy = contentType != null ?
			contentType.withParameters(params) :
			ContentType.create("multipart/" + subtypeCopy, params);

	List<FormBodyPart> bodyPartsCopy = bodyParts != null ? new ArrayList<FormBodyPart>(bodyParts) :
			Collections.<FormBodyPart>emptyList();
	MultipartForm form = new MultipartForm(charsetCopy, boundaryCopy, bodyPartsCopy);
	return new MultipartEntity(form, contentTypeCopy, form.getTotalLength());
}
 
源代码18 项目: iaf   文件: HttpSender.java
protected FormBodyPart createMultipartBodypart(String name, String message, String contentType) {
	ContentType cType = ContentType.create("text/plain", getCharSet());
	if(StringUtils.isNotEmpty(contentType))
		cType = ContentType.create(contentType, getCharSet());

	FormBodyPartBuilder bodyPart = FormBodyPartBuilder.create()
		.setName(name)
		.setBody(new StringBody(message, cType));

	if (StringUtils.isNotEmpty(getMtomContentTransferEncoding()))
		bodyPart.setField(MIME.CONTENT_TRANSFER_ENC, getMtomContentTransferEncoding());

	return bodyPart.build();
}
 
源代码19 项目: iaf   文件: HttpSender.java
protected FormBodyPart createMultipartBodypart(String name, InputStream is, String fileName, String contentType) {
	if (log.isDebugEnabled()) log.debug(getLogPrefix()+"appending filepart ["+name+"] with value ["+is+"] fileName ["+fileName+"] and contentType ["+contentType+"]");
	FormBodyPartBuilder bodyPart = FormBodyPartBuilder.create()
		.setName(name)
		.setBody(new InputStreamBody(is, ContentType.create(contentType, getCharSet()), fileName));
	return bodyPart.build();
}
 
源代码20 项目: iaf   文件: MultipartHttpSender.java
@Override
protected FormBodyPart elementToFormBodyPart(Element element, IPipeLineSession session) {
	String partType = element.getAttribute("type"); //File or otherwise
	String partName = element.getAttribute("name"); //Name of the part
	String fileName = (StringUtils.isNotEmpty(element.getAttribute("filename"))) ? element.getAttribute("filename") : element.getAttribute("fileName"); //Name of the file
	String sessionKey = element.getAttribute("sessionKey"); //SessionKey to retrieve data from
	String mimeType = element.getAttribute("mimeType"); //MimeType of the part
	String partValue = element.getAttribute("value"); //Value when SessionKey is empty or not set
	Object partObject = session.get(sessionKey);

	if (partObject != null && partObject instanceof InputStream) {
		InputStream fis = (InputStream) partObject;

		if(StringUtils.isNotEmpty(fileName)) {
			return createMultipartBodypart(partName, fis, fileName, mimeType);
		}
		else if("file".equalsIgnoreCase(partType)) {
			return createMultipartBodypart(sessionKey, fis, partName, mimeType);
		}
		else {
			return createMultipartBodypart(partName, fis, null, mimeType);
		}
	} else {
		String value = (String) session.get(sessionKey);
		if(StringUtils.isEmpty(value))
			value = partValue;

		return createMultipartBodypart(partName, value, mimeType);
	}
}
 
源代码21 项目: jmeter-bzm-plugins   文件: LoadosophiaAPIClient.java
public void endOnline(String redirectLink) throws IOException {
    String uri = address + "api/active/receiver/stop";
    LinkedList<FormBodyPart> partsList = new LinkedList<>();
    partsList.add(new FormBodyPart("redirect", new StringBody(redirectLink)));
    query(createPost(uri, partsList), 205);
}
 
源代码22 项目: curl-logger   文件: Http2Curl.java
private static String getContent(FormBodyPart bodyPart) throws IOException {
  ContentBody content = bodyPart.getBody();
  ByteArrayOutputStream out = new ByteArrayOutputStream((int) content.getContentLength());
  content.writeTo(out);
  return out.toString();
}
 
源代码23 项目: vespa   文件: SimpleHttpClient.java
public RequestExecutor setMultipartContent(final FormBodyPart... parts) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    Arrays.stream(parts).forEach(part -> builder.addPart(part.getName(), part.getBody()));
    this.entity = builder.build();
    return this;
}
 
源代码24 项目: neembuu-uploader   文件: FreakShare.java
@Override
    public void run() {
        try {
            if (freakShareAccount.loginsuccessful) {
                userType = "reg";
                httpContext = freakShareAccount.getHttpContext();
                sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
                
                if(freakShareAccount.isPremium()){
                    maxFileSizeLimit = 8438939648l; //8048 MB
                }
                else{
                    maxFileSizeLimit = 4244635648l; //4048 MB
                }
                
            } else {
                userType = "anon";
                cookieStore = new BasicCookieStore();
                httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
                maxFileSizeLimit = 1073741824l; //1024 MB
            }

            if (file.length() > maxFileSizeLimit) {
                throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
            }
            uploadInitialising();
            initialize();

            
            httpPost = new NUHttpPost(uploadURL);
            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            mpEntity.addPart("APC_UPLOAD_PROGRESS", new StringBody(progressKey));
            mpEntity.addPart("APC_UPLOAD_USERGROUP", new StringBody(userGroupKey));
            mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uploadIdentifier));
            FormBodyPart customBodyPart = FormBodyPartUtils.createEmptyFileFormBodyPart("file[]", new StringBody(""));
            mpEntity.addPart(customBodyPart);
            mpEntity.addPart("file[]", createMonitoredFileBody());
            httpPost.setEntity(mpEntity);
            
            NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
            NULogger.getLogger().info("Now uploading your file into FreakShare.com");
            uploading();
            httpResponse = httpclient.execute(httpPost, httpContext);
            final String location = httpResponse.getFirstHeader("Location").getValue();
            EntityUtils.consume(httpResponse.getEntity());
            responseString = NUHttpClientUtils.getData(location, httpContext);

            //Read the links
            gettingLink();
            //FileUtils.saveInFile("FreakShare.html", responseString);
            
            doc = Jsoup.parse(responseString);
            downloadlink = doc.select("input[type=text]").eq(0).val();
            deletelink = doc.select("input[type=text]").eq(3).val();
            
            NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
            NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
            downURL = downloadlink;
            delURL = deletelink;
            
            uploadFinished();
        } catch(NUException ex){
            ex.printError();
            uploadInvalid();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);

            uploadFailed();
        }
        
        //Checking once again as user may disable account while this upload thread is waiting in queue

//        uploadWithoutLogin();

    }
 
源代码25 项目: neembuu-uploader   文件: BitShare.java
@Override
public void run() {
    try {
        if (bitShareAccount.loginsuccessful) {
            httpContext = bitShareAccount.getHttpContext();
            
            if(bitShareAccount.isPremium()){
                maxFileSizeLimit = 1073741824l; //1024 MB
            }
            else{
                maxFileSizeLimit = 2147483648l; //2048 MB
            }
            
        } else {
            cookieStore = new BasicCookieStore();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            maxFileSizeLimit = 1073741824l; //1024 MB
        }

        if (file.length() > maxFileSizeLimit) {
            throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
        }
        uploadInitialising();
        initialize();

        
        httpPost = new NUHttpPost(uploadURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("APC_UPLOAD_PROGRESS", new StringBody(progressKey));
        mpEntity.addPart("APC_UPLOAD_USERGROUP", new StringBody(userGroupKey));
        mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uploadIdentifier));
        FormBodyPart customBodyPart = FormBodyPartUtils.createEmptyFileFormBodyPart("file[]", new StringBody(""));
        mpEntity.addPart(customBodyPart);
        mpEntity.addPart("file[]", createMonitoredFileBody());
        httpPost.setEntity(mpEntity);
        
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into BitShare.com");
        uploading();
        httpResponse = httpclient.execute(httpPost, httpContext);
        final String location = httpResponse.getFirstHeader("Location").getValue();
        responseString = EntityUtils.toString(httpResponse.getEntity());
        responseString = NUHttpClientUtils.getData(location, httpContext);
 
        //Read the links
        gettingLink();
        //FileUtils.saveInFile("BitShare.html", responseString);
        
        doc = Jsoup.parse(responseString);
        downloadlink = doc.select("#filedetails input[type=text]").eq(1).val();
        deletelink = doc.select("#filedetails input[type=text]").eq(4).val();
        
        NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
        NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
        downURL = downloadlink;
        delURL = deletelink;
        
        uploadFinished();
    } catch(NUException ex){
        ex.printError();
        uploadInvalid();
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);

        uploadFailed();
    }
}
 
源代码26 项目: container   文件: WineryConnector.java
public QName createServiceTemplateFromXaaSPackage(final File file, final QName artifactType,
                                                  final Set<QName> nodeTypes, final QName infrastructureNodeType,
                                                  final Map<String, String> tags) throws URISyntaxException,
    IOException {
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    // file
    final ContentBody fileBody = new FileBody(file);
    final FormBodyPart filePart = FormBodyPartBuilder.create("file", fileBody).build();
    builder.addPart(filePart);

    // artefactType
    final ContentBody artefactTypeBody = new StringBody(artifactType.toString(), ContentType.TEXT_PLAIN);
    final FormBodyPart artefactTypePart = FormBodyPartBuilder.create("artefactType", artefactTypeBody).build();
    builder.addPart(artefactTypePart);

    // nodeTypes
    if (!nodeTypes.isEmpty()) {
        String nodeTypesAsString = "";
        for (final QName nodeType : nodeTypes) {
            nodeTypesAsString += nodeType.toString() + ",";
        }

        final ContentBody nodeTypesBody =
            new StringBody(nodeTypesAsString.substring(0, nodeTypesAsString.length() - 1), ContentType.TEXT_PLAIN);
        final FormBodyPart nodeTypesPart = FormBodyPartBuilder.create("nodeTypes", nodeTypesBody).build();
        builder.addPart(nodeTypesPart);
    }

    // infrastructureNodeType
    if (infrastructureNodeType != null) {
        final ContentBody infrastructureNodeTypeBody =
            new StringBody(infrastructureNodeType.toString(), ContentType.TEXT_PLAIN);
        final FormBodyPart infrastructureNodeTypePart =
            FormBodyPartBuilder.create("infrastructureNodeType", infrastructureNodeTypeBody).build();
        builder.addPart(infrastructureNodeTypePart);
    }

    // tags
    if (!tags.isEmpty()) {
        String tagsString = "";
        for (final String key : tags.keySet()) {
            if (tags.get(key) == null) {
                tagsString += key + ",";
            } else {
                tagsString += key + ":" + tags.get(key) + ",";
            }
        }

        final ContentBody tagsBody =
            new StringBody(tagsString.substring(0, tagsString.length() - 1), ContentType.TEXT_PLAIN);
        final FormBodyPart tagsPart = FormBodyPartBuilder.create("tags", tagsBody).build();
        builder.addPart(tagsPart);
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        // POST to XaaSPackager
        final HttpPost xaasPOST = new HttpPost();
        xaasPOST.setURI(new URI(this.wineryPath + "servicetemplates/"));
        xaasPOST.setEntity(builder.build());
        final CloseableHttpResponse xaasResp = httpClient.execute(xaasPOST);
        xaasResp.close();

        // create QName of the created serviceTemplate resource
        String location = getHeaderValue(xaasResp, HttpHeaders.LOCATION);

        if (location.endsWith("/")) {
            location = location.substring(0, location.length() - 1);
        }

        final String localPart = getLastPathFragment(location);
        final String namespaceDblEnc = getLastPathFragment(location.substring(0, location.lastIndexOf("/")));
        final String namespace = URLDecoder.decode(URLDecoder.decode(namespaceDblEnc));

        return new QName(namespace, localPart);
    } catch (final IOException e) {
        LOG.error("Exception while calling Xaas packager: ", e);
        return null;
    }
}
 
源代码27 项目: iaf   文件: MultipartForm.java
public List<FormBodyPart> getBodyParts() {
	return this.parts;
}
 
源代码28 项目: iaf   文件: HttpSender.java
protected FormBodyPart createMultipartBodypart(String name, String message) {
	if(isMtomEnabled())
		return createMultipartBodypart(name, message, "application/xop+xml");
	else
		return createMultipartBodypart(name, message, null);
}
 
源代码29 项目: iaf   文件: HttpSender.java
protected FormBodyPart createMultipartBodypart(String name, InputStream is, String fileName) {
	return createMultipartBodypart(name, is, fileName, ContentType.APPLICATION_OCTET_STREAM.getMimeType());
}
 
源代码30 项目: iaf   文件: MultipartForm.java
/**
 * Creates an instance with the specified settings.
 *
 * @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
 * @param boundary to use  - must not be {@code null}
 * @throws IllegalArgumentException if charset is null or boundary is null
 */
public MultipartForm(final Charset charset, final String boundary, final List<FormBodyPart> parts) {
	Args.notNull(boundary, "Multipart boundary");
	this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
	this.boundary = boundary;
	this.parts = parts;
}
 
 类所在包
 同包方法