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:org.jclouds.http.internal.JavaUrlHttpCommandExecutorService.java

@Override
protected HttpURLConnection convert(HttpRequest request) throws IOException {
    URL url = request.getEndpoint().toURL();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (relaxHostname && connection instanceof HttpsURLConnection) {
        HttpsURLConnection sslCon = (HttpsURLConnection) connection;
        sslCon.setHostnameVerifier(new LogToMapHostnameVerifier());
    }//w w  w.j ava2 s  .co  m
    connection.setDoOutput(true);
    connection.setAllowUserInteraction(false);
    // do not follow redirects since https redirects don't work properly
    // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be
    // <adriancole.s3int0.s3-external-3.amazonaws.com>
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod(request.getMethod().toString());
    for (String header : request.getHeaders().keySet()) {
        for (String value : request.getHeaders().get(header)) {
            connection.setRequestProperty(header, value);

            if ("Transfer-Encoding".equals(header) && "chunked".equals(value)) {
                connection.setChunkedStreamingMode(8192);
            }
        }
    }
    connection.setRequestProperty(HttpHeaders.HOST, request.getEndpoint().getHost());
    if (request.getEntity() != null) {
        OutputStream out = connection.getOutputStream();
        try {
            if (request.getEntity() instanceof String) {
                OutputStreamWriter writer = new OutputStreamWriter(out);
                writer.write((String) request.getEntity());
                writer.close();
            } else if (request.getEntity() instanceof InputStream) {
                IOUtils.copy((InputStream) request.getEntity(), out);
            } else if (request.getEntity() instanceof File) {
                IOUtils.copy(new FileInputStream((File) request.getEntity()), out);
            } else if (request.getEntity() instanceof byte[]) {
                IOUtils.write((byte[]) request.getEntity(), out);
            } else {
                throw new UnsupportedOperationException(
                        "Content not supported " + request.getEntity().getClass());
            }
        } finally {
            IOUtils.closeQuietly(out);
        }
    } else {
        connection.setRequestProperty(HttpHeaders.CONTENT_LENGTH, "0");
    }
    return connection;
}

