package com.genesys.wsclient.impl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.client.security.BasicAuthentication;
import org.eclipse.jetty.client.security.Realm;
import org.eclipse.jetty.io.ByteArrayBuffer;
import com.genesys.wsclient.HttpRequest;
public class Jetty769HttpRequest implements HttpRequest {
private final HttpExchange exchange;
public Jetty769HttpRequest(HttpExchange exchange) {
this.exchange = exchange;
}
public HttpExchange getHttpExchange() {
return exchange;
}
@Override
public void setMethod(String method) {
exchange.setMethod(method);
}
@Override
public void setUri(String uri) {
exchange.setURL(uri);
}
@Override
public void setHeader(String name, String value) {
exchange.addRequestHeader(name, value);
}
@Override
public void setContentType(String contentType) {
exchange.setRequestContentType(contentType);
}
@Override
public void setContent(String content, String encoding) {
try {
exchange.setRequestContent(new ByteArrayBuffer(content, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
public void setBasicAuthorization(final String username, final String password) {
try {
BasicAuthentication auth = new BasicAuthentication(new Realm() {
@Override public String getPrincipal() { return username; }
@Override public String getId() { return null; }
@Override public String getCredentials() { return password; }
});
// The Jetty Client uses the ISO-8859-1 char-set for Basic Authentication,
// the same as the Jetty Server. See
// https://github.com/eclipse/jetty.project/blob/master/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/BasicAuthenticator.java
auth.setCredentials(exchange);
} catch (IOException e) {
// This happens only in the highly unlikely case that ISO-8859-1 would not be supported.
// (BasicAuthentication should throw a RuntimeException in this case, instead of propagating a checked exception).
// BasicAuthentication.setCredentials doesn't actually throw an IOException.
throw new RuntimeException(e);
}
}
@Override
public void setTimeout(int timeout) {
exchange.setTimeout(timeout);
}
}