Example usage for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT.

Prototype

String USER_AGENT

To view the source code for org.apache.commons.httpclient.params HttpMethodParams USER_AGENT.

Click Source Link

Usage

From source file:org.jahia.test.services.render.filter.channels.ChannelResolutionAndExclusionTest.java

@Test
public void testSupportedChannelResolution() throws Exception, IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
    GetMethod nodeGet = new GetMethod(getBaseServerURL() + Jahia.getContextPath() + "/cms/render/live/en"
            + SITECONTENT_ROOT_NODE + "/home.html");
    String response = null;/*from w ww  .  j av  a  2 s .com*/
    try {
        int responseCode = client.executeMethod(nodeGet);
        assertEquals("Response code " + responseCode, 200, responseCode);
        response = nodeGet.getResponseBodyAsString();
        assertFalse("This text shouldn't be displayed on iPhone channel",
                response.contains("This banner shouldn't appear on an iPhone."));
    } finally {
        nodeGet.releaseConnection();
    }
}

From source file:org.jahia.test.services.render.filter.channels.ChannelResolutionAndExclusionTest.java

@Test
public void testUnsupportedChannelResolution() throws Exception, IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/12.0.024; Profile/MIDP-2.1 Configuration/CLDC-1.1; en-us) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.12344");
    GetMethod nodeGet = new GetMethod(getBaseServerURL() + Jahia.getContextPath() + "/cms/render/live/en"
            + SITECONTENT_ROOT_NODE + "/home.html");
    String response = null;/*w  ww  .  j ava2 s .  c  om*/
    try {
        int responseCode = client.executeMethod(nodeGet);
        assertEquals("Response code " + responseCode, 200, responseCode);
        response = nodeGet.getResponseBodyAsString();
        assertTrue("Non supported channel should fall back on generic",
                response.contains("This banner shouldn't appear on an iPhone."));
    } finally {
        nodeGet.releaseConnection();
    }
}

From source file:org.jahia.test.services.render.filter.channels.ChannelResolutionAndExclusionTest.java

@Test
public void testNonExcludedChannel() throws Exception, IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
    GetMethod nodeGet = new GetMethod(getBaseServerURL() + Jahia.getContextPath() + "/cms/render/live/en"
            + SITECONTENT_ROOT_NODE + "/home.html");
    String response = null;//  w ww  .j  av  a  2 s. c o m
    try {
        int responseCode = client.executeMethod(nodeGet);
        assertEquals("Response code " + responseCode, 200, responseCode);
        response = nodeGet.getResponseBodyAsString();
        assertTrue("This text should be displayed when channel is not iPad",
                response.contains("This text shouldn't appear on an iPad."));
    } finally {
        nodeGet.releaseConnection();
    }
}

From source file:org.jahia.test.services.render.filter.channels.ChannelResolutionAndExclusionTest.java

@Test
public void testExcludedChannel() throws Exception, IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3");
    GetMethod nodeGet = new GetMethod(getBaseServerURL() + Jahia.getContextPath() + "/cms/render/live/en"
            + SITECONTENT_ROOT_NODE + "/home.html");
    String response = null;//  w  w  w. j a v a  2  s .co  m
    try {
        int responseCode = client.executeMethod(nodeGet);
        assertEquals("Response code " + responseCode, 200, responseCode);
        response = nodeGet.getResponseBodyAsString();
        assertFalse("This text should be hidden when channel is iPad",
                response.contains("This text shouldn't appear on an iPad."));
    } finally {
        nodeGet.releaseConnection();
    }
}

From source file:org.jetbrains.jet.jvm.compiler.longTest.ResolveDescriptorsFromExternalLibraries.java

private File getFileFromUrl(@NotNull String lib, @NotNull File file, @NotNull String uri) throws IOException {
    if (file.exists()) {
        return file;
    }//w ww  .j a  va2  s  .  c om

    JetTestUtils.mkdirs(file.getParentFile());

    File tmp = new File(file.getPath() + "~");

    GetMethod method = new GetMethod(uri);

    FileOutputStream os = null;

    System.out.println("Downloading library " + lib + " to " + file);

    MultiThreadedHttpConnectionManager connectionManager = null;
    try {
        connectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient httpClient = new HttpClient(connectionManager);
        os = new FileOutputStream(tmp);
        String userAgent = ResolveDescriptorsFromExternalLibraries.class.getName() + "/commons-httpclient";
        method.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
        int code = httpClient.executeMethod(method);
        if (code != 200) {
            throw new RuntimeException("failed to execute GET " + uri + ", code is " + code);
        }
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream == null) {
            throw new RuntimeException("method is executed fine, but response is null");
        }
        ByteStreams.copy(responseBodyAsStream, os);
        os.close();
        if (!tmp.renameTo(file)) {
            throw new RuntimeException("failed to rename file: " + tmp + " to " + file);
        }
        return file;
    } finally {
        if (method != null) {
            try {
                method.releaseConnection();
            } catch (Throwable e) {
            }
        }
        if (connectionManager != null) {
            try {
                connectionManager.shutdown();
            } catch (Throwable e) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Throwable e) {
            }
        }
        tmp.delete();
    }
}

