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.sun.faces.systest.ant.SystestClient.java

/**
 * Read and save the contents of the golden file for this test, if any.
 * Otherwise, the <code>saveGolden</code> list will be empty.
 *
 * @throws IOException if an input/output error occurs
 *//*from w ww . j av  a  2s.  c om*/
protected void readGolden() throws IOException {

    // Was a golden file specified?
    saveGolden.clear();
    if (golden == null) {
        return;
    }

    // Create a connection to receive the golden file contents
    URL url = new URL("http", host, port, golden);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setAllowUserInteraction(false);
    conn.setDoInput(true);
    conn.setDoOutput(false);
    conn.setFollowRedirects(true);
    conn.setRequestMethod("GET");

    // Connect to the server and retrieve the golden file
    conn.connect();
    InputStream is = conn.getInputStream();
    while (true) {
        String line = read(is);
        if (line == null) {
            break;
        }
        saveGolden.add(line);
    }
    is.close();
    conn.disconnect();

}

From source file:com.sun.faces.systest.ant.SystestClient.java

/**
 * Read and save the contents of the ignore file for this test, if any.
 * Otherwise, the <code>saveIgnore</code> list will be empty.
 *
 * @throws IOException if an input/output error occurs
 *//*  ww  w.  ja v a  2  s .c o  m*/
protected void readIgnore() throws IOException {

    // Was an ignore file specified?
    saveIgnore.clear();
    if (ignore == null) {
        return;
    }

    // Create a connection to receive the ignore file contents
    URL url = new URL("http", host, port, ignore);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setAllowUserInteraction(false);
    conn.setDoInput(true);
    conn.setDoOutput(false);
    conn.setFollowRedirects(true);
    conn.setRequestMethod("GET");

    // Connect to the server and retrieve the ignore file
    conn.connect();
    InputStream is = conn.getInputStream();
    while (true) {
        String line = read(is);
        if (line == null) {
            break;
        }
        saveIgnore.add(line);
    }
    is.close();
    conn.disconnect();

}

From source file:org.openspaces.pu.container.servicegrid.deploy.Deploy.java

private void uploadPU(String puPath, File puFile) throws IOException {
    if (puFile.length() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(
                "File " + puFile.getPath() + " is too big: " + puFile.length() + " bytes");
    }/*from   ww  w .  j a  va  2s.co  m*/
    byte[] buffer = new byte[4098];
    String codebase = getCodebase(deployAdmin);
    info("Uploading [" + puPath + "] " + "[" + puFile.getPath() + "] to [" + codebase + "]");
    HttpURLConnection conn = (HttpURLConnection) new URL(codebase + puFile.getName()).openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setAllowUserInteraction(false);
    conn.setUseCaches(false);
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Extract", "true");
    //Sets the Content-Length request property
    //And disables buffering of file in memory (pure streaming)
    conn.setFixedLengthStreamingMode((int) puFile.length());
    conn.connect();
    OutputStream out = new BufferedOutputStream(conn.getOutputStream());
    InputStream in = new BufferedInputStream(new FileInputStream(puFile));
    int byteCount = 0;
    int bytesRead = -1;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
        byteCount += bytesRead;
    }
    out.flush();
    out.close();
    in.close();

    int responseCode = conn.getResponseCode();

    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    StringBuffer sb = new StringBuffer();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    conn.disconnect();
    if (responseCode != 200 && responseCode != 201) {
        throw new RuntimeException(
                "Failed to upload file, response code [" + responseCode + "], response: " + sb.toString());
    }
}

From source file:org.opennms.xmlclient.BasicHttpMethods.java

/**
 * Sends an HTTP DELETE request to a url
 * endpoint - The server's address//from ww  w  . j  av  a  2 s .c  o m
 * output - writes the server's response to output
 * @throws Exception
 */
public void deleteData(URL endpoint, Writer output, String username, String password) throws Exception {

    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();

        try {
            conn.setRequestMethod("DELETE");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support DELETE??", e);
        }

        // set username and password 
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/xml; charset=" + "UTF-8");

        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.opennms.xmlclient.BasicHttpMethods.java

/**
 * sends data to a server via PUT request.
 * data - The data you want to send//from  w w w .j  a va  2 s  .c  o  m
 * endpoint - The server's address
 * output - writes the server's response to output
 * @throws Exception
 */
public void putData(Reader data, URL endpoint, Writer output, String username, String password)
        throws Exception {

    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();

        try {
            conn.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support PUT??", e);
        }

        // set username and password 
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=" + "UTF-8");

        OutputStream out = conn.getOutputStream();

        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while putting data", e);
        } finally {
            if (out != null)
                out.close();
        }

        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.opennms.xmlclient.BasicHttpMethods.java

/**
 * Reads data from the data reader and posts it to a server via POST request.
 * data - The data you want to send/*from   w w  w. j  a v  a2s . co  m*/
 * endpoint - The server's address
 * output - writes the server's response to output
 * @throws Exception
 */
public void postData(Reader data, URL endpoint, Writer output, String username, String password)
        throws Exception {
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();

        try {
            conn.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }

        // set username and password 
        // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html
        String userPassword = username + ":" + password;
        // Encode String
        // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder()
        byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes());
        String authStringEnc = new String(encoding);
        log.debug("Base64 encoded auth string: '" + authStringEnc + "'");
        conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "application/xml; charset=" + "UTF-8");

        OutputStream out = conn.getOutputStream();

        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            pipe(data, writer);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while posting data", e);
        } finally {
            if (out != null)
                out.close();
        }

        InputStream in = conn.getInputStream();
        try {
            Reader reader = new InputStreamReader(in);
            pipe(reader, output);
            reader.close();
        } catch (IOException e) {
            throw new Exception("IOException while reading response", e);
        } finally {
            if (in != null)
                in.close();
        }

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.docdoku.client.data.MainModel.java

