Example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

List of usage examples for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy.

Prototype

LaxRedirectStrategy

Source Link

Usage

From source file:fr.ippon.wip.http.hc.HttpClientResourceManager.java

private HttpClientResourceManager() {
    perUserClientMap = Collections.synchronizedMap(new HashMap<String, HttpClient>());
    perUserCookieStoreMap = Collections.synchronizedMap(new HashMap<String, CookieStore>());
    perUserWindowCredentialProviderMap = Collections
            .synchronizedMap(new HashMap<String, CredentialsProvider>());
    currentPortletRequest = new ThreadLocal<PortletRequest>();
    currentPortletResponse = new ThreadLocal<PortletResponse>();
    currentRequest = new ThreadLocal<RequestBuilder>();

    try {/*from w w  w  .  ja va2  s.co  m*/
        SSLSocketFactory ssf = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                new AllowAllHostnameVerifier());
        Scheme httpsScheme = new Scheme("https", 443, ssf);
        PlainSocketFactory psf = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", 80, psf);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(httpsScheme);
        registry.register(httpScheme);
        connectionManager = new PoolingClientConnectionManager(registry);
        connectionManager.setDefaultMaxPerRoute(10);
        connectionManager.setMaxTotal(100);

        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager);

        // automatically redirects all HEAD, GET and POST requests
        defaultHttpClient.setRedirectStrategy(new LaxRedirectStrategy());

        CacheConfig cacheConfig = createAndConfigureCache();

        URL ehCacheConfig = getClass().getResource("/ehcache.xml");
        cacheManager = CacheManager.create(ehCacheConfig);
        Ehcache ehcache = cacheManager.getEhcache("public");
        EhcacheHttpCacheStorage httpCacheStorage = new EhcacheHttpCacheStorage(ehcache);

        CachingHttpClient sharedCacheClient = new CachingHttpClient(defaultHttpClient, httpCacheStorage,
                cacheConfig);
        HttpClientDecorator decoratedClient = new HttpClientDecorator(sharedCacheClient);

        decoratedClient.addPreProcessor(new LtpaRequestInterceptor());
        decoratedClient.addPreProcessor(new StaleIfErrorRequestInterceptor(staleIfErrorTime));
        decoratedClient.addFilter(new IgnoreHttpRequestFilter());

        decoratedClient.addPostProcessor(new TransformerResponseInterceptor());

        rootClient = decoratedClient;

    } catch (Exception e) {
        throw new RuntimeException("Could not initialize connection manager", e);
    }

}

From source file:org.whispersystems.mmsmonster.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/* w  w w  . j  a  va 2 s  .c  o  m*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:gov.medicaid.screening.dao.impl.HealthOccupationsProgramCredentialDAOBean.java

/**
 * Performs a search for all possible results.
 *
 * @param criteria The search criteria.// ww  w  . j  av  a2  s  .  co  m
 * @return the search result for licenses
 *
 * @throws URISyntaxException if an error occurs while building the URL.
 * @throws ClientProtocolException if client does not support protocol used.
 * @throws IOException if an error occurs while parsing response.
 * @throws ParseException if an error occurs while parsing response.
 * @throws ServiceException for any other problems encountered
 */
private SearchResult<ProviderProfile> getAllResults(HealthOccupationsProgramCredentialSearchCriteria criteria)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient(getLaxSSLConnectionManager());
    client.setRedirectStrategy(new LaxRedirectStrategy());

    HttpGet getSearch = new HttpGet(new URIBuilder(getSearchURL()).build());
    HttpResponse response = client.execute(getSearch);

    verifyAndAuditCall(getSearchURL(), response);
    EntityUtils.consume(response.getEntity());

    String fullSearchURL = Util.replaceLastURLPart(getSearchURL(), "credential_search.do");
    HttpPost search = new HttpPost(new URIBuilder(fullSearchURL).build());
    List<ProviderProfile> allProfiles = new ArrayList<ProviderProfile>();

    HttpEntity entity = postForm(fullSearchURL, client, search,
            new String[][] { { "city", Util.defaultString(criteria.getCity()) },
                    { "credentialNumber", Util.defaultLongString(criteria.getCredentialNumber()) },
                    { "firstName", Util.defaultString(criteria.getFirstName()) },
                    { "lastName", Util.defaultString(criteria.getLastName()) },
                    { "county", getDefaultValue(criteria.getCounty()) },
                    { "credentialStatus", getDefaultValue(criteria.getStatus()) },
                    { "credentialType", getDefaultValue(criteria.getOccupationType()) },
                    { "discipline", getDefaultValue(criteria.getDiscipline()) },
                    { "state", getDefaultValue(criteria.getState()) }, { "p_action", "search" } },
            false);

    Document page = Jsoup.parse(EntityUtils.toString(entity));

    Elements rows = page.select("table.formTable tr:gt(0)");
    for (Element row : rows) {
        allProfiles.add(parseProfile(row.children()));
    }

    SearchResult<ProviderProfile> searchResult = new SearchResult<ProviderProfile>();
    searchResult.setItems(allProfiles);
    return searchResult;
}

