Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

In this page you can find the example usage for java.net URLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java

private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception {
    // Get the url...
    String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL);

    // add GET parameters to the urlString...
    Iterator<String> i = parametersMap.keySet().iterator();

    String div = "?";
    URL url = new URL(urlString);
    if (url.getQuery() != null)
        div = "&";

    while (i.hasNext()) {
        String keyName = "" + i.next();
        if (keyName.startsWith("XML_GET_PARAM_")) {
            String paramName = keyName.substring("XML_GET_PARAM_".length());
            String value = (String) getParameterValue(keyName);

            urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
            div = "&";
        }//from   ww w .  j av  a 2  s .  c  o m
    }

    url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("file")) {
        // do nothing
        return JRXmlUtils.parse(url.openStream());
    } else if (url.getProtocol().toLowerCase().equals("http")
            || url.getProtocol().toLowerCase().equals("https")) {
        String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME);
        String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD);

        if (url.getProtocol().toLowerCase().equals("https")) {
            JRPropertiesUtil dPROP = PropertiesHelper.DPROP;
            String socketFactory = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory");
            if (socketFactory == null) {
                socketFactory = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory");
            }

            if (socketFactory != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultSSLSocketFactory(
                        (SSLSocketFactory) Class.forName(socketFactory).newInstance());
            } else {
                log.debug("No SSLSocketFactory defined, using default");
            }

            String hostnameVerifyer = dPROP
                    .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier");
            if (hostnameVerifyer == null) {
                hostnameVerifyer = dPROP.getProperty(
                        "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier");
            }

            if (hostnameVerifyer != null) {
                // setSSLSocketFactory
                HttpsURLConnection.setDefaultHostnameVerifier(
                        (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance());
            } else {
                log.debug("No HostnameVerifier defined, using default");
            }
        }

        URLConnection conn = url.openConnection();

        if (username != null && username.length() > 0 && password != null) {
            ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes());
            ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
            Base64Encoder enc = new Base64Encoder(bytesIn, dataOut);
            enc.process();
            String encoding = dataOut.toString();
            conn.setRequestProperty("Authorization", "Basic " + encoding);
        }

        // add POST parameters to the urlString...
        i = parametersMap.keySet().iterator();

        String data = "";
        div = "";
        while (i.hasNext()) {
            String keyName = "" + i.next();
            if (keyName.startsWith("XML_POST_PARAM_")) {
                String paramName = keyName.substring("XML_POST_PARAM_".length());
                String value = (String) getParameterValue(keyName);
                data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
                div = "&";
            }
        }

        conn.setDoOutput(true);

        if (data.length() > 0) {
            conn.setDoInput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
        }

        try {
            return XMLUtils.parseNoValidation(conn.getInputStream());
        } catch (SAXException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (IOException e) {
            throw new JRException("Failed to parse the xml document", e);
        } catch (ParserConfigurationException e) {
            throw new JRException("Failed to create a document builder factory", e);
        }

        // return JRXmlUtils.parse(conn.getInputStream());
    } else {
        throw new JRException("URL protocol not supported");
    }
}

From source file:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {/*from   w w  w. ja  v  a 2s  .  c  om*/
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}

