Java Code Examples for org.apache.commons.httpclient.Header

The following examples show how to use org.apache.commons.httpclient.Header. These examples are extracted from open source projects. 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 Project: maven-framework-project   Source File: RestClient.java    License: 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 Project: development   Source File: TraceResponseHandler.java    License: 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 3
Source Project: micro-integrator   Source File: MicroIntegratorBaseUtils.java    License: 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 Project: OfficeAutomatic-System   Source File: UserController.java    License: Apache License 2.0 6 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 5
Source Project: boubei-tss   Source File: Filter5HttpProxy.java    License: 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 6
Source Project: diamond   Source File: DefaultDiamondSubscriber.java    License: 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 7
Source Project: cloudstack   Source File: BigSwitchApiTest.java    License: 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 8
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 9
Source Project: hadoop   Source File: SwiftRestClient.java    License: 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 10
Source Project: odo   Source File: HttpUtilities.java    License: 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 11
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 12
Source Project: maven-framework-project   Source File: RestClient.java    License: 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 13
Source Project: commons-vfs   Source File: HttpFileContentInfoFactory.java    License: 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 14
Source Project: http4e   Source File: HttpUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void dumpResponse( HttpMethod httpmethod, StringBuilder httpResponsePacket, StringBuilder respBody){
   try {
      httpResponsePacket.append('\n');
      httpResponsePacket.append(httpmethod.getStatusLine().toString());
      httpResponsePacket.append('\n');

      Header[] h = httpmethod.getResponseHeaders();
      for (int i = 0; i < h.length; i++) {
         httpResponsePacket.append(h[i].getName() + ": " + h[i].getValue());
         httpResponsePacket.append('\n');
      }

      InputStreamReader inR = new InputStreamReader(httpmethod.getResponseBodyAsStream());
      BufferedReader buf = new BufferedReader(inR);
      String line;
      while ((line = buf.readLine()) != null) {
         httpResponsePacket.append(line);
         httpResponsePacket.append('\n');
         respBody.append(line);
         respBody.append('\n');
      }
      httpResponsePacket.append('\n');

   } catch (Exception e) {
      throw new RuntimeException(e);
   }
}
 
Example 15
/** Chooses the strongest authentication scheme supported from the
 * array of authentication challenges. Currently only <code>NTLM</code>,
 * <code>Digest</code>, <code>Basic</code> schemes are recognized. 
 * The <code>NTLM</code> scheme is considered the strongest and is 
 * preferred to all others. The <code>Digest</code> scheme is preferred to 
 * the <code>Basic</code> one which provides no encryption for credentials.
 * The <code>Basic</code> scheme is used only if it is the only one 
 * supported.
 * 
 * @param challenges The array of authentication challenges
 * 
 * @return The strongest authentication scheme supported
 * 
 * @throws MalformedChallengeException is thrown if an authentication 
 *  challenge is malformed
 * @throws UnsupportedOperationException when none of challenge types
 *  available is supported.
 * 
 * @deprecated Use {@link AuthChallengeParser#parseChallenges(Header[])} and 
 *      {@link AuthPolicy#getAuthScheme(String)}
 */
public static AuthScheme selectAuthScheme(final Header[] challenges)
  throws MalformedChallengeException {
    LOG.trace("enter HttpAuthenticator.selectAuthScheme(Header[])");
    if (challenges == null) {
        throw new IllegalArgumentException("Array of challenges may not be null");
    }
    if (challenges.length == 0) {
        throw new IllegalArgumentException("Array of challenges may not be empty");
    }
    String challenge = null;
    Map challengemap = new HashMap(challenges.length); 
    for (int i = 0; i < challenges.length; i++) {
        challenge = challenges[i].getValue();
        String s = AuthChallengeParser.extractScheme(challenge);
        challengemap.put(s, challenge);
    }
    challenge = (String) challengemap.get("ntlm");
    if (challenge != null) {
        return new NTLMScheme(challenge);
    }
    challenge = (String) challengemap.get("digest");
    if (challenge != null) {
        return new DigestScheme(challenge);
    }
    challenge = (String) challengemap.get("basic");
    if (challenge != null) {
        return new BasicScheme(challenge);
    }
    throw new UnsupportedOperationException(
      "Authentication scheme(s) not supported: " + challengemap.toString()); 
}
 
Example 16
Source Project: sahara-extra   Source File: SwiftRestClient.java    License: 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 17
Source Project: webarchive-commons   Source File: ARC2WCDX.java    License: 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 18
Source Project: davmail   Source File: RestMethod.java    License: 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 19
public void setContentType(String contentType)
{
    for (Header hdr : headers)
    {
        if (HEADER_CONTENT_TYPE.equals( hdr.getName() ))
        {
            hdr.setValue(contentType);
            return;
        }
    }
    headers.add(new Header(HEADER_CONTENT_TYPE, contentType));
}
 
Example 20
@Test
public final void testARCGetHeaders() throws Exception {
	long length = 7109;
	long offset = 6865980;
	String name = "http://webcurator.sourceforge.net/contact.shtml";
	HarvestResourceDTO dto = new ArcHarvestResourceDTO(targetInstanceOid, harvestResultNumber, 54321, name, length, offset, 0,
			TestCARC, 200, true);

	Header[] headers = testInstance.getHeaders(new Long(targetInstanceOid).toString(), harvestResultNumber, dto);
	assertTrue(headers != null);
	assertTrue(headers.length == 4);
}
 