From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 *
 * @param msgContext/*from   ww w.  ja v  a  2  s. c  o  m*/
 *            the messsage context
 *
 * @throws AxisFault
 */
public void invoke(final MessageContext msgContext) throws AxisFault {
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    Request req = null;
    Response response = null;
    try {
        if (exec == null) {
            targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
            String userID = msgContext.getUsername();
            String passwd = msgContext.getPassword();
            // if UserID is not part of the context, but is in the URL, use
            // the one in the URL.
            if ((userID == null) && (targetURL.getUserInfo() != null)) {
                String info = targetURL.getUserInfo();
                int sep = info.indexOf(':');

                if ((sep >= 0) && (sep + 1 < info.length())) {
                    userID = info.substring(0, sep);
                    passwd = info.substring(sep + 1);
                } else
                    userID = info;
            }
            Credentials cred = new UsernamePasswordCredentials(userID, passwd);
            if (userID != null) {
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = userID.indexOf("\\");
                if (domainIndex > 0) {
                    String domain = userID.substring(0, domainIndex);
                    if (userID.length() > domainIndex + 1) {
                        String user = userID.substring(domainIndex + 1);
                        cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain);
                    }
                }
            }
            HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() {

                public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
                        final HttpContext context) throws ProtocolException {
                    URI uri = getLocationURI(request, response, context);
                    String method = request.getRequestLine().getMethod();
                    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME))
                        return new HttpHead(uri);
                    else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                        HttpPost httpPost = new HttpPost(uri);
                        httpPost.addHeader(request.getFirstHeader("Authorization"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        httpPost.addHeader(request.getFirstHeader("Content-Type"));
                        httpPost.addHeader(request.getFirstHeader("User-Agent"));
                        httpPost.addHeader(request.getFirstHeader("SOAPAction"));
                        if (request instanceof HttpEntityEnclosingRequest)
                            httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
                        return httpPost;
                    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
                        return new HttpGet(uri);
                    } else {
                        throw new IllegalStateException(
                                "Redirect called on un-redirectable http method: " + method);
                    }
                }
            }).build();

            exec = Executor.newInstance(httpClient);
            HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol());
            exec.auth(host, cred);
            exec.authPreemptive(host);
            HttpUtils.setupProxy(exec, targetURL.toURI());
        }
        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null)
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
        }
        HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI());
        if (posting) {
            req = Request.Post(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            Message reqMessage = msgContext.getRequestMessage();

            addContextInfo(req, msgContext, targetURL);
            Iterator<?> it = reqMessage.getAttachments();
            if (it.hasNext()) {
                ByteArrayOutputStream bos = null;
                try {
                    bos = new ByteArrayOutputStream();
                    reqMessage.writeTo(bos);
                    req.body(new ByteArrayEntity(bos.toByteArray()));
                } finally {
                    FileUtils.closeStream(bos);
                }
            } else
                req.body(new StringEntity(reqMessage.getSOAPPartAsString()));

        } else {
            req = Request.Get(targetURL.toString());
            if (proxy != null)
                req.viaProxy(proxy);
            addContextInfo(req, msgContext, targetURL);
        }

        response = exec.execute(req);
        response.handleResponse(new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response) throws IOException {
                HttpEntity en = response.getEntity();
                InputStream in = null;
                try {
                    StatusLine statusLine = response.getStatusLine();
                    int returnCode = statusLine.getStatusCode();
                    String contentType = en.getContentType().getValue();

                    in = new BufferedHttpEntity(en).getContent();
                    // String str = IOUtils.toString(in);
                    if (returnCode > 199 && returnCode < 300) {
                        // SOAP return is OK - so fall through
                    } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
                        // For now, if we're SOAP 1.2, fall
                        // through, since the range of
                        // valid result codes is much greater
                    } else if (contentType != null && !contentType.equals("text/html")
                            && ((returnCode > 499) && (returnCode < 600))) {
                        // SOAP Fault should be in here - so
                        // fall through
                    } else {
                        String statusMessage = statusLine.getReasonPhrase();
                        AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null,
                                null);
                        fault.setFaultDetailString(
                                Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in)));
                        fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
                                Integer.toString(returnCode));
                        throw fault;
                    }
                    Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP))
                            in = new GZIPInputStream(in);
                        else {
                            AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '"
                                    + contentEncoding.getValue() + "' found", null, null);
                            throw fault;
                        }

                    }

                    // Transfer HTTP headers of HTTP message
                    // to MIME headers of SOAP
                    // message
                    MimeHeaders mh = new MimeHeaders();
                    for (Header h : response.getAllHeaders())
                        mh.addHeader(h.getName(), h.getValue());
                    Message outMsg = new Message(in, false, mh);

                    outMsg.setMessageType(Message.RESPONSE);
                    msgContext.setResponseMessage(outMsg);
                    if (log.isDebugEnabled()) {
                        log.debug("\n" + Messages.getMessage("xmlRecd00"));
                        log.debug("-----------------------------------------------");
                        log.debug(outMsg.getSOAPPartAsString());
                    }
                } finally {
                    FileUtils.closeStream(in);
                }
                return "";
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        log.debug(e);
        throw AxisFault.makeFault(e);
    }
    if (log.isDebugEnabled())
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
}

