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:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {/*from   w w w .jav a  2  s . c o  m*/
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRServerImpl.java

public ResponseType requestCall(RequestType request) {

    AutoCreate ac = new AutoCreate();
    ac.setRequest(request);//from   ww  w  .j  ava  2  s.  com

    ResponseType response = null;

    try {

        Marshaller marshaller = jaxbc.createMarshaller();
        Unmarshaller unmarshaller = jaxbc.createUnmarshaller();

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        marshaller.marshal(ac, byteStream);

        String xml = byteStream.toString();

        URL url = new URL(this.serverURL);
        URLConnection con = url.openConnection();

        con.setDoInput(true);
        con.setDoOutput(true);

        con.setRequestProperty("Content-Type", "text/xml");
        con.setRequestProperty("Content-transfer-encoding", "text");

        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());

        log.info("Sending request: " + xml);

        out.write(xml);
        out.flush();
        out.close();

        InputStream in = con.getInputStream();

        int len = 4096;
        byte[] buffer = new byte[len];
        int off = 0;
        int read = 0;
        while ((read = in.read(buffer, off, len)) != -1) {
            off += read;
            len -= off;
        }

        String responseText = new String(buffer, 0, off);

        log.debug("Received response: " + responseText);

        Object o = unmarshaller.unmarshal(new ByteArrayInputStream(responseText.getBytes()));

        if (o instanceof AutoCreate) {
            AutoCreate acr = (AutoCreate) o;
            response = acr.getResponse();
        }

    } catch (MalformedURLException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    } catch (JAXBException e) {
        log.error("", e);
    } finally {
        if (response == null) {
            response = new ResponseType();
            response.setStatus(StatusType.ERROR);
            response.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR);
            response.setErrorString("Unknown error occurred sending request to IVR server");
        }

    }
    return response;
}

From source file:CounterApp.java

public int getCount() throws Exception {
    java.net.URL url = new java.net.URL(servletURL);
    java.net.URLConnection con = url.openConnection();
    if (sessionCookie != null) {
        con.setRequestProperty("cookie", sessionCookie);
    }// ww w . ja  v  a2  s . c  o  m
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(byteOut);
    out.flush();
    byte buf[] = byteOut.toByteArray();
    con.setRequestProperty("Content-type", "application/octet-stream");
    con.setRequestProperty("Content-length", "" + buf.length);
    DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
    dataOut.write(buf);
    dataOut.flush();
    dataOut.close();
    DataInputStream in = new DataInputStream(con.getInputStream());
    int count = in.readInt();
    in.close();
    if (sessionCookie == null) {
        String cookie = con.getHeaderField("set-cookie");
        if (cookie != null) {
            sessionCookie = parseCookie(cookie);
            System.out.println("Setting session ID=" + sessionCookie);
        }
    }

    return count;
}

From source file:com.google.ie.common.util.ReCaptchaUtility.java

/**
 * /*  ww w  .j  a  v  a  2s  .  co  m*/
 * This method makes a post request to captcha server for verification of
 * captcha.
 * 
 * @param postUrl the url of the server
 * @param postParameters the parameters making the post request
 * @return String the message from the server in response to the request
 *         posted
 * @throws IOException
 */
private String sendPostRequest(String postUrl, String postParameters) throws IOException {
    OutputStream out = null;
    String message = null;
    InputStream in = null;
    try {
        URL url = new URL(postUrl);

        /* open connection with settings */
        URLConnection urlConnection = url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);

        /* open output stream */
        out = urlConnection.getOutputStream();
        out.write(postParameters.getBytes());
        out.flush();

        /* open input stream */
        in = urlConnection.getInputStream();

        /* get output */
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        while (true) {
            int rc = in.read(buf);
            if (rc <= 0)
                break;
            bout.write(buf, 0, rc);
        }
        message = bout.toString();
        /* close streams */
        out.close();
        in.close();
        return message;
    } catch (IOException e) {
        LOG.error("Cannot load URL: " + e.getMessage());
        out.close();
        in.close();
        return null;
    }
}

From source file:TSAClient.java

private byte[] getTSAResponse(byte[] request) throws IOException {
    LOG.debug("Opening connection to TSA server");

    // todo: support proxy servers
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);//from   w  w  w.j  a v a2  s  . co m
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type", "application/timestamp-query");

    LOG.debug("Established connection to TSA server");

    if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) {
        connection.setRequestProperty(username, password);
    }

    // read response
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(request);
    } finally {
        IOUtils.closeQuietly(output);
    }

    LOG.debug("Waiting for response from TSA server");

    InputStream input = null;
    byte[] response;
    try {
        input = connection.getInputStream();
        response = IOUtils.toByteArray(input);
    } finally {
        IOUtils.closeQuietly(input);
    }

    LOG.debug("Received response from TSA server");

    return response;
}

From source file:org.xframium.device.data.perfectoMobile.PerfectoMobileDataProvider.java

