org.apache.http.entity.mime.FormBodyPart Java Examples

The following examples show how to use org.apache.http.entity.mime.FormBodyPart. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example #2
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: Http2Curl.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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);
  }

}
 
Example #4
Source File: MultipartForm.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #5
Source File: HttpServerTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
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;
                }
            });
}
 
Example #6
Source File: TestMultipartContent.java    From database with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: MultipartForm.java    From iaf with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #9
Source File: WineryConnector.java    From container with Apache License 2.0 5 votes vote down vote up
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 "";
    }
}
 
Example #10
Source File: MultipartHttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example #11
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #12
Source File: HttpSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #13
Source File: MultipartEntityBuilder.java    From iaf with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #14
Source File: MultipartEntityBuilder.java    From iaf with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: MultipartForm.java    From iaf with Apache License 2.0 5 votes vote down vote up
/**
  * 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);
		}
	}
 
Example #16
Source File: Http2Curl.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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());
  }
}
 
Example #17
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
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") + "/";
}
 
Example #20
Source File: HttpUtils.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: BitShare.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@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();
    }
}
 
Example #22
Source File: WineryConnector.java    From container with Apache License 2.0 4 votes vote down vote up
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;
    }
}
 
Example #23
Source File: MultipartForm.java    From iaf with Apache License 2.0 4 votes vote down vote up
public List<FormBodyPart> getBodyParts() {
	return this.parts;
}
 
Example #24
Source File: FreakShare.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@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();

    }
 
Example #25
Source File: SimpleHttpClient.java    From vespa with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example #26
Source File: Http2Curl.java    From curl-logger with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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();
}
 
Example #27
Source File: HttpSender.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected FormBodyPart createMultipartBodypart(String name, String message) {
	if(isMtomEnabled())
		return createMultipartBodypart(name, message, "application/xop+xml");
	else
		return createMultipartBodypart(name, message, null);
}
 
Example #28
Source File: LoadosophiaAPIClient.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example #29
Source File: HttpSender.java    From iaf with Apache License 2.0 4 votes vote down vote up
protected FormBodyPart createMultipartBodypart(String name, InputStream is, String fileName) {
	return createMultipartBodypart(name, is, fileName, ContentType.APPLICATION_OCTET_STREAM.getMimeType());
}
 
Example #30
Source File: MultipartForm.java    From iaf with Apache License 2.0 3 votes vote down vote up
/**
 * 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;
}