org.apache.commons.httpclient.header Java Examples

The following examples show how to use org.apache.commons.httpclient.header. 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: RestClient.java    From maven-framework-project with MIT License 7 votes vote down vote up
public Book getBook(String bookName) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/getbook/";

            url = url + URLEncoder.encode(bookName, "UTF-8");

            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            client.executeMethod( mPost );
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("out : " + output);
        }catch(Exception e){
            throw new Exception("Exception in retriving group page info : " + e);
        }
        return null;
    }
 
Example #2
Source File: HttpFileContentInfoFactory.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {

    String contentType = null;
    String contentEncoding = null;

    HeadMethod headMethod;
    try (final HttpFileObject<HttpFileSystem> httpFile = (HttpFileObject<HttpFileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        headMethod = httpFile.getHeadMethod();
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
    final Header header = headMethod.getResponseHeader("content-type");
    if (header != null) {
        final HeaderElement[] element = header.getElements();
        if (element != null && element.length > 0) {
            contentType = element[0].getName();
        }
    }

    contentEncoding = headMethod.getResponseCharSet();

    return new DefaultFileContentInfo(contentType, contentEncoding);
}
 
Example #3
Source File: MicroIntegratorBaseUtils.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * This is a utility method which can be used to set security headers in a service client. This method
 * will create authorization header according to basic security protocol. i.e. encodeBase64(username:password)
 * and put it in a HTTP header with name "Authorization".
 *
 * @param userName      User calling the service.
 * @param password      Password of the user.
 * @param rememberMe    <code>true</code> if UI asks to persist remember me cookie.
 * @param serviceClient The service client used in the communication.
 */
public static void setBasicAccessSecurityHeaders(String userName, String password, boolean rememberMe,
                                                 ServiceClient serviceClient) {

    String userNamePassword = userName + ":" + password;
    String encodedString = Base64Utils.encode(userNamePassword.getBytes());

    String authorizationHeader = "Basic " + encodedString;

    List<Header> headers = new ArrayList<Header>();

    Header authHeader = new Header("Authorization", authorizationHeader);
    headers.add(authHeader);

    if (rememberMe) {
        Header rememberMeHeader = new Header("RememberMe", TRUE);
        headers.add(rememberMeHeader);
    }

    serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
}
 
Example #4
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * 处理请求自动转向问题
 * </p>
 * @param appServer
 * @param response
 * @param client
 * @param httppost
 * @throws IOException
 * @throws BusinessServletException
 */
private void dealWithRedirect(AppServer appServer, HttpServletResponse response, HttpClient client, HttpMethod httpMethod) 
           throws IOException, BusinessServletException {
    
	Header location = httpMethod.getResponseHeader("location");
	httpMethod.releaseConnection();
	
	if ( location == null || EasyUtils.isNullOrEmpty(location.getValue()) ) {
		throw new BusinessServletException(appServer.getName() + "(" + appServer.getCode() + ")返回错误的自动转向地址信息");
	}
	
	String redirectURI = location.getValue();
       GetMethod redirect = new GetMethod(redirectURI);
       try {
           client.executeMethod(redirect); // 发送Get请求
           
           transmitResponse(appServer, response, client, redirect);
           
       } finally {
           redirect.releaseConnection();
       }
}
 
Example #5
Source File: DefaultDiamondSubscriber.java    From diamond with Apache License 2.0 6 votes vote down vote up
/**
 * 回馈的结果为RP_NO_CHANGE,则整个流程为:<br>
 * 1.检查缓存中的MD5码与返回的MD5码是否一致,如果不一致,则删除缓存行。重新再次查询。<br>
 * 2.如果MD5码一致,则直接返回NULL<br>
 */
private String getNotModified(String dataId, CacheData cacheData, HttpMethod httpMethod) {
    Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5);
    if (null == md5Header) {
        throw new RuntimeException("RP_NO_CHANGE返回的结果中没有MD5码");
    }
    String md5 = md5Header.getValue();
    if (!cacheData.getMd5().equals(md5)) {
        String lastMd5 = cacheData.getMd5();
        cacheData.setMd5(Constants.NULL);
        cacheData.setLastModifiedHeader(Constants.NULL);
        throw new RuntimeException("MD5码校验对比出错,DataID为:[" + dataId + "]上次MD5为:[" + lastMd5 + "]本次MD5为:[" + md5
                + "]");
    }

    cacheData.setMd5(md5);
    changeSpacingInterval(httpMethod);
    if (log.isInfoEnabled()) {
        log.info("DataId: " + dataId + ", 对应的configInfo没有变化");
    }
    return null;
}
 
Example #6
Source File: BigSwitchApiTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test(expected = BigSwitchBcfApiException.class)
public void testExecuteUpdateObjectFailure() throws BigSwitchBcfApiException, IOException {
    NetworkData network = new NetworkData();
    _method = mock(PutMethod.class);
    when(_method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    Header header = mock(Header.class);
    when(header.getValue()).thenReturn("text/html");
    when(_method.getResponseHeader("Content-type")).thenReturn(header);
    when(_method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later.");
    when(_method.isRequestSent()).thenReturn(true);
    try {
        _api.executeUpdateObject(network, "/", Collections.<String, String> emptyMap());
    } finally {
        verify(_method, times(1)).releaseConnection();
    }
}
 
Example #7
Source File: HMACFilterAuthenticationProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String getHeaders(HttpMethodBase method) {
	Header[] headersArray = method.getRequestHeaders();
	Map<String, String> headers = new HashMap<>(headersArray.length);
	for (int i = 0; i < headersArray.length; i++) { // only 1 value admitted for each header
		headers.put(headersArray[i].getName(), headersArray[i].getValue());
	}

	StringBuilder res = new StringBuilder();
	for (String name : HMACUtils.HEADERS_SIGNED) {
		String value = headers.get(name); // only 1 value admitted
		if (value != null) {
			res.append(name);
			res.append(value);
		}
	}
	return res.toString();
}
 
Example #8
Source File: HttpUtilities.java    From odo with Apache License 2.0 6 votes vote down vote up
/**
 * Obtain newline-delimited headers from method
 *
 * @param method HttpMethod to scan
 * @return newline-delimited headers
 */
public static String getHeaders(HttpMethod method) {
    String headerString = "";
    Header[] headers = method.getRequestHeaders();
    for (Header header : headers) {
        String name = header.getName();
        if (name.equals(Constants.ODO_PROXY_HEADER)) {
            // skip.. don't want to log this
            continue;
        }

        if (headerString.length() != 0) {
            headerString += "\n";
        }

        headerString += header.getName() + ": " + header.getValue();
    }

    return headerString;
}
 
Example #9
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public long getHeaderFieldDate(String key, long def) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

  if (head == null) {
    return def;
  }

  try {
    Date date = DateUtil.parseDate(head.getValue());
    return date.getTime();

  } catch (DateParseException e) {
    return def;
  }
}
 
Example #10
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Execute the request with the request and response logged at debug level
 * @param method method to execute
 * @param client client to use
 * @param <M> method type
 * @return the status code
 * @throws IOException any failure reported by the HTTP client.
 */
private <M extends HttpMethod> int execWithDebugOutput(M method,
                                                       HttpClient client) throws
        IOException {
  if (LOG.isDebugEnabled()) {
    StringBuilder builder = new StringBuilder(
            method.getName() + " " + method.getURI() + "\n");
    for (Header header : method.getRequestHeaders()) {
      builder.append(header.toString());
    }
    LOG.debug(builder);
  }
  int statusCode = client.executeMethod(method);
  if (LOG.isDebugEnabled()) {
    LOG.debug("Status code = " + statusCode);
  }
  return statusCode;
}
 
Example #11
Source File: RestClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
public void addBook(String bookName, String author) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/addbook";
            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            mPost.addParameter("name", "Naked Sun");
            mPost.addParameter("author", "Issac Asimov");
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            //mtHeader.setValue("application/json");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("output : " + output);
        }catch(Exception e){
            throw new Exception("Exception in adding bucket : " + e);
        }

    }
 
