Search in sources :

Example 31 with Executor

use of org.apache.http.client.fluent.Executor in project hale by halestudio.

the class AbstractWFSWriter method execute.

@Override
public IOReport execute(ProgressIndicator progress) throws IOProviderConfigurationException, IOException {
    progress.begin("WFS Transaction", ProgressIndicator.UNKNOWN);
    // configure internal provider
    internalProvider.setDocumentWrapper(createTransaction());
    final PipedInputStream pIn = new PipedInputStream();
    PipedOutputStream pOut = new PipedOutputStream(pIn);
    currentExecuteStream = pOut;
    Future<Response> futureResponse = null;
    IOReporter reporter = createReporter();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        // read the stream (in another thread)
        futureResponse = executor.submit(new Callable<Response>() {

            @Override
            public Response call() throws Exception {
                Proxy proxy = ProxyUtil.findProxy(targetWfs.getLocation());
                Request request = Request.Post(targetWfs.getLocation()).bodyStream(pIn, ContentType.APPLICATION_XML);
                Executor executor = FluentProxyUtil.setProxy(request, proxy);
                // authentication
                String user = getParameter(PARAM_USER).as(String.class);
                String password = getParameter(PARAM_PASSWORD).as(String.class);
                if (user != null) {
                    // target host
                    int port = targetWfs.getLocation().getPort();
                    String hostName = targetWfs.getLocation().getHost();
                    String scheme = targetWfs.getLocation().getScheme();
                    HttpHost host = new HttpHost(hostName, port, scheme);
                    // add credentials
                    Credentials cred = ClientProxyUtil.createCredentials(user, password);
                    executor.auth(new AuthScope(host), cred);
                    executor.authPreemptive(host);
                }
                try {
                    return executor.execute(request);
                } finally {
                    pIn.close();
                }
            }
        });
        // write the stream
        SubtaskProgressIndicator subprogress = new SubtaskProgressIndicator(progress);
        reporter = (IOReporter) super.execute(subprogress);
    } finally {
        executor.shutdown();
    }
    try {
        Response response = futureResponse.get();
        HttpResponse res = response.returnResponse();
        int statusCode = res.getStatusLine().getStatusCode();
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        if (statusCode >= 200 && statusCode < 300) {
            // success
            reporter.setSuccess(reporter.isSuccess());
            // construct summary from response
            try {
                Document responseDoc = parseResponse(res.getEntity());
                // totalInserted
                String inserted = xpath.compile("//TransactionSummary/totalInserted").evaluate(responseDoc);
                // XXX totalUpdated
                // XXX totalReplaced
                // XXX totalDeleted
                reporter.setSummary("Inserted " + inserted + " features.");
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl(MessageFormat.format("Server returned status code {0}, but could not parse server response", statusCode), e));
                reporter.setSuccess(false);
            }
        } else {
            // failure
            reporter.error(new IOMessageImpl("Server reported failure with code " + res.getStatusLine().getStatusCode() + ": " + res.getStatusLine().getReasonPhrase(), null));
            reporter.setSuccess(false);
            try {
                Document responseDoc = parseResponse(res.getEntity());
                String errorText = xpath.compile("//ExceptionText/text()").evaluate(responseDoc);
                reporter.setSummary("Request failed: " + errorText);
            } catch (XPathExpressionException e) {
                log.error("Error in XPath used to evaluate service response");
            } catch (ParserConfigurationException | SAXException e) {
                reporter.error(new IOMessageImpl("Could not parse server response", e));
                reporter.setSuccess(false);
            }
        }
    } catch (ExecutionException | InterruptedException e) {
        reporter.error(new IOMessageImpl("Failed to execute WFS-T request", e));
        reporter.setSuccess(false);
    }
    progress.end();
    return reporter;
}
Also used : XPathExpressionException(javax.xml.xpath.XPathExpressionException) IOMessageImpl(eu.esdihumboldt.hale.common.core.io.report.impl.IOMessageImpl) PipedOutputStream(java.io.PipedOutputStream) Document(org.w3c.dom.Document) Callable(java.util.concurrent.Callable) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) IOReporter(eu.esdihumboldt.hale.common.core.io.report.IOReporter) Proxy(java.net.Proxy) Executor(org.apache.http.client.fluent.Executor) HttpHost(org.apache.http.HttpHost) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ExecutionException(java.util.concurrent.ExecutionException) XPath(javax.xml.xpath.XPath) Request(org.apache.http.client.fluent.Request) HttpResponse(org.apache.http.HttpResponse) SubtaskProgressIndicator(eu.esdihumboldt.hale.common.core.io.impl.SubtaskProgressIndicator) PipedInputStream(java.io.PipedInputStream) HttpResponse(org.apache.http.HttpResponse) Response(org.apache.http.client.fluent.Response) ExecutorService(java.util.concurrent.ExecutorService) AuthScope(org.apache.http.auth.AuthScope) UserPasswordCredentials(eu.esdihumboldt.hale.common.core.io.config.UserPasswordCredentials) Credentials(org.apache.http.auth.Credentials)

