Example usage for org.apache.http.client.methods HttpUriRequest getURI

List of usage examples for org.apache.http.client.methods HttpUriRequest getURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getURI.

Prototype

URI getURI();

Source Link

Document

Returns the URI this request uses, such as <code>http://example.org/path/to/file</code>.

Usage

From source file:org.apache.http.impl.client.StatiscicsLoggingRequestDirector.java

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 *//*from   w w  w.j  a v  a  2 s  . c  o m*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    HttpRoute route = roureq.getRoute();
    RequestWrapper request = roureq.getRequest();

    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params)
            && this.redirectStrategy.isRedirected(request, response, context)) {

        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;

        // Virtual host cannot be used any longer
        virtualHost = null;

        HttpUriRequest redirect = redirectStrategy.getRedirect(request, response, context);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        URI uri = redirect.getURI();
        if (uri.getHost() == null) {
            throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
        }

        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);

        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }

        RequestWrapper wrapper = wrapRequest(redirect);
        wrapper.setParams(params);

        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);

        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }

        return newRequest;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);

    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {

        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }

            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);

            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }

        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {

            HttpHost proxy = route.getProxyHost();

            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);

            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}

From source file:org.apache.http.impl.nio.client.AbstractHttpAsyncClient.java

private HttpHost determineTarget(final HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;//from   w  w w.j a v a  2s.  com

    final URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = URIUtils.extractHost(requestURI);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI);
        }
    }
    return target;
}

From source file:org.apache.http.impl.nio.client.DefaultAsyncRequestDirector.java

private RoutedRequest handleRedirect() throws HttpException {
    if (this.redirectStrategy.isRedirected(this.currentRequest, this.currentResponse, this.localContext)) {

        final HttpRoute route = this.mainRequest.getRoute();
        final RequestWrapper request = this.mainRequest.getRequest();

        final int maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
        if (this.redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }//from  w  w w . ja v a 2 s  .c o  m
        this.redirectCount++;

        final HttpUriRequest redirect = this.redirectStrategy.getRedirect(this.currentRequest,
                this.currentResponse, this.localContext);
        final HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());

        final URI uri = redirect.getURI();
        if (uri.getHost() == null) {
            throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
        }
        final HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        // Reset auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + this.id + "] Resetting target auth state");
            }
            this.targetAuthState.reset();
            final AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + this.id + "] Resetting proxy auth state");
                }
                this.proxyAuthState.reset();
            }
        }

        final RequestWrapper newRequest = wrapRequest(redirect);
        newRequest.setParams(this.params);

        final HttpRoute newRoute = determineRoute(newTarget, newRequest, this.localContext);

        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + this.id + "] Redirecting to '" + uri + "' via " + newRoute);
        }
        return new RoutedRequest(newRequest, newRoute);
    }
    return null;
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