Example #12
Source File: TraceResponseHandler.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Will either respond with data from the underlying server
 * or the proxy's own data.
 * @see net.sf.j2ep.model.ResponseHandler#process(javax.servlet.http.HttpServletResponse)
 */
public void process(HttpServletResponse response) throws IOException {
    
    if (proxyTargeted) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("content-type", "message/http");
        response.setHeader("Connection", "close");
        
        String path = method.getPath();
        String protocol = method.getParams().getVersion().toString();
        PrintWriter writer = response.getWriter();
        writer.println("TRACE " + path + " " + protocol);
        Header[] headers = method.getRequestHeaders();
        for (int i=0; i < headers.length; i++) {
            writer.print(headers[i]);
        }
        writer.flush();
        writer.close();
        
    } else {
        setHeaders(response);
        response.setStatus(getStatusCode());
        sendStreamToClient(response);
    }
}
 
Example #13
Source File: ARC2WCDX.java    From webarchive-commons with Apache License 2.0 5 votes vote down vote up
protected static void appendField(StringBuilder builder, Object obj) {
    if(builder.length()>0) {
        // prepend with delimiter
        builder.append(' ');
    }
    if(obj instanceof Header) {
        obj = ((Header)obj).getValue().trim();
    }

    builder.append((obj==null||obj.toString().length()==0)?"-":obj);
}
 