private void downloadFileWithServlet(Component pParent, File pLocalFile, String pURL) throws IOException {
    System.out.println("Downloading file from servlet");
    ProgressMonitorInputStream in = null;
    OutputStream out = null;/*from w w  w . j  ava 2  s  .c o m*/
    HttpURLConnection conn = null;
    try {
        //Hack for NTLM proxy
        //perform a head method to negociate the NTLM proxy authentication
        performHeadHTTPMethod(pURL);

        out = new BufferedOutputStream(new FileOutputStream(pLocalFile), Config.BUFFER_CAPACITY);
        URL url = new URL(pURL);
        conn = (HttpURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestMethod("GET");
        byte[] encoded = org.apache.commons.codec.binary.Base64
                .encodeBase64((getLogin() + ":" + getPassword()).getBytes("ISO-8859-1"));
        conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII"));
        conn.connect();
        int code = conn.getResponseCode();
        System.out.println("Download HTTP response code: " + code);
        in = new ProgressMonitorInputStream(pParent, I18N.BUNDLE.getString("DownloadMsg_part1"),
                new BufferedInputStream(conn.getInputStream(), Config.BUFFER_CAPACITY));
        ProgressMonitor pm = in.getProgressMonitor();
        pm.setMaximum(conn.getContentLength());
        byte[] data = new byte[Config.CHUNK_SIZE];
        int length;
        while ((length = in.read(data)) != -1) {
            out.write(data, 0, length);
        }
        out.flush();
    } finally {
        out.close();
        in.close();
        conn.disconnect();
    }
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Reads data from the data stream and posts it to solr,
 * writes to the response to output//from  w ww .j av a  2s.c  om
 * @return true if success
 */
public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) {
    if (mockMode)
        return true;
    boolean success = true;
    if (type == null)
        type = DEFAULT_CONTENT_TYPE;
    HttpURLConnection urlc = null;
    try {
        try {
            urlc = (HttpURLConnection) url.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", type);
            if (url.getUserInfo() != null) {
                String encoding = DatatypeConverter
                        .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII));
                urlc.setRequestProperty("Authorization", "Basic " + encoding);
            }
            if (null != length)
                urlc.setFixedLengthStreamingMode(length);
            urlc.connect();
        } catch (IOException e) {
            fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
            success = false;
        }

        try (final OutputStream out = urlc.getOutputStream()) {
            pipe(data, out);
        } catch (IOException e) {
            fatal("IOException while posting data: " + e);
            success = false;
        }

        try {
            success &= checkResponseCode(urlc);
            try (final InputStream in = urlc.getInputStream()) {
                pipe(in, output);
            }
        } catch (IOException e) {
            warn("IOException while reading response: " + e);
            success = false;
        }
    } finally {
        if (urlc != null)
            urlc.disconnect();
    }
    return success;
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * @param replica host and port of replica to connect to
 * @param path URL to access (relative to context root)
 * @param method HTTP method to use/*from ww  w .  j a  v a  2 s  .  c  o  m*/
 * @param doOutput if true, will need to write data into the request body
 * @param chunkedStreaming if true, use chunked streaming to accommodate a large upload, if possible
 * @param requestProperties additional request key/value pairs or {@code null} for none
 */