From source file:org.jetbrains.kotlin.jvm.compiler.longTest.ResolveDescriptorsFromExternalLibraries.java

private static File getFileFromUrl(@NotNull String lib, @NotNull File file, @NotNull String uri)
        throws IOException {
    if (file.exists()) {
        return file;
    }/*from  w  w  w . java  2 s.co m*/

    KotlinTestUtils.mkdirs(file.getParentFile());

    File tmp = new File(file.getPath() + "~");

    GetMethod method = new GetMethod(uri);

    FileOutputStream os = null;

    System.out.println("Downloading library " + lib + " to " + file);

    MultiThreadedHttpConnectionManager connectionManager = null;
    try {
        connectionManager = new MultiThreadedHttpConnectionManager();
        HttpClient httpClient = new HttpClient(connectionManager);
        os = new FileOutputStream(tmp);
        String userAgent = ResolveDescriptorsFromExternalLibraries.class.getName() + "/commons-httpclient";
        method.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
        int code = httpClient.executeMethod(method);
        if (code != 200) {
            throw new RuntimeException("failed to execute GET " + uri + ", code is " + code);
        }
        InputStream responseBodyAsStream = method.getResponseBodyAsStream();
        if (responseBodyAsStream == null) {
            throw new RuntimeException("method is executed fine, but response is null");
        }
        ByteStreams.copy(responseBodyAsStream, os);
        os.close();
        if (!tmp.renameTo(file)) {
            throw new RuntimeException("failed to rename file: " + tmp + " to " + file);
        }
        return file;
    } finally {
        try {
            method.releaseConnection();
        } catch (Throwable e) {
        }
        if (connectionManager != null) {
            try {
                connectionManager.shutdown();
            } catch (Throwable e) {
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (Throwable e) {
            }
        }
        tmp.delete();
    }
}

From source file:org.moxie.proxy.connection.ProxyDownload.java

/**
 * Do the download.//from w  w  w  .j  a  v a 2 s . c o m
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + "to " + dest.getAbsolutePath());

    GetMethod get = new GetMethod(url.toString());
    get.setFollowRedirects(true);
    try {
        int status = client.executeMethod(get);

        log.info("Download status: " + status);
        if (status == 1 && log.isLoggable(Level.FINE)) {
            Header[] header = get.getResponseHeaders();
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(get.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(get);
        }

        // Make sure the temporary file is created in
        // the destination folder, otherwise
        // dl.renameTo(dest) might not work
        // for example if you have a separate /tmp partition
        // on Linux
        File destinationFolder = dest.getParentFile();
        dest.getParentFile().mkdirs();
        File dl = File.createTempFile("moxie-", ".tmp", destinationFolder);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dl));
        copy(get.getResponseBodyAsStream(), out);
        out.close();

        // create folder structure after successful download
        // - no, we create it before the download!
        //dest.getParentFile().mkdirs();

        if (dest.exists()) {
            dest.delete();
        }
        dl.renameTo(dest);

        // preserve last-modified, if possible
        try {
            Header lastModified = get.getResponseHeader("Last-Modified");
            if (lastModified != null) {
                Date date = DateUtil.parseDate(lastModified.getValue());
                dest.setLastModified(date.getTime());
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "could not parse \"last-modified\" for " + url, e);
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:org.moxie.proxy.connection.ProxyHead.java

/**
 * Do the download (of the headers)./*from ww  w .jav  a  2 s.  co m*/
 * 
 * @throws IOException
 * @throws DownloadFailed
 */
public void download() throws IOException, DownloadFailed {
    if (!config.isAllowed(url)) {
        throw new DownloadFailed(
                "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in Moxie Proxy config");
    }

    HttpClient client = new HttpClient();
    String userAgent = config.getUserAgent();
    if (userAgent != null && userAgent.trim().length() > 0) {
        client.getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent);
    }

    String msg = "";
    if (config.useProxy(url)) {
        Proxy proxy = config.getProxy(url);
        Credentials defaultcreds = new UsernamePasswordCredentials(proxy.username, proxy.password);
        AuthScope scope = new AuthScope(proxy.host, proxy.port, AuthScope.ANY_REALM);
        HostConfiguration hc = new HostConfiguration();
        hc.setProxy(proxy.host, proxy.port);
        client.setHostConfiguration(hc);
        client.getState().setProxyCredentials(scope, defaultcreds);
        msg = "via proxy ";
    }
    log.info("Downloading " + msg + url);

    MyHeadMethod head = new MyHeadMethod(url.toString());
    head.setFollowRedirects(true);
    try {
        int status = client.executeMethod(head);

        log.info("Download status: " + status);
        this.header = head.getResponseHeaders();
        this.statusLine = head.getStatusLine().toString();
        this.responseBody = head.getResponseBody();
        if (status == 1 && log.isLoggable(Level.FINE)) {
            for (int i = 0; i < header.length; i++)
                log.fine(header[i].toString().trim());
        }

        log.info("Content: " + valueOf(head.getResponseHeader("Content-Length")) + " bytes; "
                + valueOf(head.getResponseHeader("Content-Type")));

        if (status != HttpStatus.SC_OK) {
            throw new DownloadFailed(head);
        }

    } finally {
        head.releaseConnection();
    }
}