Example #14
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Find objects in a directory
 *
 * @param path path prefix
 * @param requestHeaders optional request headers
 * @return byte[] file data or null if the object was not found
 * @throws IOException on IO Faults
 * @throws FileNotFoundException if nothing is at the end of the URI -that is,
 * the directory is empty
 */
public byte[] listDeepObjectsInDirectory(SwiftObjectPath path,
                                         boolean listDeep,
                                     final Header... requestHeaders)
        throws IOException {
  preRemoteCommand("listDeepObjectsInDirectory");

  String endpoint = getEndpointURI().toString();
  StringBuilder dataLocationURI = new StringBuilder();
  dataLocationURI.append(endpoint);
  String object = path.getObject();
  if (object.startsWith("/")) {
    object = object.substring(1);
  }
  if (!object.endsWith("/")) {
    object = object.concat("/");
  }

  if (object.equals("/")) {
    object = "";
  }

  dataLocationURI = dataLocationURI.append("/")
          .append(path.getContainer())
          .append("/?prefix=")
          .append(object)
          .append("&format=json");

  //in listing deep set param to false
  if (listDeep == false) {
      dataLocationURI.append("&delimiter=/");
  }

  return findObjects(dataLocationURI.toString(), requestHeaders);
}
 
Example #15
Source File: AuthUtils.java    From httpclientAuthHelper with Apache License 2.0 5 votes vote down vote up
public static Header[] printResponseHeaders(HttpMethodBase httpget) throws IOException {
    System.out.println("Printing Response Header...\n");

    Header[] headers = httpget.getResponseHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName()
                + " ,Value : " + header.getValue());

    }
    return headers;
}
 
Example #16
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example #17
Source File: DifidoClient.java    From difido-reports with Apache License 2.0 5 votes vote down vote up
public void addTestDetails(int executionId, TestDetails testDetails) throws Exception {
	PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/details");
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(testDetails);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	final int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
}
 
Example #18
Source File: SwiftNativeFileSystemStore.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Does the object exist
 *
 * @param path swift object path
 * @return true if the metadata of an object could be retrieved
 * @throws IOException IO problems other than FileNotFound, which
 *                     is downgraded to an object does not exist return code
 */
public boolean objectExists(SwiftObjectPath path) throws IOException {
  try {
    Header[] headers = swiftRestClient.headRequest("objectExists",
                                                   path,
                                                   SwiftRestClient.NEWEST);
    //no headers is treated as a missing file
    return headers.length != 0;
  } catch (FileNotFoundException e) {
    return false;
  }
}
 
Example #19
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 5 votes vote down vote up
/**
 * Find objects in a directory
 *
 * @param path path prefix
 * @param addTrailingSlash should a trailing slash be added if there isn't one
 * @param requestHeaders optional request headers
 * @return byte[] file data or null if the object was not found
 * @throws IOException on IO Faults
 * @throws FileNotFoundException if nothing is at the end of the URI -that is,
 * the directory is empty
 */
public byte[] listDeepObjectsInDirectory(SwiftObjectPath path,
                                         boolean listDeep,
                                         boolean addTrailingSlash,
                                     final Header... requestHeaders)
        throws IOException {
  preRemoteCommand("listDeepObjectsInDirectory");

  String endpoint = getEndpointURI().toString();
  StringBuilder dataLocationURI = new StringBuilder();
  dataLocationURI.append(endpoint);
  String object = path.getObject();
  if (object.startsWith("/")) {
    object = object.substring(1);
  }
  if (addTrailingSlash && !object.endsWith("/")) {
    object = object.concat("/");
  }

  if (object.equals("/")) {
    object = "";
  }

  dataLocationURI = dataLocationURI.append("/")
          .append(path.getContainer())
          .append("/?prefix=")
          .append(object)
          .append("&format=json");

  //in listing deep set param to false
  if (listDeep == false) {
      dataLocationURI.append("&delimiter=/");
  }

  return findObjects(dataLocationURI.toString(), requestHeaders);
}
 
