Example usage for java.net HttpURLConnection setAllowUserInteraction

List of usage examples for java.net HttpURLConnection setAllowUserInteraction

Introduction

In this page you can find the example usage for java.net HttpURLConnection setAllowUserInteraction.

Prototype

public void setAllowUserInteraction(boolean allowuserinteraction) 

Source Link

Document

Set the value of the allowUserInteraction field of this URLConnection .

Usage

From source file:com.eucalyptus.tokens.oidc.OidcDiscoveryCache.java

private OidcDiscoveryCachedResource fetchResource(final String url, final long timeNow,
        final OidcDiscoveryCachedResource cached) throws IOException {
    final URL location = new URL(url);
    final OidcResource oidcResource;
    { // setup url connection and resolve
        final HttpURLConnection conn = (HttpURLConnection) location.openConnection();
        conn.setAllowUserInteraction(false);
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(CONNECT_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        conn.setUseCaches(false);//from www  . j  av  a2 s. c o  m
        if (cached != null) {
            if (cached.lastModified.isDefined()) {
                conn.setRequestProperty(HttpHeaders.IF_MODIFIED_SINCE, cached.lastModified.get());
            }
            if (cached.etag.isDefined()) {
                conn.setRequestProperty(HttpHeaders.IF_NONE_MATCH, cached.etag.get());
            }
        }
        oidcResource = resolve(conn);
    }

    // build cache entry from resource
    if (oidcResource.statusCode == 304) {
        return new OidcDiscoveryCachedResource(timeNow, cached);
    } else {
        return new OidcDiscoveryCachedResource(timeNow, Option.of(oidcResource.lastModifiedHeader),
                Option.of(oidcResource.etagHeader), ImmutableList.copyOf(oidcResource.certs), url,
                new String(oidcResource.content, StandardCharsets.UTF_8));
    }
}

From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Extract the content of a scitation.aip.org page.
 * (changed code from ScrapingContext.getContentAsString)
 * @param urlConn Connection to api page (from url.openConnection())
 * @param cookie Cookie for auth.//from   ww w.ja va  2s . com
 * @return Content of aip page.
 * @throws IOException
 */
private String getPageContent(HttpURLConnection urlConn, String cookie) throws IOException {

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);
    urlConn.setRequestProperty("Cookie", cookie);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // build content
    StringWriter out = new StringWriter();
    InputStream in = new BufferedInputStream(urlConn.getInputStream());
    int b;
    while ((b = in.read()) >= 0) {
        out.write(b);
    }

    urlConn.disconnect();
    in.close();
    out.flush();
    out.close();

    return out.toString();
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 * @param req servlet request//  w  ww .jav a 2s. c o m
 * @param resp servlet response
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {

        URL url = getURL(req, req.getParameter("uri"));
        HttpURLConnection con = (HttpURLConnection) (url.openConnection());
        con.setAllowUserInteraction(false);
        con.setUseCaches(false);

        // TODO: figure out why this is necessary for HTTPS URLs
        if (con instanceof HttpsURLConnection) {
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                        return true;
                    } else {
                        log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                        return false;
                    }
                }
            };
            ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
        }
        // pass along all appropriate HTTP headers
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hname = (String) headerNames.nextElement();
            if (!unproxiedHeaders.contains(hname.toLowerCase())) {
                con.addRequestProperty(hname, req.getHeader(hname));
            }
        }
        con.connect();

        // read result headers of GET, write to response
        Map<String, List<String>> headers = con.getHeaderFields();
        for (String key : headers.keySet()) {
            if (key != null) { // TODO: why is this check necessary!
                List<String> header = headers.get(key);
                if (header.size() > 0)
                    resp.setHeader(key, header.get(0));
            }
        }

        InputStream in = con.getInputStream();
        OutputStream out = resp.getOutputStream();
        final byte[] buf = new byte[8192];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();

    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

private void performHeadHTTPMethod(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(false);/*from  ww  w .  ja v  a2  s  .  co  m*/
    conn.setAllowUserInteraction(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1"));
    conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
    conn.setRequestMethod("HEAD");
    conn.connect();
    int code = conn.getResponseCode();
}

From source file:org.openbravo.test.datasource.TestAllowUnpagedDatasourcePreference.java

private HttpURLConnection createConnection(String wsPart, String method) throws Exception {
    Authenticator.setDefault(new Authenticator() {
        @Override// www  .  j a v  a  2  s  .c  o m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(LOGIN, PWD.toCharArray());
        }
    });
    final URL url = new URL(getOpenbravoURL() + wsPart);
    final HttpURLConnection hc = (HttpURLConnection) url.openConnection();
    hc.setRequestMethod(method);
    hc.setAllowUserInteraction(false);
    hc.setDefaultUseCaches(false);
    hc.setDoOutput(true);
    hc.setDoInput(true);
    hc.setInstanceFollowRedirects(true);
    hc.setUseCaches(false);
    hc.setRequestProperty("Content-Type", "text/xml");
    return hc;
}

From source file:com.entertailion.android.dial.HttpRequestHelper.java

public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;/*from   w  w  w .j  a  v  a2s  . c om*/
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception e) {
        throw new IOException("Error connecting");
    } // end try-catch

    return in;
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 * @param req servlet request//from  w w  w.  j a v a 2 s.c o  m
 * @param resp servlet response
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    URL url = getURL(req, req.getParameter("uri"));
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(true);
    con.setAllowUserInteraction(false);
    con.setUseCaches(false);

    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    // pass along all appropriate HTTP headers
    Enumeration headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hname = (String) headerNames.nextElement();
        if (!unproxiedHeaders.contains(hname.toLowerCase())) {
            con.addRequestProperty(hname, req.getHeader(hname));
        }
    }
    con.connect();

    // read POST data from incoming request, write to outgoing request
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    // read result headers of POST, write to response
    Map<String, List<String>> headers = con.getHeaderFields();
    for (String key : headers.keySet()) {
        if (key != null) { // TODO: why is this check necessary!
            List<String> header = headers.get(key);
            if (header.size() > 0)
                resp.setHeader(key, header.get(0));
        }
    }

    // read result data of POST, write out to response
    in = new BufferedInputStream(con.getInputStream());
    out = new BufferedOutputStream(resp.getOutputStream());
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    in.close();
    out.close();
    out.flush();

    con.disconnect();
}