From source file:cz.opendata.linked.lodcloud.loader.Loader.java

@Override
protected void innerExecute() throws DPUException {
    logger.debug("Querying metadata");

    String datasetUrl = executeSimpleSelectQuery(
            "SELECT ?d WHERE {?d a <" + LoaderVocabulary.DCAT_DATASET_CLASS + ">}", "d");

    List<Map<String, Value>> distributions = executeSelectQuery(
            "SELECT ?distribution WHERE {<" + datasetUrl + "> <" + LoaderVocabulary.DCAT_DISTRIBUTION
                    + "> ?distribution . ?distribution <" + LoaderVocabulary.VOID_SPARQLENDPOINT + "> [] .  }");

    if (distributions.size() != 1) {
        throw new DPUException("Expected 1 distribution with SPARQL endpoint. Found: " + distributions.size());
    }/*from  w  ww .  ja  va  2  s  .  c  o m*/

    String distribution = distributions.get(0).get("distribution").stringValue();
    String title = executeSimpleSelectQuery("SELECT ?title WHERE {<" + distribution + "> <" + DCTERMS.TITLE
            + "> ?title FILTER(LANGMATCHES(LANG(?title), \"en\"))}", "title");
    String description = executeSimpleSelectQuery("SELECT ?description WHERE {<" + distribution + "> <"
            + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \"en\"))}",
            "description");
    String sparqlEndpointVoid = executeSimpleSelectQuery("SELECT ?sparqlEndpoint WHERE {<" + distribution
            + "> <" + LoaderVocabulary.VOID_SPARQLENDPOINT + "> ?sparqlEndpoint }", "sparqlEndpoint");
    String datadump = executeSimpleSelectQuery(
            "SELECT ?dwnld WHERE {<" + distribution + "> <" + LoaderVocabulary.VOID_DATADUMP + "> ?dwnld }",
            "dwnld");
    String triplecount = executeSimpleSelectQuery("SELECT ?triplecount WHERE {<" + distribution + "> <"
            + LoaderVocabulary.VOID_TRIPLES + "> ?triplecount }", "triplecount");
    String dformat = executeSimpleSelectQuery(
            "SELECT ?format WHERE {<" + distribution + "> <" + DCTERMS.FORMAT + "> ?format }", "format");
    String dlicense = executeSimpleSelectQuery(
            "SELECT ?license WHERE {<" + distribution + "> <" + DCTERMS.LICENSE + "> ?license }", "license");
    String dschema = executeSimpleSelectQuery("SELECT ?schema WHERE {<" + distribution + "> <"
            + LoaderVocabulary.WDRS_DESCRIBEDBY + "> ?schema }", "schema");

    LinkedList<String> examples = new LinkedList<String>();
    for (Map<String, Value> map : executeSelectQuery("SELECT ?exampleResource WHERE {<" + distribution + "> <"
            + LoaderVocabulary.VOID_EXAMPLERESOURCE + "> ?exampleResource }")) {
        examples.add(map.get("exampleResource").stringValue());
    }

    logger.debug("Querying for the dataset in CKAN");
    boolean exists = false;
    Map<String, String> resUrlIdMap = new HashMap<String, String>();
    Map<String, String> resFormatIdMap = new HashMap<String, String>();

    CloseableHttpClient queryClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy())
            .build();
    HttpGet httpGet = new HttpGet(config.getApiUri() + "/" + config.getDatasetID());
    CloseableHttpResponse queryResponse = null;
    try {
        queryResponse = queryClient.execute(httpGet);
        if (queryResponse.getStatusLine().getStatusCode() == 200) {
            logger.info("Dataset found");
            exists = true;

            JSONObject response = new JSONObject(EntityUtils.toString(queryResponse.getEntity()));
            JSONArray resourcesArray = response.getJSONArray("resources");
            for (int i = 0; i < resourcesArray.length(); i++) {
                try {
                    String id = resourcesArray.getJSONObject(i).getString("id");
                    String url = resourcesArray.getJSONObject(i).getString("url");
                    resUrlIdMap.put(url, id);

                    if (resourcesArray.getJSONObject(i).has("format")) {
                        String format = resourcesArray.getJSONObject(i).getString("format");
                        resFormatIdMap.put(format, id);
                    }

                } catch (JSONException e) {
                    logger.error(e.getLocalizedMessage(), e);
                }
            }

        } else {
            String ent = EntityUtils.toString(queryResponse.getEntity());
            logger.info("Dataset not found");
        }
    } catch (ClientProtocolException e) {
        logger.error(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage(), e);
    } catch (ParseException e) {
        logger.error(e.getLocalizedMessage(), e);
    } catch (JSONException e) {
        logger.error(e.getLocalizedMessage(), e);
    } finally {
        if (queryResponse != null) {
            try {
                queryResponse.close();
                queryClient.close();
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
    }

    logger.debug("Creating JSON");
    try {
        JSONObject root = new JSONObject();

        JSONArray tags = new JSONArray();
        tags.put("lod");
        tags.put(config.getVocabTag().toString());
        tags.put(config.getVocabMappingTag().toString());
        tags.put(config.getPublishedTag().toString());
        tags.put(config.getProvenanceMetadataTag().toString());
        tags.put(config.getLicenseMetadataTag().toString());
        if (config.isLimitedSparql())
            tags.put("limited-sparql-endpoint");
        if (config.isLodcloudNolinks())
            tags.put("lodcloud.nolinks");
        if (config.isLodcloudUnconnected())
            tags.put("lodcloud.unconnected");
        if (config.isLodcloudNeedsInfo())
            tags.put("lodcloud.needsinfo");
        if (config.isLodcloudNeedsFixing())
            tags.put("lodcloud.needsfixing");
        for (String prefix : config.getVocabularies()) {
            tags.put("format-" + prefix);
        }
        tags.put(config.getTopic());
        for (String s : config.getAdditionalTags())
            tags.put(s);

        JSONArray resources = new JSONArray();

        // Start of Sparql Endpoint resource
        JSONObject sparqlEndpoint = new JSONObject();

        sparqlEndpoint.put("format", "api/sparql");
        sparqlEndpoint.put("resource_type", "api");
        sparqlEndpoint.put("description", config.getSparqlEndpointDescription());
        sparqlEndpoint.put("name", config.getSparqlEndpointName());
        sparqlEndpoint.put("url", sparqlEndpointVoid);

        if (resFormatIdMap.containsKey("api/sparql"))
            sparqlEndpoint.put("id", resFormatIdMap.get("api/sparql"));

        resources.put(sparqlEndpoint);
        // End of Sparql Endpoint resource

        // Start of VoID resource
        JSONObject voidJson = new JSONObject();

        voidJson.put("format", "meta/void");
        voidJson.put("resource_type", "file");
        voidJson.put("description", "VoID description generated live");
        voidJson.put("name", "VoID");
        String voidUrl = sparqlEndpointVoid + "?query="
                + URLEncoder.encode("DESCRIBE <" + distribution + ">", "UTF-8") + "&output="
                + URLEncoder.encode("text/turtle", "UTF-8");
        voidJson.put("url", voidUrl);

        if (resFormatIdMap.containsKey("meta/void"))
            voidJson.put("id", resFormatIdMap.get("meta/void"));

        resources.put(voidJson);
        // End of VoID resource

        if (config.getVocabTag() != LoaderConfig.VocabTags.NoProprietaryVocab && !dschema.isEmpty()) {
            // Start of RDFS/OWL schema resource
            JSONObject schemaResource = new JSONObject();

            schemaResource.put("format", "meta/rdf-schema");
            schemaResource.put("resource_type", "file");
            schemaResource.put("description", "RDFS/OWL Schema with proprietary vocabulary");
            schemaResource.put("name", "RDFS/OWL schema");
            schemaResource.put("url", dschema);

            if (resFormatIdMap.containsKey("meta/rdf-schema"))
                schemaResource.put("id", resFormatIdMap.get("meta/rdf-schema"));

            resources.put(schemaResource);
            // End of RDFS/OWL schema resource
        }

        // Start of Dump resource
        JSONObject dump = new JSONObject();

        dump.put("format", dformat);
        dump.put("resource_type", "file");
        //dump.put("description","Dump is a zipped TriG file");
        dump.put("name", "Dump");
        dump.put("url", datadump);

        if (resUrlIdMap.containsKey(datadump))
            dump.put("id", resUrlIdMap.get(datadump));

        resources.put(dump);
        // End of Dump resource

        for (String example : examples) {
            // Start of Example resource text/turtle
            JSONObject exTurtle = new JSONObject();

            exTurtle.put("format", "example/turtle");
            exTurtle.put("resource_type", "file");
            //exTurtle.put("description","Generated by Virtuoso FCT");
            exTurtle.put("name", "Example resource in Turtle");
            String exTurtleUrl = sparqlEndpointVoid + "?query="
                    + URLEncoder.encode("DESCRIBE <" + example + ">", "UTF-8") + "&output="
                    + URLEncoder.encode("text/turtle", "UTF-8");
            exTurtle.put("url", exTurtleUrl);

            if (resUrlIdMap.containsKey(exTurtleUrl))
                exTurtle.put("id", resUrlIdMap.get(exTurtleUrl));

            resources.put(exTurtle);
            // End of text/turtle resource

            // Start of Example resource html
            JSONObject exHTML = new JSONObject();

            exHTML.put("format", "HTML");
            exHTML.put("resource_type", "file");
            exHTML.put("description", "Generated by Virtuoso FCT");
            exHTML.put("name", "Example resource in Virtuoso FCT");
            exHTML.put("url", example);

            if (resUrlIdMap.containsKey(example))
                exHTML.put("id", resUrlIdMap.get(example));

            resources.put(exHTML);
            // End of html resource

            // Mapping file resources
            for (MappingFile mapping : config.getMappingFiles()) {
                JSONObject exMapping = new JSONObject();

                String mappingMime = "mapping/" + mapping.getMappingFormat();
                exMapping.put("format", mappingMime);
                exMapping.put("resource_type", "file");
                exMapping.put("description",
                        "Schema mapping file in " + mapping.getMappingFormat() + " format.");
                exMapping.put("name", "Mapping " + mapping.getMappingFormat());
                exMapping.put("url", mapping.getMappingFile());

                if (resFormatIdMap.containsKey(mappingMime))
                    exMapping.put("id", resFormatIdMap.get(mappingMime));

                resources.put(exMapping);
            }
            // End of mapping file resources

        }

        JSONObject extras = new JSONObject();
        extras.put("triples", triplecount);
        if (!config.getShortname().isEmpty())
            extras.put("shortname", config.getShortname());
        if (!config.getNamespace().isEmpty())
            extras.put("namespace", config.getNamespace());
        if (!dlicense.isEmpty())
            extras.put("license_link", dlicense);
        extras.put("sparql_graph_name", datasetUrl);
        for (LinkCount link : config.getLinks()) {
            extras.put("links:" + link.getTargetDataset(), link.getLinkCount());
        }

        if (!config.getDatasetID().isEmpty())
            root.put("name", config.getDatasetID());
        root.put("url", datasetUrl);
        root.put("title", title);
        if (!config.getMaintainerName().isEmpty())
            root.put("maintainer", config.getMaintainerName());
        if (!config.getMaintainerEmail().isEmpty())
            root.put("maintainer_email", config.getMaintainerEmail());
        root.put("license_id", config.getLicense_id());
        root.put("notes", description);
        if (!config.getAuthorName().isEmpty())
            root.put("author", config.getAuthorName());
        if (!config.getAuthorEmail().isEmpty())
            root.put("author_email", config.getAuthorEmail());

        if (config.isVersionGenerated()) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date versiondate = new Date();
            String version = dateFormat.format(versiondate);
            root.put("version", version);
        } else if (!config.getVersion().isEmpty())
            root.put("version", config.getVersion());

        root.put("tags", tags);
        root.put("resources", resources);
        root.put("extras", extras);

        if (!exists) {
            JSONObject createRoot = new JSONObject();

            createRoot.put("name", config.getDatasetID());
            createRoot.put("title", title);
            createRoot.put("owner_org", config.getOrgID());

            logger.debug("Creating dataset in CKAN");
            CloseableHttpClient client = HttpClientBuilder.create()
                    .setRedirectStrategy(new LaxRedirectStrategy()).build();
            HttpPost httpPost = new HttpPost(config.getApiUri());
            httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey()));

            String json = createRoot.toString();

            logger.debug("Creating dataset with: " + json);

            httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

            CloseableHttpResponse response = null;

            try {
                response = client.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 201) {
                    logger.info("Dataset created OK: " + response.getStatusLine());
                } else if (response.getStatusLine().getStatusCode() == 409) {
                    logger.error("Dataset already exists: " + response.getStatusLine());
                    ContextUtils.sendError(ctx, "Dataset already exists", "Dataset already exists: {0}",
                            response.getStatusLine());
                } else {
                    ContextUtils.sendError(ctx, "Error creating dataset",
                            "Response while creating dataset: {0}", response.getStatusLine());
                }
            } catch (ClientProtocolException e) {
                logger.error(e.getLocalizedMessage(), e);
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            } finally {
                if (response != null) {
                    try {
                        response.close();
                        client.close();
                    } catch (IOException e) {
                        logger.error(e.getLocalizedMessage(), e);
                        ContextUtils.sendError(ctx, "Error creating dataset", e.getLocalizedMessage());
                    }
                }
            }
        }

        if (!ctx.canceled()) {
            logger.debug("Posting to CKAN");
            CloseableHttpClient client = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(config.getApiUri() + "/" + config.getDatasetID());
            HttpPost httpPost = new HttpPost(uriBuilder.build().normalize());
            httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey()));

            String json = root.toString();

            httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));

            CloseableHttpResponse response = null;

            try {
                response = client.execute(httpPost);
                if (response.getStatusLine().getStatusCode() == 200) {
                    logger.info("Response: " + response.getEntity());
                } else {
                    ContextUtils.sendError(ctx, "Error updating dataset",
                            "Response while updating dataset: {0}", response.getStatusLine());
                }
            } catch (ClientProtocolException e) {
                logger.error(e.getLocalizedMessage(), e);
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            } finally {
                if (response != null) {
                    try {
                        response.close();
                        client.close();
                    } catch (IOException e) {
                        logger.error(e.getLocalizedMessage(), e);
                        ContextUtils.sendError(ctx, "Error updating dataset", e.getLocalizedMessage());
                    }
                }
            }
        }
    } catch (JSONException e) {
        logger.error(e.getLocalizedMessage(), e);
    } catch (URISyntaxException e) {
        logger.error(e.getLocalizedMessage(), e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getLocalizedMessage(), e);
    }

}