Example #20
Source File: UserController.java    From OfficeAutomatic-System with Apache License 2.0 5 votes vote down vote up
private void message(String phone,String hysbh,String time) throws IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://gbk.api.smschinese.cn");
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
    NameValuePair[] data = { new NameValuePair("Uid", "dddz97"),
            new NameValuePair("Key", "d41d8cd98f00b204e980"),
            new NameValuePair("smsMob", phone),
            new NameValuePair("smsText", "请于"+time+",到"+hysbh+"开会") };
    post.setRequestBody(data);

    client.executeMethod(post);
    Header[] headers = post.getResponseHeaders();
    int statusCode = post.getStatusCode();
    System.out.println("statusCode:" + statusCode);
    for (Header h : headers) {
        System.out.println(h.toString());
    }
    String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
    System.out.println(result); // 打印返回消息状态

    post.releaseConnection();
}
 
Example #21
Source File: SwiftNativeFileSystemStore.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Tell the Swift server to expect a multi-part upload by submitting
 * a 0-byte file with the X-Object-Manifest header
 *
 * @param path path of final final
 * @throws IOException
 */
public void createManifestForPartUpload(Path path) throws IOException {
  String pathString = toObjectPath(path).toString();
  if (!pathString.endsWith("/")) {
    pathString = pathString.concat("/");
  }
  if (pathString.startsWith("/")) {
    pathString = pathString.substring(1);
  }

  swiftRestClient.upload(toObjectPath(path),
          new ByteArrayInputStream(new byte[0]),
          0,
          new Header(SwiftProtocolConstants.X_OBJECT_MANIFEST, pathString));
}
 
Example #22
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Make an HTTP GET request to Swift to get a range of data in the object.
 *
 * @param path   path to object
 * @param offset offset from file beginning
 * @param length file length
 * @return The input stream -which must be closed afterwards.
 * @throws IOException Problems
 * @throws SwiftException swift specific error
 * @throws FileNotFoundException path is not there
 */
public HttpBodyContent getData(SwiftObjectPath path,
                               long offset,
                               long length) throws IOException {
  if (offset < 0) {
    throw new SwiftException("Invalid offset: " + offset
                          + " in getDataAsInputStream( path=" + path
                          + ", offset=" + offset
                          + ", length =" + length + ")");
  }
  if (length <= 0) {
    throw new SwiftException("Invalid length: " + length
              + " in getDataAsInputStream( path="+ path
                          + ", offset=" + offset
                          + ", length ="+ length + ")");
  }

  final String range = String.format(SWIFT_RANGE_HEADER_FORMAT_PATTERN,
          offset,
          offset + length - 1);
  if (LOG.isDebugEnabled()) {
    LOG.debug("getData:" + range);
  }

  return getData(path,
                 new Header(HEADER_RANGE, range),
                 SwiftRestClient.NEWEST);
}
 
Example #23
Source File: CarbonUIAuthenticationUtil.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the cookie information, i.e. whether remember me cookie is enabled of disabled. If enabled
 * we will send that information in a HTTP header.
 * @param cookie  The remember me cookie.
 * @param serviceClient The service client used in communication.
 */
public static void setCookieHeaders(Cookie cookie, ServiceClient serviceClient) {

    List<Header> headers = new ArrayList<Header>();
    Header rememberMeHeader = new Header("RememberMeCookieData", cookie.getValue());
    headers.add(rememberMeHeader);

    serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headers);
}
 
Example #24
Source File: Utility.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
/**
 * Set Auth headers to service client. Singed JWT authentication handler expect username
 * as a claim in order to validate the user. This is an alternative to mutual auth.
 *
 * @param serviceClient Service client.
 * @param username      username which is set in header.
 */

public static void setAuthHeaders(ServiceClient serviceClient, String username) {
    List headerList = new ArrayList();
    Header header = new Header();
    header.setName(HTTPConstants.HEADER_AUTHORIZATION);
    header.setValue(getAuthHeader(username));
    headerList.add(header);
    serviceClient.getOptions().setProperty(HTTPConstants.HTTP_HEADERS, headerList);
}
 