Example 32 with Executor

use of org.apache.http.client.fluent.Executor in project gogs-webhook-plugin by jenkinsci.

the class GogsConfigHandler method createWebHook.

/**
 * Creates a web hook in Gogs with the passed json configuration string
 *
 * @param jsonCommand A json buffer with the creation command of the web hook
 * @param projectName the project (owned by the user) where the webHook should be created
 * @throws IOException something went wrong
 */
int createWebHook(String jsonCommand, String projectName) throws IOException {
    String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks";
    Executor executor = getExecutor();
    String result = executor.execute(Request.Post(gogsHooksConfigUrl).bodyString(jsonCommand, ContentType.APPLICATION_JSON)).returnContent().asString();
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(result);
    int id = jsonObject.getInt("id");
    return id;
}
Also used : Executor(org.apache.http.client.fluent.Executor) JSONObject(net.sf.json.JSONObject)

Example 33 with Executor

use of org.apache.http.client.fluent.Executor in project substitution-schedule-parser by vertretungsplanme.

the class LoginHandlerTest method testPostAuthFormData.

@Test
public void testPostAuthFormData() throws JSONException, IOException, CredentialInvalidException {
    stubPostAuthFormData();
    Executor exec = newExecutor();
    LoginHandler handler = new LoginHandler(dataPostFormData, correct, null);
    handler.handleLogin(exec, null);
    // loading page should succeed
    String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString();
    assertEquals("content", content);
}
Also used : Executor(org.apache.http.client.fluent.Executor) Test(org.junit.Test)

Example 34 with Executor

use of org.apache.http.client.fluent.Executor in project substitution-schedule-parser by vertretungsplanme.

the class LoginHandlerTest method testBasicAuth.

@Test
public void testBasicAuth() throws JSONException, IOException, CredentialInvalidException {
    stubBasicAuth();
    Executor exec = newExecutor();
    LoginHandler handler = new LoginHandler(dataBasic, correct, null);
    handler.handleLogin(exec, null);
    // loading page should succeed
    int status = exec.execute(Request.Get(baseurl + "/index.html")).returnResponse().getStatusLine().getStatusCode();
    assertEquals(200, status);
}
Also used : Executor(org.apache.http.client.fluent.Executor) Test(org.junit.Test)

Example 35 with Executor

use of org.apache.http.client.fluent.Executor in project substitution-schedule-parser by vertretungsplanme.

the class LoginHandlerTest method testPostAuth.

@Test
public void testPostAuth() throws JSONException, IOException, CredentialInvalidException {
    stubPostAuth();
    Executor exec = newExecutor();
    LoginHandler handler = new LoginHandler(dataPost, correct, null);
    handler.handleLogin(exec, null);
    // loading page should succeed
    String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString();
    assertEquals("content", content);
}
Also used : Executor(org.apache.http.client.fluent.Executor) Test(org.junit.Test)

Aggregations

Executor (org.apache.http.client.fluent.Executor)46 Test (org.junit.Test)26 Request (org.apache.http.client.fluent.Request)12 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)11 HttpResponse (org.apache.http.HttpResponse)6 Response (org.apache.http.client.fluent.Response)6 URI (java.net.URI)5 Cookie (org.apache.http.cookie.Cookie)5 Test (org.junit.jupiter.api.Test)5 JsonObject (com.google.gson.JsonObject)4 InputStream (java.io.InputStream)4 DistributionTransportSecret (org.apache.sling.distribution.transport.DistributionTransportSecret)4 StreamsConnection (com.ibm.streamsx.rest.StreamsConnection)3 HashMap (java.util.HashMap)3 DistributionRequest (org.apache.sling.distribution.DistributionRequest)3 JsonParser (com.google.gson.JsonParser)2 Instance (com.ibm.streamsx.rest.Instance)2 ICP4DAuthenticator (com.ibm.streamsx.rest.internal.ICP4DAuthenticator)2 StandaloneAuthenticator (com.ibm.streamsx.rest.internal.StandaloneAuthenticator)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2