From source file:org.openrdf.repository.sparql.SPARQLConnection.java

public SPARQLConnection(SPARQLRepository repository, String queryEndpointUrl, String updateEndpointUrl) {
    super(repository);
    this.queryEndpointUrl = queryEndpointUrl;
    this.updateEndpointUrl = updateEndpointUrl;

    // Use MultiThreadedHttpConnectionManager to allow concurrent access on
    // HttpClient
    HttpConnectionManager manager = new MultiThreadedHttpConnectionManager();

    // Allow 20 concurrent connections to the same host (default is 2)
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setDefaultMaxConnectionsPerHost(20);
    params.setStaleCheckingEnabled(false);
    manager.setParams(params);/* www.  j a v a 2  s .co  m*/

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setParameter(HttpMethodParams.USER_AGENT,
            APP_NAME + "/" + VERSION + " " + clientParams.getParameter(HttpMethodParams.USER_AGENT));
    // set additional HTTP headers, if desired by the user
    if (repository.getAdditionalHttpHeaders() != null)
        clientParams.setParameter(ADDITIONAL_HEADER_NAME, repository.getAdditionalHttpHeaders());
    client = new HttpClient(clientParams, manager);
}

From source file:org.red5.server.service.Installer.java

/**
 * Returns a Map containing all of the application wars in the snapshot repository.
 * /*from   ww w .ja  v  a2s  . c o m*/
 * @return async message
 */
public AsyncMessage getApplicationList() {
    AcknowledgeMessage result = new AcknowledgeMessage();

    // create a singular HttpClient object
    HttpClient client = new HttpClient();

    // set the proxy (WT)
    // test if we received variables on the commandline
    if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(System.getProperty("http.proxyHost").toString(),
                Integer.parseInt(System.getProperty("http.proxyPort")));
    }

    // establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    //get the params for the client
    HttpClientParams params = client.getParams();
    params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
    //get registry file
    HttpMethod method = new GetMethod(applicationRepositoryUrl + "registry-0.9.xml");
    //follow any 302's although there shouldnt be any
    method.setFollowRedirects(true);
    // execute the method
    try {
        IConnection conn = Red5.getConnectionLocal();
        int code = client.executeMethod(method);
        log.debug("HTTP response code: {}", code);
        String xml = method.getResponseBodyAsString();
        log.trace("Response: {}", xml);
        //prepare response for flex         
        result.body = xml;
        result.clientId = conn.getClient().getId();
        result.messageId = UUID.randomUUID().toString();
        result.timestamp = System.currentTimeMillis();
        //send the servers java version so the correct apps are installed
        String javaVersion = System.getProperty("java.version");
        if (!ServiceUtils.invokeOnConnection(conn, "onJavaVersion", new Object[] { javaVersion })) {
            log.warn("Client call to onJavaVersion failed");
        }
    } catch (HttpException he) {
        log.error("Http error connecting to {}", applicationRepositoryUrl, he);
    } catch (IOException ioe) {
        log.error("Unable to connect to {}", applicationRepositoryUrl, ioe);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return result;
}