Example #25
Source File: CSP.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
public String getAccessTokenUserPass() {
    if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
        return this.oAuth2AccessToken;
    }

    if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
            || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
        return "";
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        // post development
        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));

        method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
        NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
                new NameValuePair("grant_type", oAuth2GrantType) };
        method.setRequestBody(body);
        int responseCode = client.executeMethod(method);

        String responseBody = method.getResponseBodyAsString();
        if (responseCode != 200) {
            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }

        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example #26
Source File: PutTest.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
private PutMethod getMethod(Resource resource, String path, String encoding) {
    PutMethod method = new PutMethod(this.csp.getUrl() + this.csp.getVersion() + path + resource.getId());

    ComplienceUtils.configureMethod(method);
    method.setRequestHeader(new Header("Accept", "application/" + encoding));
    if (resource.getMeta() != null && !resource.getMeta().getVersion().isEmpty()) {
        method.setRequestHeader(new Header("If-Match", resource.getMeta().getVersion()));
    }
    return method;
}
 
Example #27
Source File: RestMethod.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
    Header contentTypeHeader = getResponseHeader("Content-Type");
    if (contentTypeHeader != null && "application/json; charset=utf-8".equals(contentTypeHeader.getValue())) {
        try {
            if (DavGatewayHttpClientFacade.isGzipEncoded(this)) {
                processResponseStream(new GZIPInputStream(getResponseBodyAsStream()));
            } else {
                processResponseStream(getResponseBodyAsStream());
            }
        } catch (IOException | JSONException e) {
            LOGGER.error("Error while parsing json response: " + e, e);
        }
    }
}
 
Example #28
Source File: TestSwiftRestClient.java    From sahara-extra with Apache License 2.0 5 votes vote down vote up
@Test(timeout = SWIFT_TEST_TIMEOUT)
public void testPutAndDelete() throws Throwable {
  assumeEnabled();
  SwiftRestClient client = createClient();
  client.authenticate();
  Path path = new Path("restTestPutAndDelete");
  SwiftObjectPath sobject = SwiftObjectPath.fromPath(serviceURI, path);
  byte[] stuff = new byte[1];
  stuff[0] = 'a';
  client.upload(sobject, new ByteArrayInputStream(stuff), stuff.length);
  //check file exists
  Duration head = new Duration();
  Header[] responseHeaders = client.headRequest("expect success",
                                                sobject,
                                                SwiftRestClient.NEWEST);
  head.finished();
  LOG.info("head request duration " + head);
  for (Header header: responseHeaders) {
    LOG.info(header.toString());
  }
  //delete the file
  client.delete(sobject);
  //check file is gone
  try {
    Header[] headers = client.headRequest("expect fail",
                                          sobject,
                                          SwiftRestClient.NEWEST);
    Assert.fail("Expected deleted file, but object is still present: "
                + sobject);
  } catch (FileNotFoundException e) {
    //expected
  }
  for (DurationStats stats: client.getOperationStatistics()) {
    LOG.info(stats);
  }
}
 
Example #29
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example #30
Source File: BusinessJob.java    From http4e with Apache License 2.0 5 votes vote down vote up
private void addHeaders( HttpMethod httpMethod, Map<String, String> parameterizedMap){
   for (Iterator it = model.getHeaders().entrySet().iterator(); it.hasNext();) {
      Map.Entry me = (Map.Entry) it.next();
      String key = (String) me.getKey();
      List values = (List) me.getValue();
      StringBuilder sb = new StringBuilder();
      int cnt = 0;
      for (Iterator it2 = values.iterator(); it2.hasNext();) {
         String val = (String) it2.next();
         if (cnt != 0) {
            sb.append(",");
         }
         sb.append(val);
         cnt++;
      }

      String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
      httpMethod.addRequestHeader(key, parameterizedVal);
   }

   // add User-Agent: ProjectName
   boolean userAgentExist = false;
   Header[] hhh = httpMethod.getRequestHeaders();
   for (int i = 0; i < hhh.length; i++) {
      Header h = hhh[i];
      if (CoreConstants.HEADER_USER_AGENT.equalsIgnoreCase(h.getName())) {
         userAgentExist = true;
      }
   }

   if (!userAgentExist) {
      httpMethod.addRequestHeader(CoreConstants.HEADER_USER_AGENT, CoreMessages.PLUGIN_NAME_SHORT + "/" + CoreMessages.VERSION);
   }
}