From source file:org.jboss.arquillian.container.tomcat.CommonTomcatManager.java

/**
 * Execute the specified command, based on the configured properties. The input stream will be closed upon completion of
 * this task, whether it was executed successfully or not.
 *
 * @param command Command to be executed
 * @param istream InputStream to include in an HTTP PUT, if any
 * @param contentType Content type to specify for the input, if any
 * @param contentLength Content length to specify for the input, if any
 * @throws IOException//  ww  w  . ja  v  a2 s  . c  o  m
 * @throws MalformedURLException
 * @throws DeploymentException
 */
protected void execute(String command, InputStream istream, String contentType, int contentLength)
        throws IOException {

    URLConnection conn = null;
    try {
        // Create a connection for this command
        conn = (new URL(configuration.getManagerUrl() + command)).openConnection();
        HttpURLConnection hconn = (HttpURLConnection) conn;

        // Set up standard connection characteristics
        hconn.setAllowUserInteraction(false);
        hconn.setDoInput(true);
        hconn.setUseCaches(false);
        if (istream != null) {
            hconn.setDoOutput(true);
            hconn.setRequestMethod("PUT");
            if (contentType != null) {
                hconn.setRequestProperty("Content-Type", contentType);
            }
            if (contentLength >= 0) {
                hconn.setRequestProperty("Content-Length", "" + contentLength);

                hconn.setFixedLengthStreamingMode(contentLength);
            }
        } else {
            hconn.setDoOutput(false);
            hconn.setRequestMethod("GET");
        }
        hconn.setRequestProperty("User-Agent", "Arquillian-Tomcat-Manager-Util/1.0");
        // add authorization header if password is provided
        if (configuration.getUser() != null && configuration.getUser().length() != 0) {
            hconn.setRequestProperty("Authorization", constructHttpBasicAuthHeader());
        }
        hconn.setRequestProperty("Accept", "text/plain");

        // Establish the connection with the server
        hconn.connect();

        // Send the request data (if any)
        if (istream != null) {
            BufferedOutputStream ostream = new BufferedOutputStream(hconn.getOutputStream(), 1024);
            IOUtil.copy(istream, ostream);
            ostream.flush();
            ostream.close();
            istream.close();
        }

        processResponse(command, hconn);
    } finally {
        IOUtil.closeQuietly(istream);
    }
}

From source file:org.bibsonomy.scraper.url.kde.blackwell.BlackwellSynergyScraper.java

/** FIXME: refactor
 * Gets the cookie which is needed to extract the content of aip pages.
 * (changed code from ScrapingContext.getContentAsString) 
 * @param urlConn Connection to api page (from url.openConnection())
 * @return The value of the cookie.//from   w  w w .  j a va2s .  c o  m
 * @throws IOException
 */
private String getCookie() throws IOException {
    HttpURLConnection urlConn = (HttpURLConnection) new URL("http://www.blackwell-synergy.com/help")
            .openConnection();
    String cookie = null;

    urlConn.setAllowUserInteraction(true);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(false);
    urlConn.setUseCaches(false);
    urlConn.setFollowRedirects(true);
    urlConn.setInstanceFollowRedirects(false);

    urlConn.setRequestProperty("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
    urlConn.connect();

    // extract cookie from header
    Map map = urlConn.getHeaderFields();
    cookie = urlConn.getHeaderField("Set-Cookie");
    if (cookie != null && cookie.indexOf(";") >= 0)
        cookie = cookie.substring(0, cookie.indexOf(";"));

    urlConn.disconnect();
    return cookie;
}

From source file:nl.b3p.viewer.stripes.ProxyActionBean.java

private Resolution proxyArcIMS() throws Exception {

    HttpServletRequest request = getContext().getRequest();

    if (!"POST".equals(request.getMethod())) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }//w ww.  j  av a  2s  .c  o  m

    Map params = new HashMap(getContext().getRequest().getParameterMap());
    // Only allow these parameters in proxy request
    params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName"));
    URL theUrl = new URL(url);
    // Must not allow file / jar etc protocols, only HTTP:
    String path = theUrl.getPath();
    for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) {
        if (path.length() == theUrl.getPath().length()) {
            path += "?";
        } else {
            path += "&";
        }
        path += URLEncoder.encode(param.getKey(), "UTF-8") + "="
                + URLEncoder.encode(param.getValue()[0], "UTF-8");
    }
    theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path);

    // TODO logging for inspecting malicious proxy use

    ByteArrayOutputStream post = new ByteArrayOutputStream();
    IOUtils.copy(request.getInputStream(), post);

    // This check makes some assumptions on how browsers serialize XML
    // created by OpenLayers' ArcXML.js write() function (whitespace etc.),
    // but all major browsers pass this check
    if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) {
        return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN);
    }

    final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr());

    connection.connect();
    try {
        IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream());
    } finally {
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
    }

    return new StreamingResolution(connection.getContentType()) {
        @Override
        protected void stream(HttpServletResponse response) throws IOException {
            try {
                IOUtils.copy(connection.getInputStream(), response.getOutputStream());
            } finally {
                connection.disconnect();
            }

        }
    };
}