public List<Device> readData() {
    List<Device> deviceList = new ArrayList<Device>(10);
    try {/*w  w w.  j ava  2s.  c  om*/
        URL deviceURL = new URL("https://" + CloudRegistry.instance().getCloud().getHostName()
                + "/services/handsets?operation=list&user=" + CloudRegistry.instance().getCloud().getUserName()
                + "&password=" + CloudRegistry.instance().getCloud().getPassword());

        if (log.isInfoEnabled())
            log.info("Reading Devices from " + deviceURL.toString());

        URLConnection urlConnection = deviceURL.openConnection();
        urlConnection.setDoInput(true);

        InputStream inputStream = urlConnection.getInputStream();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputStream);

        NodeList handSets = doc.getElementsByTagName("handset");

        if (log.isInfoEnabled())
            log.info("Analysing handsets using [" + pmValidator.getClass().getSimpleName() + "]");

        boolean deviceFound = false;

        for (int i = 0; i < handSets.getLength(); i++) {

            if (pmValidator.validate(handSets.item(i))) {
                String driverName = "";
                switch (driverType) {
                case APPIUM:
                    String osType = getValue(handSets.item(i), "os");
                    if (osType.equals("iOS"))
                        driverName = "IOS";
                    else if (osType.equals("Android"))
                        driverName = "ANDROID";
                    else
                        throw new IllegalArgumentException(
                                "Appium is not supported on the following OS " + osType);
                    break;

                case PERFECTO:
                    driverName = "PERFECTO";
                    break;

                case WEB:
                    driverName = "WEB";
                    break;
                }

                deviceFound = true;
                deviceList.add(new SimpleDevice(getValue(handSets.item(i), "deviceId"),
                        getValue(handSets.item(i), "manufacturer"), getValue(handSets.item(i), "model"),
                        getValue(handSets.item(i), "os"), getValue(handSets.item(i), "osVersion"), null, null,
                        1, driverName, true, getValue(handSets.item(i), "deviceId")));
            }

        }

        if (!deviceFound)
            log.warn(pmValidator.getMessage());

        inputStream.close();
        return deviceList;

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

From source file:com.github.beat.signer.pdf_signer.TSAClient.java

private byte[] getTSAResponse(byte[] request) throws IOException {
    LOGGER.debug("Opening connection to TSA server");

    // FIXME: support proxy servers
    URLConnection connection = tsaInfo.getTsaUrl().openConnection();
    connection.setDoOutput(true);//from  w  ww  .j a  va2s .c o  m
    connection.setDoInput(true);
    connection.setReadTimeout(CONNECT_TIMEOUT);
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setRequestProperty("Content-Type", "application/timestamp-query");

    // TODO set accept header

    LOGGER.debug("Established connection to TSA server");

    String username = tsaInfo.getUsername();
    char[] password = tsaInfo.getPassword();
    if (StringUtils.isNotBlank(username) && password != null) {
        // FIXME this most likely wrong, e.g. set correct request property!
        // connection.setRequestProperty(username, password);
    }

    // read response
    sendRequest(request, connection);

    LOGGER.debug("Waiting for response from TSA server");

    byte[] response = getResponse(connection);

    LOGGER.debug("Received response from TSA server");

    return response;
}

From source file:com.qiqi8226.http.MainActivity.java

private void onBtnPost() {
    new AsyncTask<String, String, Void>() {

        @Override/* w  w  w.  j  av  a2  s .c  o m*/
        protected Void doInBackground(String... params) {
            URL url;
            try {
                url = new URL(params[0]);
                URLConnection conn = url.openConnection();

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

                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
                bw.write("");
                bw.flush();

                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    publishProgress(line);
                }
                br.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            tv.append(values[0] + "\n");
        }
    }.execute("http://www.baidu.com/");
}

From source file:service.GoEuroServiceImpl.java

@Override
public List<GoEuroModel> convertJsonDataToModel(String cityName) {
    String completeUrl = URL_SOURCE + cityName;
    List<GoEuroModel> goEuroModels = new LinkedList<>();
    try {//from   w  ww.jav a2 s.  c  om
        URL url = new URL(completeUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setDoInput(true);
        if (url.getContent() != null) {
            InputStream is = url.openStream();
            String jsonData = getJsonData(new BufferedReader(new InputStreamReader(is)));
            JSONArray jsonArray = new JSONArray(jsonData);
            int jsonArrayLength = jsonArray.length();

            for (int i = 0; i < jsonArrayLength; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                GoEuroModel goEuroModel = new GoEuroModel();
                goEuroModel.set_id(Long.parseLong(jsonObject.get(ID).toString()));
                goEuroModel.setName(jsonObject.get(NAME).toString());
                goEuroModel.setType(jsonObject.get(TYPE).toString());
                goEuroModel.setLatitude(Double
                        .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ZERO_INDEX_POSITION]
                                .split(COLON)[ONE_INDEX_POSITION]));
                goEuroModel.setLongitude(Double
                        .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ONE_INDEX_POSITION]
                                .split(COLON)[ONE_INDEX_POSITION]
                                        .split(CLOSING_CURLY_BRACE)[ZERO_INDEX_POSITION]));
                goEuroModels.add(goEuroModel);
            }
        }
    } catch (MalformedURLException e) {
        throw new GoEuroException(e.getMessage());
    } catch (IOException | JSONException e) {
        throw new GoEuroException(e.getMessage());
    }
    return goEuroModels;
}

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

private TimeStampResponse probe(TimeStampRequest request) throws IOException, TSPException {
    URLConnection connection = this.url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);/*  w w w.  j  a v a  2  s .  c om*/
    connection.setUseCaches(false);
    connection.setRequestProperty("Content-Type", "application/timestamp-query");
    OutputStream outputStream = (connection.getOutputStream());
    outputStream.write(request.getEncoded());
    outputStream.flush();
    outputStream.close();
    InputStream inputStream = connection.getInputStream();
    TimeStampResponse response = new TimeStampResponse(inputStream);
    inputStream.close();
    return response;
}