Example 21
Source Project: difido-reports   Source File: DifidoClient.java    License: Apache License 2.0 5 votes vote down vote up
public int addMachine(int executionId, MachineNode machine) throws Exception {
	PostMethod method = new PostMethod(baseUri + "executions/" + executionId + "/machines/");
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	final ObjectMapper mapper = new ObjectMapper();
	final String json = mapper.writeValueAsString(machine);
	final RequestEntity entity = new StringRequestEntity(json,"application/json","UTF-8");
	method.setRequestEntity(entity);
	int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
	return Integer.parseInt(method.getResponseBodyAsString());
}
 
Example 22
Source Project: difido-reports   Source File: DifidoClient.java    License: Apache License 2.0 5 votes vote down vote up
public int addExecution(ExecutionDetails details) throws Exception {
	final PostMethod method = new PostMethod(baseUri + "executions/");
	method.setRequestHeader(new Header("Content-Type", "application/json"));
	if (details != null) {
		final String descriptionJson = new ObjectMapper().writeValueAsString(details);
		method.setRequestEntity(new StringRequestEntity(descriptionJson,"application/json","UTF-8"));
	}
	final int responseCode = client.executeMethod(method);
	handleResponseCode(method, responseCode);
	return Integer.parseInt(method.getResponseBodyAsString());
}
 
Example 23
private void postResponse(HttpMethod httpMethod) {
	if (!httpMethod.isRequestSent()) return;
	final Header[] responseHeaders = httpMethod.getResponseHeaders(TraceeConstants.TPIC_HEADER);
	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (responseHeaders != null && responseHeaders.length > 0 && filterConfiguration.shouldProcessContext(IncomingResponse)) {
		final List<String> stringTraceeHeaders = new ArrayList<>();
		for (Header header : responseHeaders) {
			stringTraceeHeaders.add(header.getValue());
		}

		backend.putAll(filterConfiguration.filterDeniedParams(transportSerialization.parse(stringTraceeHeaders), IncomingResponse));
	}
}
 
Example 24
public long getLastModified() throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader("Last-Modified");

  if (head != null) {
    try {
      return DateUtil.parseDate(head.getValue()).getTime();
    } catch (DateParseException e) {
      return 0;
    }
  }

  return 0;
}
 
Example 25
/**
 * Send Request to the repository
 */
protected HttpMethod sendRemoteRequest(Request req) throws AuthenticationException, IOException
{
    if (logger.isDebugEnabled())
    {
        logger.debug("");
        logger.debug("* Request: " + req.getMethod() + " " + req.getFullUri() + (req.getBody() == null ? "" : "\n" + new String(req.getBody(), "UTF-8")));
    }

    HttpMethod method = createMethod(req);

    // execute method
    executeMethod(method);

    // Deal with redirect
    if(isRedirect(method))
    {
        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null)
        {
            String redirectLocation = locationHeader.getValue();
            method.setURI(new URI(redirectLocation, true));
            httpClient.executeMethod(method);
        }
    }

    return method;
}
 
Example 26
Source Project: carbon-device-mgt   Source File: ExternalOAuthValidator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO
 * containing the validity and user details if valid.
 *
 * @param token which need to be validated.
 * @return OAuthValidationResponse with the validated results.
 */
public OAuthValidationResponse validateToken(String token) throws RemoteException {
    OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken =
            new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
    accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE);
    accessToken.setIdentifier(token);
    validationRequest.setAccessToken(accessToken);
    OAuth2TokenValidationServiceStub tokenValidationService =
            new OAuth2TokenValidationServiceStub(hostURL);
    ServiceClient client = tokenValidationService._getServiceClient();
    Options options = client.getOptions();
    List<Header> headerList = new ArrayList<>();
    Header header = new Header();
    header.setName(HTTPConstants.HEADER_AUTHORIZATION);
    header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials());
    headerList.add(header);
    options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
    client.setOptions(options);
    OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService.
            findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
    boolean isValid = tokenValidationResponse.getValid();
    String userName = null;
    String tenantDomain = null;
    if (isValid) {
        userName = MultitenantUtils.getTenantAwareUsername(
                tokenValidationResponse.getAuthorizedUser());
        tenantDomain = MultitenantUtils.
                getTenantDomain(tokenValidationResponse.getAuthorizedUser());
    }
    return new OAuthValidationResponse(userName,tenantDomain,isValid);
}
 
Example 27
/**
 * Get the timestamp on the HTTP response
 * 
 * @param method HttpMethod
 * @return timestamp (ms, in UNIX time)
 * @throws IOException
 */
protected Long getResponseTimestamp(HttpMethod method) throws IOException
{
    Header header = method.getResponseHeader(HEADER_TIMESTAMP);
    if(header != null)
    {
        return Long.valueOf(header.getValue());
    }
    else
    {
        return null;
    }
}
 
Example 28
Source Project: sahara-extra   Source File: TestSwiftRestClient.java    License: 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 Project: hadoop   Source File: SwiftRestClient.java    License: 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 30
Source Project: httpclientAuthHelper   Source File: AuthUtils.java    License: 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;
}