From source file:org.vfny.geoserver.wfs.servlets.TestWfsPost.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www . j a  v  a2 s.  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 *
 * @throws ServletException DOCUMENT ME!
 * @throws IOException DOCUMENT ME!
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestString = request.getParameter("body");
    String urlString = request.getParameter("url");
    boolean doGet = (requestString == null) || requestString.trim().equals("");

    if ((urlString == null)) {
        PrintWriter out = response.getWriter();
        StringBuffer urlInfo = request.getRequestURL();

        if (urlInfo.indexOf("?") != -1) {
            urlInfo.delete(urlInfo.indexOf("?"), urlInfo.length());
        }

        String geoserverUrl = urlInfo.substring(0, urlInfo.indexOf("/", 8)) + request.getContextPath();
        response.setContentType("text/html");
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>TestWfsPost</title>");
        out.println("</head>");
        out.println("<script language=\"JavaScript\">");
        out.println("function doNothing() {");
        out.println("}");
        out.println("function sendRequest() {");
        out.println("  if (checkURL()==true) {");
        out.print("    document.frm.action = \"");
        out.print(urlInfo.toString());
        out.print("\";\n");
        out.println("    document.frm.target = \"_blank\";");
        out.println("    document.frm.submit();");
        out.println("  }");
        out.println("}");
        out.println("function checkURL() {");
        out.println("  if (document.frm.url.value==\"\") {");
        out.println("    alert(\"Please give URL before you sumbit this form!\");");
        out.println("    return false;");
        out.println("  } else {");
        out.println("    return true;");
        out.println("  }");
        out.println("}");
        out.println("function clearRequest() {");
        out.println("document.frm.body.value = \"\";");
        out.println("}");
        out.println("</script>");
        out.println("<body>");
        out.println("<form name=\"frm\" action=\"JavaScript:doNothing()\" method=\"POST\">");
        out.println("<table align=\"center\" cellspacing=\"2\" cellpadding=\"2\" border=\"0\">");
        out.println("<tr>");
        out.println("<td><b>URL:</b></td>");
        out.print("<td><input name=\"url\" value=\"");
        out.print(geoserverUrl);
        out.print("/wfs/GetFeature\" size=\"70\" MAXLENGTH=\"100\"/></td>\n");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td><b>Request:</b></td>");
        out.println("<td><textarea cols=\"60\" rows=\"24\" name=\"body\"></textarea></td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("<table align=\"center\">");
        out.println("<tr>");
        out.println("<td><input type=\"button\" value=\"Clear\" onclick=\"clearRequest()\"></td>");
        out.println("<td><input type=\"button\" value=\"Submit\" onclick=\"sendRequest()\"></td>");
        out.println("<td></td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
        out.close();
    } else {
        response.setContentType("application/xml");

        BufferedReader xmlIn = null;
        PrintWriter xmlOut = null;
        StringBuffer sbf = new StringBuffer();
        String resp = null;

        try {
            URL u = new URL(urlString);
            java.net.HttpURLConnection acon = (java.net.HttpURLConnection) u.openConnection();
            acon.setAllowUserInteraction(false);

            if (!doGet) {
                //System.out.println("set to post");
                acon.setRequestMethod("POST");
                acon.setRequestProperty("Content-Type", "application/xml");
            } else {
                //System.out.println("set to get");
                acon.setRequestMethod("GET");
            }

            acon.setDoOutput(true);
            acon.setDoInput(true);
            acon.setUseCaches(false);

            //SISfixed - if there was authentication info in the request,
            //           Pass it along the way to the target URL
            //DJB: applied patch in GEOS-335
            String authHeader = request.getHeader("Authorization");

            String username = request.getParameter("username");

            if ((username != null) && !username.trim().equals("")) {
                String password = request.getParameter("password");
                String up = username + ":" + password;
                byte[] encoded = Base64.encodeBase64(up.getBytes());
                authHeader = "Basic " + new String(encoded);
            }

            if (authHeader != null) {
                acon.setRequestProperty("Authorization", authHeader);
            }

            if (!doGet) {
                xmlOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(acon.getOutputStream())));
                xmlOut = new java.io.PrintWriter(acon.getOutputStream());

                xmlOut.write(requestString);
                xmlOut.flush();
            }

            // Above 400 they're all error codes, see:
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
            if (acon.getResponseCode() >= 400) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println("HTTP response: " + acon.getResponseCode() + "\n"
                        + URLDecoder.decode(acon.getResponseMessage(), "UTF-8"));
                out.println("</servlet-exception>");
                out.close();
            } else {
                // xmlIn = new BufferedReader(new InputStreamReader(
                // acon.getInputStream()));
                // String line;

                // System.out.println("got encoding from acon: "
                // + acon.getContentType());
                response.setContentType(acon.getContentType());
                response.setHeader("Content-disposition", acon.getHeaderField("Content-disposition"));

                OutputStream output = response.getOutputStream();
                int c;
                InputStream in = acon.getInputStream();

                while ((c = in.read()) != -1)
                    output.write(c);

                in.close();
                output.close();
            }

            //while ((line = xmlIn.readLine()) != null) {
            //    out.print(line);
            //}
        } catch (Exception e) {
            PrintWriter out = response.getWriter();
            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<servlet-exception>");
            out.println(e.toString());
            out.println("</servlet-exception>");
            out.close();
        } finally {
            try {
                if (xmlIn != null) {
                    xmlIn.close();
                }
            } catch (Exception e1) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println(e1.toString());
                out.println("</servlet-exception>");
                out.close();
            }

            try {
                if (xmlOut != null) {
                    xmlOut.close();
                }
            } catch (Exception e2) {
                PrintWriter out = response.getWriter();
                out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                out.println("<servlet-exception>");
                out.println(e2.toString());
                out.println("</servlet-exception>");
                out.close();
            }
        }
    }
}

From source file:com.adr.taskexecutor.ui.TaskExecutorRemote.java