From source file:org.apache.jsp.communities_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);

      try {/*from w ww  . ja  va 2  s  . c o  m*/
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          URL url = new URL(API_ROOT + addr);
          URLConnection urlConnection = url.openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              urlConnection.setDoInput(true);
              urlConnection.setDoOutput(true);
              urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
          }
          IOUtils.copy(urlConnection.getInputStream(), output);
          String newCookie = getConnectionInfiniteCookie(urlConnection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
          return output.toString();
      } catch (IOException e) {
          System.out.println(e.getMessage());
          return null;
      }
  }

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doAnalytics(String analytics, String event, String pageURL, String resourcePath,
        String resourceType) {/*from  ww  w  .  j  av a 2  s  .  co m*/

    if (analytics != null && pageURL != null && resourcePath != null && resourceType != null && event != null) {

        URLConnection urlConn = null;
        DataOutputStream printout = null;
        BufferedReader input = null;
        String tmp = null;
        try {

            URL pageurl = new URL(pageURL);
            StringBuffer sb = new StringBuffer(
                    "<?xml version=1.0 encoding=UTF-8?><request><sc_xml_ver>1.0</sc_xml_ver>");
            sb.append("<events>" + event + "</events>");
            sb.append("<pageURL>" + pageURL + "</pageURL>");
            sb.append("<pageName>"
                    + pageurl.getPath().substring(1, pageurl.getPath().indexOf(".")).replaceAll("/", ":")
                    + "</pageName>");
            sb.append("<evar1>" + resourcePath + "</evar1>");
            sb.append("<evar2>" + resourceType + "</evar2>");
            sb.append("<visitorID>demomachine</visitorID>");
            sb.append("<reportSuiteID>" + analytics.substring(0, analytics.indexOf(".")) + "</reportSuiteID>");
            sb.append("</request>");

            logger.debug("New Analytics Event: " + sb.toString());

            URL sitecaturl = new URL("http://" + analytics);

            urlConn = sitecaturl.openConnection();
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            printout = new DataOutputStream(urlConn.getOutputStream());

            printout.writeBytes(sb.toString());
            printout.flush();
            printout.close();

            input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((tmp = input.readLine()))) {
                logger.debug(tmp);
            }
            printout.close();
            input.close();

        } catch (Exception ex) {

            logger.error(ex.getMessage());

        }

    }

}

From source file:org.apache.jsp.communities_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
          HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);
      String result = "";
      try {//from   w  w w . j  a v  a2s  .c  om
          URLConnection connection = new URL(API_ROOT + addr).openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              connection.setDoInput(true);
          }
          connection.setDoOutput(true);
          connection.setRequestProperty("Accept-Charset", "UTF-8");

          // Post JSON string to URL
          OutputStream os = connection.getOutputStream();
          byte[] b = data.getBytes("UTF-8");
          os.write(b);

          // Receive results back from API
          InputStream is = connection.getInputStream();
          result = IOUtils.toString(is, "UTF-8");

          String newCookie = getConnectionInfiniteCookie(connection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
      } catch (Exception e) {
          //System.out.println("Exception: " + e.getMessage());
      }
      return result;
  }

From source file:org.apache.jsp.sources_jsp.java

public String callRestfulApi(String addr, HttpServletRequest request, HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);

       try {/*from   w  w  w  .j av  a2s  . co  m*/
           ByteArrayOutputStream output = new ByteArrayOutputStream();
           URL url = new URL(API_ROOT + addr);
           URLConnection urlConnection = url.openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               urlConnection.setDoInput(true);
               urlConnection.setDoOutput(true);
               urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
           }
           IOUtils.copy(urlConnection.getInputStream(), output);
           String newCookie = getConnectionInfiniteCookie(urlConnection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
           return output.toString();
       } catch (IOException e) {
           System.out.println(e.getMessage());
           return null;
       }
   }

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

private void checkForUpdates() {
    URL url = null;//from   w w  w. j a  v  a 2 s. co m
    URLConnection urlConn = null;
    BufferedReader br = null;
    logger.info("Checking for updates...");

    try {
        url = new URL("http://www.itemanalysis.com/version/jmetrik-version.txt");
        urlConn = url.openConnection();

        urlConn.setDoInput(true);
        urlConn.setUseCaches(false);

        br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String s = "";
        String[] availableVersion = null;
        String[] currentVersion = VERSION.split("\\.");
        int needUpdate = 0;

        while ((s = br.readLine()) != null) {
            availableVersion = s.trim().split("\\.");
        }
        br.close();

        if (currentVersion.length < availableVersion.length) {
            needUpdate++;
        }

        for (int i = 0; i < currentVersion.length; i++) {
            if (Integer.parseInt(currentVersion[i].trim()) < Integer.parseInt(availableVersion[i].trim())) {
                needUpdate++;
            }
        }
        if (needUpdate > 0 && !BETA_VERSION) {
            showUpdateResults(needUpdate > 0);
            logger.info(
                    "jMetrik updates available. Please go to www.ItemAnalysis.com and download the new version.");
        } else {
            logger.info("No updates available. You have the most current version of jMetrik.");
        }

    } catch (MalformedURLException ex) {
        logger.fatal("Could not access update information: MalformedURLException");
    } catch (IOException ex) {
        logger.fatal("Could not access update information: IOException");
    }
}

