Search in sources :

Example 6 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project tdi-studio-se by Talend.

the class MDMTransaction method commit.

public void commit() throws IOException {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    HttpMethod method = new PostMethod(url + "/" + id);
    method.setDoAuthentication(true);
    try {
        //$NON-NLS-1$ //$NON-NLS-2$
        method.setRequestHeader("Cookie", getStickySession() + "=" + sessionId);
        client.executeMethod(method);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
    int statuscode = method.getStatusCode();
    if (statuscode >= 400) {
        throw new MDMTransactionException("Commit failed. The commit operation has returned the code " + statuscode + ".");
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 7 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project tdi-studio-se by Talend.

the class WSDLLocatorImpl method createHttpClient.

private HttpClient createHttpClient() {
    HttpClient httpClient = new HttpClient();
    if (configuration.getProxyServer() != null) {
        HostConfiguration hostConfiguration = new HostConfiguration();
        hostConfiguration.setProxy(configuration.getProxyServer(), configuration.getProxyPort());
        httpClient.setHostConfiguration(hostConfiguration);
    }
    if (configuration.getUsername() != null) {
        Credentials credentials = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword());
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    if (configuration.getProxyUsername() != null) {
        Credentials credentials = new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword());
        httpClient.getState().setProxyCredentials(AuthScope.ANY, credentials);
        httpClient.getHostConfiguration().setProxy(configuration.getProxyServer(), configuration.getProxyPort());
    }
    return httpClient;
}
Also used : HostConfiguration(org.apache.commons.httpclient.HostConfiguration) HttpClient(org.apache.commons.httpclient.HttpClient) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 8 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project zm-mailbox by Zimbra.

the class SoapHttpTransport method invoke.

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId, String changeToken, String tokenType, ResponseHandler respHandler) throws IOException, HttpException, ServiceException {
    PostMethod method = null;
    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);
        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }
        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken, tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();
        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));
        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);
        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet()) method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");
        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }
        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }
        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);
        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(), SoapProtocol.getCharset());
        String responseStr = "";
        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);
                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamReader(java.io.InputStreamReader) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) AuthScope(org.apache.commons.httpclient.auth.AuthScope) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project zm-mailbox by Zimbra.

the class ProxyServlet method doProxy.

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }
    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);
    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));
    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }
        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }
        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode();
        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue();
        InputStream targetResponseBody = method.getResponseBodyAsStream();
        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()).getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";
            List<Upload> uploads = null;
            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }
            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName()))
                resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}
Also used : ContentType(com.zimbra.common.mime.ContentType) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) URL(java.net.URL) HttpException(org.apache.commons.httpclient.HttpException) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthToken(com.zimbra.cs.account.AuthToken) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 10 with UsernamePasswordCredentials

use of org.apache.commons.httpclient.UsernamePasswordCredentials in project zm-mailbox by Zimbra.

the class TestProvIDN method testBasicAuth.

@Test
public void testBasicAuth() throws Exception {
    Names.IDNName domainName = new Names.IDNName(makeTestDomainName("basicAuthTest."));
    Domain domain = createDomain(domainName.uName(), domainName.uName());
    Names.IDNName acctName = new Names.IDNName("acct", domainName.uName());
    Account acct = (Account) createTest(EntryType.ACCOUNT, NameType.UNAME, acctName);
    HttpState initialState = new HttpState();
    /*
        Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false);
        Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false);
        initialState.addCookie(authCookie);
        initialState.addCookie(sessionCookie);
        */
    String guestName = acct.getUnicodeName();
    String guestPassword = "test123";
    Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
    initialState.setCredentials(AuthScope.ANY, loginCredentials);
    HttpClient client = new HttpClient();
    client.setState(initialState);
    String url = UserServlet.getRestUrl(acct) + "/Calendar";
    System.out.println("REST URL: " + url);
    HttpMethod method = new GetMethod(url);
    HttpMethodParams methodParams = method.getParams();
    methodParams.setCredentialCharset("UTF-8");
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        if (respCode != HttpStatus.SC_OK) {
            System.out.println("failed, respCode=" + respCode);
        } else {
            boolean chunked = false;
            boolean textContent = false;
        /*
                 System.out.println("Headers:");
                 System.out.println("--------");
                 for (Header header : method.getRequestHeaders()) {
                     System.out.print("    " + header.toString());
                 }
                 System.out.println();
                 
                 System.out.println("Body:");
                 System.out.println("-----");
                 String respBody = method.getResponseBodyAsString();
                 System.out.println(respBody);
                 */
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}
Also used : Account(com.zimbra.cs.account.Account) HttpState(org.apache.commons.httpclient.HttpState) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Names(com.zimbra.qa.unittest.prov.Names) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Domain(com.zimbra.cs.account.Domain) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)113 Credentials (org.apache.commons.httpclient.Credentials)97 ArrayList (java.util.ArrayList)65 NameValuePair (org.apache.commons.httpclient.NameValuePair)61 JsonObject (javax.json.JsonObject)52 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)51 Test (org.junit.Test)51 JsonArray (javax.json.JsonArray)19 HttpClient (org.apache.commons.httpclient.HttpClient)19 AuthScope (org.apache.commons.httpclient.auth.AuthScope)17 HashSet (java.util.HashSet)14 GetMethod (org.apache.commons.httpclient.methods.GetMethod)14 HttpException (org.apache.commons.httpclient.HttpException)9 IOException (java.io.IOException)8 HttpMethod (org.apache.commons.httpclient.HttpMethod)8 HttpState (org.apache.commons.httpclient.HttpState)6 PostMethod (org.apache.commons.httpclient.methods.PostMethod)6 URL (java.net.URL)5 RepositoryException (org.apache.sling.ide.transport.RepositoryException)5 Header (org.apache.commons.httpclient.Header)4