From source file:com.guardtime.ksi.service.client.http.apache.ApacheHttpClient.java

/**
 * Creates asynchronous Apache HTTP client.
 *
 * @param settings/*from  ww  w  .  j  av a 2s.  co  m*/
 *         - settings to use to create client
 * @param conf
 *         - configuration related to async connection
 * @return instance of {@link CloseableHttpAsyncClient}
 */
private CloseableHttpAsyncClient createClient(AbstractHttpClientSettings settings,
        ApacheHttpClientConfiguration conf) {
    IOReactorConfig ioReactor = IOReactorConfig.custom().setIoThreadCount(conf.getMaxThreadCount()).build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom().useSystemProperties()
            // allow POST redirects
            .setRedirectStrategy(new LaxRedirectStrategy()).setMaxConnTotal(conf.getMaxTotalConnectionCount())
            .setMaxConnPerRoute(conf.getMaxRouteConnectionCount()).setDefaultIOReactorConfig(ioReactor)
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .setDefaultRequestConfig(createDefaultRequestConfig(settings));
    if (settings.getProxyUrl() != null) {
        DefaultProxyRoutePlanner routePlanner = createProxyRoutePlanner(settings, httpClientBuilder);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }
    CloseableHttpAsyncClient httpClient = httpClientBuilder.build();
    httpClient.start();
    return httpClient;
}