private HttpURLConnection buildConnectionToReplica(HostAndPort replica, String path, String method,
        boolean doOutput, boolean chunkedStreaming, Map<String, String> requestProperties) throws IOException {
    String contextPath = config.getContextPath();
    if (contextPath != null) {
        path = '/' + contextPath + path;
    }
    String protocol = config.isSecure() ? "https" : "http";
    URL url;
    try {
        url = new URL(protocol, replica.getHostText(), replica.getPort(), path);
    } catch (MalformedURLException mue) {
        // can't happen
        throw new IllegalStateException(mue);
    }
    log.debug("{} {}", method, url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoInput(true);
    connection.setDoOutput(doOutput);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty(HttpHeaders.ACCEPT, DESIRED_RESPONSE_CONTENT_TYPE);
    if (closeConnection) {
        connection.setRequestProperty(HttpHeaders.CONNECTION, "close");
    }
    if (chunkedStreaming) {
        if (needAuthentication) {
            // Must buffer in memory if using authentication since it won't handle the authorization challenge
            log.debug("Authentication is enabled, so ingest data must be buffered in memory");
        } else {
            connection.setChunkedStreamingMode(0); // Use default buffer size
        }
    }
    if (requestProperties != null) {
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    return connection;
}

From source file:com.sun.faces.systest.ant.SystestClient.java

/**
 * Execute the test via use of an HttpURLConnection.
 *
 * @throws BuildException if an exception occurs
 *//*from  w ww  . ja va 2s.co  m*/
protected void executeHttp() throws BuildException {

    // Construct a summary of the request we will be sending
    String summary = "[" + method + " " + request + "]";
    boolean success = true;
    String result = null;
    Throwable throwable = null;
    HttpURLConnection conn = null;

    try {

        // Configure an HttpURLConnection for this request
        if (log.isDebugEnabled()) {
            log.debug("Configuring HttpURLConnection for this request");
        }
        URL url = new URL("http", host, port, request);
        conn = (HttpURLConnection) url.openConnection();
        conn.setAllowUserInteraction(false);
        conn.setDoInput(true);
        if (inContent != null) {
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + inContent.length());
            if (log.isTraceEnabled()) {
                log.trace("INPH: Content-Length: " + inContent.length());
            }
        } else {
            conn.setDoOutput(false);
        }

        // Send the session id cookie (if any)
        if (joinSession && (sessionId != null)) {
            conn.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
            if (log.isTraceEnabled()) {
                log.trace("INPH: Cookie: JSESSIONID=" + sessionId);
            }
        }

        if (this.redirect && log.isTraceEnabled()) {
            log.trace("FLAG: setInstanceFollowRedirects(" + this.redirect + ")");
        }
        conn.setInstanceFollowRedirects(this.redirect);
        conn.setRequestMethod(method);
        if (inHeaders != null) {
            String headers = inHeaders;
            while (headers.length() > 0) {
                int delimiter = headers.indexOf("##");
                String header = null;
                if (delimiter < 0) {
                    header = headers;
                    headers = "";
                } else {
                    header = headers.substring(0, delimiter);
                    headers = headers.substring(delimiter + 2);
                }
                int colon = header.indexOf(":");
                if (colon < 0)
                    break;
                String name = header.substring(0, colon).trim();
                String value = header.substring(colon + 1).trim();
                conn.setRequestProperty(name, value);
                if (log.isTraceEnabled()) {
                    log.trace("INPH: " + name + ": " + value);
                }
            }
        }

        // Connect to the server and send our output if necessary
        conn.connect();
        if (inContent != null) {
            if (log.isTraceEnabled()) {
                log.trace("INPD: " + inContent);
            }
            OutputStream os = conn.getOutputStream();
            for (int i = 0, length = inContent.length(); i < length; i++)
                os.write(inContent.charAt(i));
            os.close();
        }

        // Acquire the response data, if there is any
        String outData = "";
        String outText = "";
        boolean eol = false;
        InputStream is = conn.getInputStream();
        int lines = 0;
        while (true) {
            String line = read(is);
            if (line == null)
                break;
            if (lines == 0)
                outData = line;
            else
                outText += line + "\r\n";
            saveResponse.add(line);
            lines++;
        }
        is.close();

        // Dump out the response stuff
        if (log.isTraceEnabled()) {
            log.trace("RESP: " + conn.getResponseCode() + " " + conn.getResponseMessage());
        }
        for (int i = 1; i < 1000; i++) {
            String name = conn.getHeaderFieldKey(i);
            String value = conn.getHeaderField(i);
            if ((name == null) || (value == null))
                break;
            if (log.isTraceEnabled()) {
                log.trace("HEAD: " + name + ": " + value);
            }
            save(name, value);
            if ("Set-Cookie".equals(name))
                parseSession(value);
        }
        if (log.isTraceEnabled()) {
            log.trace("DATA: " + outData);
            if (outText.length() > 2) {
                log.trace("TEXT: " + outText);
            }
        }

        // Validate the response against our criteria
        if (success) {
            result = validateStatus(conn.getResponseCode());
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateMessage(conn.getResponseMessage());
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateHeaders();
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateData(outData);
            if (result != null)
                success = false;
        }
        if (success) {
            result = validateGolden();
            if (result != null)
                success = false;
        }

    } catch (Throwable t) {
        if (t instanceof FileNotFoundException) {
            if (status == 404) {
                success = true;
                result = "Not Found";
                throwable = null;
            } else {
                success = false;
                try {
                    result = "Status=" + conn.getResponseCode() + ", Message=" + conn.getResponseMessage();
                } catch (IOException e) {
                    result = e.toString();
                }
                throwable = null;
            }
        } else if (t instanceof ConnectException) {
            success = false;
            result = t.getMessage();
            throwable = null;
        } else {
            success = false;
            result = t.getMessage();
            throwable = t;
        }
    }

    // Log the results of executing this request
    if (success) {
        System.out.println("OK   " + summary);
    } else {
        System.out.println("FAIL " + summary + " " + result);
        if (throwable != null)
            throwable.printStackTrace(System.out);
        if (failonerror) {
            if (throwable != null) {
                throw new BuildException("System test failed", throwable);
            } else {
                throw new BuildException("System test failed");
            }
        }
    }

}