@Override
public void responseCompleted(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpResponse currentResponse = handler.getCurrentResponse();

    if (!handler.isRouteEstablished()) {
        final int status = currentResponse.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_OK) {
            handler.setCurrentResponse(null);
            return;
        }/*from  w  w w .j av  a  2  s. c o  m*/
    }

    final boolean keepAlive = handler.manageConnectionPersistence();
    if (!keepAlive) {
        handler.releaseConnection();
        final AuthState proxyAuthState = localContext.getProxyAuthState();
        if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null
                && proxyAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
            }
            proxyAuthState.reset();
        }
        final AuthState targetAuthState = localContext.getTargetAuthState();
        if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null
                && targetAuthState.getAuthScheme().isConnectionBased()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
            }
            targetAuthState.reset();
        }
    }

    Object userToken = localContext.getUserToken();
    if (userToken == null) {
        userToken = this.userTokenHandler.getUserToken(localContext);
        localContext.setAttribute(HttpClientContext.USER_TOKEN, userToken);
    }

    if (state.getFinalResponse() != null) {
        final HttpAsyncResponseConsumer<?> responseConsumer = state.getResponseConsumer();
        responseConsumer.responseCompleted(localContext);
        if (this.log.isDebugEnabled()) {
            this.log.debug("[exchange: " + state.getId() + "] Response processed");
        }
        handler.releaseConnection();
    } else {
        if (state.getRedirect() != null) {
            final HttpUriRequest redirect = state.getRedirect();
            final URI uri = redirect.getURI();
            if (this.log.isDebugEnabled()) {
                this.log.debug("[exchange: " + state.getId() + "] Redirecting to '" + uri + "'");
            }
            state.setRedirect(null);

            final HttpHost newTarget = URIUtils.extractHost(uri);
            if (newTarget == null) {
                throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
            }

            // Reset auth states if redirecting to another host
            final HttpRoute route = handler.getRoute();
            if (!route.getTargetHost().equals(newTarget)) {
                final AuthState targetAuthState = localContext.getTargetAuthState();
                if (this.log.isDebugEnabled()) {
                    this.log.debug("[exchange: " + state.getId() + "] Resetting target auth state");
                }
                targetAuthState.reset();
                final AuthState proxyAuthState = localContext.getProxyAuthState();
                final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                if (authScheme != null && authScheme.isConnectionBased()) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("[exchange: " + state.getId() + "] Resetting proxy auth state");
                    }
                    proxyAuthState.reset();
                }
            }

            if (!redirect.headerIterator().hasNext()) {
                final HttpRequest original = state.getMainRequest().getOriginal();
                redirect.setHeaders(original.getAllHeaders());
            }

            final HttpRequestWrapper newRequest = HttpRequestWrapper.wrap(redirect);
            final HttpRoute newRoute = this.routePlanner.determineRoute(newTarget, newRequest, localContext);
            if (!route.equals(newRoute)) {
                handler.releaseConnection();
            }
            handler.setRoute(newRoute);
            handler.setCurrentRequest(newRequest);
            state.setMainRequest(newRequest);
            prepareRequest(state, handler);
        }
    }
    handler.setCurrentResponse(null);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }//from   w ww .  ja  v  a2  s .co m

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test
public void testListVMMakesTheCorrectNumberOfAPICalls() throws CloudException, InternalException {

    ArrayList<HostedServiceModel> hostedServiceModelList = new ArrayList<HostedServiceModel>();
    for (Integer i = 1; i < 20; i++) {
        final HostedServiceModel hostedServiceModel = new HostedServiceModel();
        hostedServiceModel.setServiceName(String.format("HOSTED_SERVICE_%s", i.toString()));
        hostedServiceModel.setUrl("TEST_SERVICE_URL");
        hostedServiceModelList.add(hostedServiceModel);
    }/*from ww  w.java 2 s  . co  m*/
    HostedServicesModel hostedServicesModel = new HostedServicesModel();
    hostedServicesModel.setHostedServiceModelList(hostedServiceModelList);
    final DaseinObjectToXmlEntity<HostedServicesModel> responseEntity = new DaseinObjectToXmlEntity<HostedServicesModel>(
            hostedServicesModel);

    final CloseableHttpResponse getHttpResponseHostedServicesEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), responseEntity, new Header[] {});
    final CloseableHttpResponse getHttpResponseEmptyEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), null, new Header[] {});

    final String expectedUrl = String.format(HOSTED_SERVICES_URL, ENDPOINT, ACCOUNT_NO);
    final ArrayList<String> actualAPICallUrls = new ArrayList<String>();
    new MockUp<CloseableHttpClient>() {
        @Mock
        public CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
            if (request.getURI().toString().endsWith("hostedservices")) {
                assertGet(request, expectedUrl, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseHostedServicesEntityMock;
            } else if (request.getURI().toString().endsWith("embed-detail=true")) {
                Assert.assertNotNull(
                        CollectionUtils.find(Arrays.asList(request.getAllHeaders()), new Predicate() {
                            @Override
                            public boolean evaluate(Object object) {
                                Header actualHeader = (Header) object;
                                return actualHeader.getName() == "x-ms-version"
                                        && actualHeader.getValue() == "2014-05-01";
                            }
                        }));
                actualAPICallUrls.add(request.getURI().toString());
                return getHttpResponseEmptyEntityMock;
            } else {
                Assert.fail("listVirtualMachine method makes an unexpected API call");
                return null;
            }
        }
    };

    AzureVM azureVM = new AzureVM(azureMock);
    Iterable<VirtualMachine> virtualMachines = azureVM.listVirtualMachines();

    Assert.assertNotNull(virtualMachines);
    assertEquals(hostedServicesModel.getHostedServiceModelList().size(), actualAPICallUrls.size());
    for (HostedServiceModel hostedServiceModel : hostedServicesModel.getHostedServiceModelList()) {
        String expectedUrlCall = String.format(HOSTED_SERVICES_SERVICE_EMBEDED_DETAILS_URL, ENDPOINT,
                ACCOUNT_NO, hostedServiceModel.getServiceName());
        assertTrue(actualAPICallUrls.contains(expectedUrlCall));
    }
    assertEquals(0, IteratorUtils.toList(virtualMachines.iterator()).size());
}

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test
public void testListVirtualMachineReturnsCorrectMachine(@Mocked final AzureOSImage imageSupportMock,
        @Mocked final AzureNetworkServices networkServicesMock, @Mocked final AzureVlanSupport vlanSupportMock,
        @Mocked final VLAN vlanMock) throws CloudException, InternalException, URISyntaxException {
    String affinityGroupId = "TEST_AFFINITY_ID";
    final HostedServiceModel hostedServiceModel = getHostedServiceModel(affinityGroupId);
    hostedServiceModel.setUrl("TEST_SERVICE_URL");
    hostedServiceModel.setServiceName(DEPLOYMENT_NAME);
    HostedServicesModel hostedServicesModel = new HostedServicesModel();
    hostedServicesModel.setHostedServiceModelList(new ArrayList<HostedServiceModel>() {
        {/*from w w  w  .  j  ava2s  . c  o  m*/
            add(hostedServiceModel);
        }
    });
    final DaseinObjectToXmlEntity<HostedServicesModel> hostedServicesResponseEntity = new DaseinObjectToXmlEntity<HostedServicesModel>(
            hostedServicesModel);
    final DaseinObjectToXmlEntity<HostedServicesModel> hostedServiceResponseEntity = new DaseinObjectToXmlEntity<HostedServicesModel>(
            hostedServicesModel);

    final CloseableHttpResponse getHttpResponseHostedServicesEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), hostedServicesResponseEntity, new Header[] {});
    final CloseableHttpResponse getHttpResponseHostedServiceEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), hostedServiceResponseEntity, new Header[] {});

    final MachineImage testMachineImage = MachineImage.getInstance(ACCOUNT_NO, REGION, "DISK_SOURCE_IMAGE_NAME",
            ImageClass.MACHINE, MachineImageState.ACTIVE, "DISK_SOURCE_IMAGE_NAME", "DISK_SOURCE_IMAGE_NAME",
            Architecture.I64, Platform.WINDOWS);
    final DataCenter testDataCenter = new DataCenter(REGION, REGION_NAME, REGION, true, true);
    final AffinityGroup testAffinityGroup = AffinityGroup.getInstance(affinityGroupId, "AG_NAME",
            "AG_DESCRIPTION", REGION, null);
    new NonStrictExpectations() {
        {
            azureMock.getComputeServices();
            result = computeServiceMock;
        }

        {
            computeServiceMock.getAffinityGroupSupport();
            result = affinitySupportMock;
        }

        {
            computeServiceMock.getImageSupport();
            result = imageSupportMock;
        }

        {
            azureMock.getNetworkServices();
            result = networkServicesMock;
        }

        {
            networkServicesMock.getVlanSupport();
            result = vlanSupportMock;
        }

        {
            vlanSupportMock.getVlan("VLAN_NAME");
            result = vlanMock;
        }

        {
            vlanMock.getProviderVlanId();
            result = "PROVIDER_VLAN_ID";
        }

        {
            imageSupportMock.getMachineImage("DISK_SOURCE_IMAGE_NAME");
            result = testMachineImage;
        }

        {
            affinitySupportMock.get(anyString);
            result = testAffinityGroup;
        }

        {
            azureMock.getDataCenterServices();
            result = dataCenterServiceMock;
        }

        {
            dataCenterServiceMock.getDataCenter(anyString);
            result = testDataCenter;
        }
    };

    new MockUp<CloseableHttpClient>() {
        @Mock
        public CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
            if (request.getURI().toString().endsWith("hostedservices")) {
                return getHttpResponseHostedServicesEntityMock;
            } else if (request.getURI().toString().endsWith("embed-detail=true")) {
                return getHttpResponseHostedServiceEntityMock;
            } else {
                Assert.fail("listVirtualMachine method makes an unexpected API call");
                return null;
            }
        }
    };

    AzureVM azureVM = new AzureVM(azureMock);
    Iterable<VirtualMachine> virtualMachines = azureVM.listVirtualMachines();
    Assert.assertNotNull(virtualMachines);
    Assert.assertEquals(1, IteratorUtils.toList(virtualMachines.iterator()).size());
    assertVirtualMachine(hostedServiceModel, testMachineImage,
            (VirtualMachine) IteratorUtils.toList(virtualMachines.iterator()).get(0), DEPLOYMENT_NAME,
            DEPLOYMENT_NAME, DEPLOYMENT_NAME);
}