From source file:org.apache.jsp.sources_jsp.java

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
           HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);
       String result = "";
       try {/*from   ww w .  ja  va2  s.c  o  m*/
           URLConnection connection = new URL(API_ROOT + addr).openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               connection.setDoInput(true);
           }
           connection.setDoOutput(true);
           connection.setRequestProperty("Accept-Charset", "UTF-8");

           // Post JSON string to URL
           OutputStream os = connection.getOutputStream();
           byte[] b = data.getBytes("UTF-8");
           os.write(b);

           // Receive results back from API
           InputStream is = connection.getInputStream();
           result = IOUtils.toString(is, "UTF-8");

           String newCookie = getConnectionInfiniteCookie(connection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
       } catch (Exception e) {
           //System.out.println("Exception: " + e.getMessage());
       }
       return result;
   }

From source file:com.techventus.server.voice.Voice.java

/**
 * Executes the enable/disable action with the provided url params.
 *
 * @param paraString the URL Parameters (encoded), ie ?auth=3248sdf7234&enable=0&phoneId=1&enable=1&phoneId=2&_rnr_se=734682ghdsf
 * @return the raw response of the disable action.
 * @throws IOException Signals that an I/O exception has occurred.
 */// w  ww  . j ava 2s. c  o  m
private String phonesEnableDisableApply(String paraString) throws IOException {
    String out = "";

    // POST /voice/call/connect/ outgoingNumber=[number to
    // call]&forwardingNumber=[forwarding
    // number]&subscriberNumber=undefined&remember=0&_rnr_se=[pull from
    // page]

    //
    if (PRINT_TO_CONSOLE)
        System.out.println(phoneEnableURLString);
    if (PRINT_TO_CONSOLE)
        System.out.println(paraString);
    URL requestURL = new URL(phoneEnableURLString);

    URLConnection conn = requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";

    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;

}

From source file:com.techventus.server.voice.Voice.java

/**
 * Enables/disables the call Announcement setting (general for all phones).
 *
 * @param announceCaller <br/>//from   w  w w .j av  a2s  .co m
 * true Announces caller's name and gives answering options <br/>
 * false Directly connects calls when phones are answered
 * @return the raw response of the disable action.
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String setCallPresentation(boolean announceCaller) throws IOException {
    String out = "";

    URL requestURL = new URL(generalSettingsURLString);
    /** 0 for enable, 1 for disable **/
    String announceCallerStr = "";

    if (announceCaller) {
        announceCallerStr = "0";
        if (PRINT_TO_CONSOLE)
            System.out.println("Turning caller announcement on.");
    } else {
        announceCallerStr = "1";
        if (PRINT_TO_CONSOLE)
            System.out.println("Turning caller announcement off.");
    }

    String paraString = "";
    paraString += URLEncoder.encode("directConnect", enc) + "=" + URLEncoder.encode(announceCallerStr, enc);
    paraString += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);

    URLConnection conn = requestURL.openConnection();
    conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
    conn.setRequestProperty("User-agent", USER_AGENT);

    conn.setDoOutput(true);
    conn.setDoInput(true);

    OutputStreamWriter callwr = new OutputStreamWriter(conn.getOutputStream());
    callwr.write(paraString);
    callwr.flush();

    BufferedReader callrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
        out += line + "\n\r";
    }

    callwr.close();
    callrd.close();

    if (out.equals("")) {
        throw new IOException("No Response Data Received.");
    }

    return out;
}