@Override
public void run(TaskExecutor.RunProcess ui) throws Exception {

    URL url;/*from ww w.  j a va 2  s .c om*/
    BufferedReader readerin = null;
    Writer writerout = null;
    try {
        // http://localhost:8084/taskexecutor/executetask?parameter=&loglevel=INFO&trace=false&stats=true&task=
        url = new URL(jURL.getText());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        String query = "&parameter=" + URLEncoder.encode(parameter, "UTF-8");
        query += "&task=" + URLEncoder.encode(task, "UTF-8");
        query += "&language=" + URLEncoder.encode(language, "UTF-8");
        query += "&loglevel=" + URLEncoder.encode(jLoggingLevel.getSelectedItem().toString(), "UTF-8");
        query += "&trace=" + URLEncoder.encode(Boolean.toString(jTrace.isSelected()), "UTF-8");
        query += "&stats=" + URLEncoder.encode(Boolean.toString(jStats.isSelected()), "UTF-8");

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write("Content-Type: application/x-www- form-urlencoded,encoding=UTF-8\n");
        writerout.write("Content-length: " + String.valueOf(query.length()) + "\n");
        writerout.write("\n");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONParser jsonp = new JSONParser();
            JSONObject json = (JSONObject) jsonp.parse(text.toString());

            // Print lines
            JSONArray jsonlines = (JSONArray) json.get("lines");
            for (Object l : jsonlines) {
                JSONObject jsonline = (JSONObject) l;
                Object type = jsonline.get("type");
                if ("build".equals(type)) {
                    ui.buildMessage((String) jsonline.get("text"));
                } else if ("run".equals(type)) {
                    ui.runMessage((String) jsonline.get("text"));
                } else if ("out".equals(type)) {
                    ui.printOut((String) jsonline.get("text"));
                } else if ("log".equals(type)) {
                    ui.printLog((String) jsonline.get("text"));
                } else if ("success".equals(type)) {
                    ui.successMessage(((Number) jsonline.get("time")).longValue());
                } else if ("fail".equals(type)) {
                    ui.failMessage((String) jsonline.get("text"), ((Number) jsonline.get("time")).longValue());
                } else if ("exception".equals(type)) {
                    ui.exceptionMessage((String) jsonline.get("text"),
                            ((Number) jsonline.get("time")).longValue());
                }
            }

            // Print stats
            ui.getStatsModel().reset();
            JSONArray jsonstats = (JSONArray) json.get("stats");
            if (jsonstats != null) {
                for (Object l : jsonstats) {
                    JSONObject jsonstat = (JSONObject) l;
                    ui.getStatsModel().addRow((String) jsonstat.get("task"), (String) jsonstat.get("step"),
                            ((Number) jsonstat.get("executions")).intValue(),
                            ((Number) jsonstat.get("records")).intValue(),
                            ((Number) jsonstat.get("rejected")).intValue(),
                            ((Number) jsonstat.get("totaltime")).doubleValue(),
                            ((Number) jsonstat.get("avgtime")).doubleValue());
                }
            }

            // save preferences if execution went well
            Configuration.getInstance().setPreference("remote.serverurl", jURL.getText());
            Configuration.getInstance().setPreference("remote.logginglevel",
                    jLoggingLevel.getSelectedItem().toString());
            Configuration.getInstance().setPreference("remote.trace", Boolean.toString(jTrace.isSelected()));
            Configuration.getInstance().setPreference("remote.stats", Boolean.toString(jStats.isSelected()));
            Configuration.getInstance().flushPreferences();

            //                 } catch (NullPointerException ex) {
            //                 } catch (ClassCastException ex) {
            //                 } catch (ParseException ex) {
        } else {
            throw new IOException(MessageFormat.format(bundle.getString("message.httperror"),
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
        //        } catch (MalformedURLException ex) {
        //        } catch (IOException ex) {
    } finally {
        if (writerout != null) {
            try {
                writerout.close();
            } catch (IOException ex) {
            }
            writerout = null;
        }
        if (readerin != null) {
            try {
                readerin.close();
            } catch (IOException ex) {
            }
            readerin = null;
        }
    }
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Prepares a connection to the server.//  w  ww. j  av a2s .c  o  m
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    con.setConnectTimeout(connectionTimeoutMillis);
    con.setReadTimeout(readTimeoutMillis);
    con.setAllowUserInteraction(false);
    con.setDefaultUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");

    // do stuff for ssl
    if (HttpsURLConnection.class.isInstance(con)) {
        HttpsURLConnection https = HttpsURLConnection.class.cast(con);
        if (hostNameVerifier != null) {
            https.setHostnameVerifier(hostNameVerifier);
        }
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    // add headers
    con.setRequestProperty("Content-Type", "application/json-rpc");
    for (Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : extraHeaders.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // return it
    return con;
}

From source file:TaxSvc.TaxSvc.java

public CancelTaxResult CancelTax(CancelTaxRequest req) {

    //Create URL/*from  www. j  a  va  2 s .  c  o m*/
    String taxget = svcURL + "/1.0/tax/cancel";
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);         //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //Note: tax/cancel will return a 200 response even if the document could not be cancelled. Special attention needs to be paid to the ResultCode.
        { //If we got a more serious error, print out the error message.
            CancelTaxResult res = mapper.readValue(conn.getErrorStream(), CancelTaxResult.class); //Deserialize response
            return res;
        } else {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            CancelTaxResponse res = mapper.readValue(conn.getInputStream(), CancelTaxResponse.class); //Deserialize response
            return res.CancelTaxResult;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:com.workfront.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }/*from  w  w w.j av a 2s.  c o m*/

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);

    return conn;
}

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL/*from  w ww .  j  av  a2s .c o  m*/
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:org.overlord.rtgov.activity.server.rest.client.RESTActivityServer.java

/**
 * This method retrieves the activity types associated with the supplied
 * query URL./*from   w  w w .j a  va2  s .  c o  m*/
 * 
 * @param queryUrl The query URL
 * @return The list of activity types
 * @throws Exception Failed to get activity types
 */
protected List<ActivityType> getActivityTypes(URL queryUrl) throws Exception {
    List<ActivityType> ret = null;

    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    initAuth(connection);

    connection.setRequestMethod("GET");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/json");

    java.io.InputStream is = connection.getInputStream();

    byte[] b = new byte[is.available()];
    is.read(b);

    ret = ActivityUtil.deserializeActivityTypeList(b);

    is.close();

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer getActivityTypes result: " + ret);
    }

    return (ret);
}

From source file:org.overlord.rtgov.activity.server.rest.client.RESTActivityServer.java

/**
 * {@inheritDoc}/*from  ww w .  j av a2  s.co  m*/
 */
public ActivityUnit getActivityUnit(String id) throws Exception {
    ActivityUnit ret = null;

    URL queryUrl = new URL(_serverURL + UNIT + "?id=" + id);

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer[" + queryUrl + "] getActivityUnit: " + id);
    }

    HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection();

    initAuth(connection);

    connection.setRequestMethod("GET");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/json");

    java.io.InputStream is = connection.getInputStream();

    byte[] b = new byte[is.available()];

    is.read(b);

    is.close();

    ret = ActivityUtil.deserializeActivityUnit(b);

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer getActivityUnit result: " + ret);
    }

    return (ret);
}

From source file:org.overlord.rtgov.activity.server.rest.client.RESTActivityServer.java

/**
 * {@inheritDoc}//from   w ww  . j  av  a2 s .  c  om
 */
public void store(List<ActivityUnit> activities) throws Exception {
    URL storeUrl = new URL(_serverURL + STORE);

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer[" + storeUrl + "] store: " + activities);
    }

    HttpURLConnection connection = (HttpURLConnection) storeUrl.openConnection();

    initAuth(connection);

    connection.setRequestMethod("POST");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/json");

    java.io.OutputStream os = connection.getOutputStream();

    os.write(ActivityUtil.serializeActivityUnitList(activities));

    os.flush();
    os.close();

    java.io.InputStream is = connection.getInputStream();

    byte[] b = new byte[is.available()];

    is.read(b);

    is.close();

    if (LOG.isLoggable(Level.FINER)) {
        LOG.finer("RESTActivityServer result: " + new String(b));
    }
}