From source file:org.hawk.http.HTTPManager.java

private CloseableHttpClient createClient() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    // Provide username and password if specified
    if (username != null) {
        final BasicCredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(new HttpHost(repositoryURL.getHost())),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credProvider);
    }//w w w . j a v a2s  .c  o  m

    // Follow redirects
    builder.setRedirectStrategy(new LaxRedirectStrategy());

    return builder.build();
}

From source file:gov.medicaid.screening.dao.impl.PharmacyLicenseDAOBean.java

/**
 * Performs a search for all possible results.
 *
 * @param firstOrBusinessName First or Business name.
 * @param lastName Last name./*from  w  w  w  .jav a2 s . c  o  m*/
 * @param licenseNumber License number.
 * @return the search result for licenses
 * @throws URISyntaxException When an error occurs while building the URL.
 * @throws ClientProtocolException When client does not support protocol used.
 * @throws IOException When an error occurs while parsing response.
 * @throws ParseException When an error occurs while parsing response.
 */
private SearchResult<License> getAllResults(String firstOrBusinessName, String lastName, String licenseNumber)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    String path = "/mnbop/GLSuiteWeb/Clients/MNBOPharm/Public/";
    URIBuilder builder = new URIBuilder(getSearchURL()).setPath(path + "LicenseeSearch.aspx");

    HttpGet httpget = new HttpGet(builder.build());
    HttpEntity entity = client.execute(httpget).getEntity();
    Document page = Jsoup.parse(EntityUtils.toString(entity));

    HttpPost httppost = new HttpPost(builder.build());
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("__VIEWSTATE", page.select("#__VIEWSTATE").first().val()));
    parameters.add(
            new BasicNameValuePair("__VIEWSTATEENCRYPTED", page.select("#__VIEWSTATEENCRYPTED").first().val()));
    parameters
            .add(new BasicNameValuePair("__EVENTVALIDATION", page.select("#__EVENTVALIDATION").first().val()));
    parameters.add(new BasicNameValuePair("ObjectID", page.select("#ObjectID").first().val()));
    parameters.add(new BasicNameValuePair("ObjectTypeID", page.select("#ObjectTypeID").first().val()));
    parameters.add(new BasicNameValuePair("waFirstName", Util.defaultString(firstOrBusinessName)));
    parameters.add(new BasicNameValuePair("waLastName", Util.defaultString(lastName)));
    parameters.add(new BasicNameValuePair("waLicenseNumber", Util.defaultString(licenseNumber)));

    httppost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));
    HttpResponse postResponse = client.execute(httppost);

    entity = postResponse.getEntity();
    // licenses list
    List<License> licenseList = new ArrayList<License>();
    if (entity != null) {
        page = Jsoup.parse(EntityUtils.toString(entity));
        Elements trs = page.select("table#DataTable a");
        if (trs != null) {
            for (Element element : trs) {
                String href = element.attr("href");
                HttpGet detailsGet = new HttpGet(getSearchURL() + path + href);
                HttpResponse detailsResponse = client.execute(detailsGet);
                HttpEntity detailsEntity = detailsResponse.getEntity();
                if (detailsEntity != null) {
                    Document details = Jsoup.parse(EntityUtils.toString(detailsEntity));
                    licenseList.add(parseLicense(details));
                }
            }
        }
    }
    SearchResult<License> result = new SearchResult<License>();
    result.setItems(licenseList);
    return result;
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

@Test
public void concurrentLoginSingleUserSingleClient() throws Throwable {
    log.info("*********************************************");
    long start = System.currentTimeMillis();

    AtomicReference<String> userSessionId = new AtomicReference<>();
    LoginTask loginTask = null;/*from  w  w  w .  j  av a  2 s  . c om*/

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setRedirectStrategy(new LaxRedirectStrategy()).build()) {
        loginTask = new LoginTask(httpClient, userSessionId, 100, 1, true,
                Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password")));
        run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask);
        int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test",
                userSessionId.get());
        Assert.assertEquals(2, clientSessionsCount);
    } finally {
        long end = System.currentTimeMillis() - start;
        log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram());
        log.info("concurrentLoginSingleUserSingleClient took " + (end / 1000) + "s");
        log.info("*********************************************");
    }
}