From source file:org.flowable.admin.service.engine.FlowableClientService.java

/**
 * Execute the given request. Will return the parsed JSON present in the
 * response-body, in case the status code is as expected. In case the response
 * returns a different status-code, an {@link FlowableServiceException} is
 * thrown with the error message received from the client, if possible.
 *///from   w w w.java 2  s. c  o  m
public JsonNode executeRequest(HttpUriRequest request, String userName, String password,
        int expectedStatusCode) {

    FlowableServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {
        CloseableHttpResponse response = client.execute(request);

        try {
            InputStream responseContent = response.getEntity().getContent();
            String strResponse = IOUtils.toString(responseContent);

            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;
            if (success) {
                JsonNode bodyNode = objectMapper.readTree(strResponse);
                return bodyNode;

            } else {
                JsonNode bodyNode = null;
                try {
                    bodyNode = objectMapper.readTree(strResponse);
                } catch (Exception e) {
                    log.debug("Error parsing error message", e);
                }
                exception = new FlowableServiceException(extractError(bodyNode,
                        "An error occurred while calling Flowable: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:org.flowable.admin.service.engine.FlowableClientService.java

public JsonNode executeDownloadRequest(HttpUriRequest request, HttpServletResponse httpResponse,
        String userName, String password, int expectedStatusCode) {

    FlowableServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {//from w  ww  . j a  v  a  2 s.c o m
        CloseableHttpResponse response = client.execute(request);
        try {
            boolean success = response.getStatusLine() != null
                    && response.getStatusLine().getStatusCode() == expectedStatusCode;
            if (success) {
                httpResponse.setHeader("Content-Disposition",
                        response.getHeaders("Content-Disposition")[0].getValue());
                response.getEntity().writeTo(httpResponse.getOutputStream());
                return null;

            } else {
                JsonNode bodyNode = null;
                String strResponse = IOUtils.toString(response.getEntity().getContent());
                try {
                    bodyNode = objectMapper.readTree(strResponse);
                } catch (Exception e) {
                    log.debug("Error parsing error message", e);
                }
                exception = new FlowableServiceException(extractError(bodyNode,
                        "An error occurred while calling Flowable: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}

From source file:org.flowable.admin.service.engine.FlowableClientService.java

public AttachmentResponseInfo executeDownloadRequest(HttpUriRequest request, String userName, String password,
        Integer... expectedStatusCodes) {
    FlowableServiceException exception = null;
    CloseableHttpClient client = getHttpClient(userName, password);
    try {/*from   ww  w . j  a  v  a 2 s  .c o m*/
        CloseableHttpResponse response = client.execute(request);

        try {
            int statusCode = -1;
            if (response.getStatusLine() != null) {
                statusCode = response.getStatusLine().getStatusCode();
            }
            boolean success = Arrays.asList(expectedStatusCodes).contains(statusCode);
            if (success) {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String contentDispositionFileName[] = response.getHeaders("Content-Disposition")[0]
                            .getValue().split("=");
                    String fileName = contentDispositionFileName[contentDispositionFileName.length - 1];
                    return new AttachmentResponseInfo(fileName,
                            IOUtils.toByteArray(response.getEntity().getContent()));
                } else {
                    return new AttachmentResponseInfo(statusCode,
                            readJsonContent(response.getEntity().getContent()));
                }

            } else {
                exception = new FlowableServiceException(
                        extractError(readJsonContent(response.getEntity().getContent()),
                                "An error occurred while calling Flowable: " + response.getStatusLine()));
            }
        } catch (Exception e) {
            log.warn("Error consuming response from uri " + request.getURI(), e);
            exception = wrapException(e, request);
        } finally {
            response.close();
        }

    } catch (Exception e) {
        log.error("Error executing request to uri " + request.getURI(), e);
        exception = wrapException(e, request);
    } finally {
        try {
            client.close();
        } catch (Exception e) {
            log.warn("Error closing http client instance", e);
        }
    }

    if (exception != null) {
        throw exception;
    }

    return null;
}