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.apache.axis2.transport.testkit.http.JavaNetClient.java

public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception {
    URL url = new URL(channel.getEndpointReference().getAddress());
    log.debug("Opening connection to " + url + " using " + URLConnection.class.getName());
    try {// w ww .j a  v  a  2 s  .  c  o m
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", contentType.toString());
        if (contentType.getBaseType().equals("text/xml")) {
            connection.setRequestProperty("SOAPAction", "");
        }
        OutputStream out = connection.getOutputStream();
        out.write(message);
        out.close();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            log.debug("Response code: " + httpConnection.getResponseCode());
            log.debug("Response message: " + httpConnection.getResponseMessage());
            int i = 0;
            String headerValue;
            while ((headerValue = httpConnection.getHeaderField(i)) != null) {
                String headerName = httpConnection.getHeaderFieldKey(i);
                if (headerName != null) {
                    log.debug(headerName + ": " + headerValue);
                } else {
                    log.debug(headerValue);
                }
                i++;
            }
        }
        InputStream in = connection.getInputStream();
        IOUtils.copy(in, System.out);
        in.close();
    } catch (IOException ex) {
        log.debug("Got exception", ex);
        throw ex;
    }
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) {

    //receives : apiEndPoint (https://api.test.sabre.com)
    //encodedCliAndSecret : base64Encode(  base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) )
    String strRet = null;/*from w  w w . ja  v  a  2s .  c o m*/

    try {

        URL urlConn = new URL(apiEndPoint + "/v1/auth/token");
        URLConnection conn = urlConn.openConnection();

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

        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret);
        conn.setRequestProperty("Accept", "application/json");

        //send request
        DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream());
        dataOut.writeBytes("grant_type=client_credentials");
        dataOut.flush();
        dataOut.close();

        //get response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String strChunk = "";
        StringBuilder sb = new StringBuilder();
        while (null != ((strChunk = rd.readLine())))
            sb.append(strChunk);

        //parse the token
        JSONObject respParser = new JSONObject(sb.toString());
        strRet = respParser.getString("access_token");

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return strRet;

}

From source file:org.talend.mdm.commmon.util.datamodel.management.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)"); //$NON-NLS-1$
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = Base64.encodeBase64String("admin:talend".getBytes()); //$NON-NLS-1$
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);/* ww w.  ja  v  a2 s .  co  m*/
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials); //$NON-NLS-1$
            conn.setRequestProperty("Expect", "100-continue"); //$NON-NLS-1$
            InputStreamReader doc = new InputStreamReader(conn.getInputStream());
            BufferedReader reader = new BufferedReader(doc);
            String line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            return new InputSource(new StringReader(buffer.toString()));
        } else {
            int mark = systemId.indexOf("file:///"); //$NON-NLS-1$
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0)); //$NON-NLS-1$
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}

From source file:org.openbel.framework.core.protocol.handler.AbstractProtocolHandler.java

/**
 * Retrieves a resource from the {@code urlc} and save it to
 * {@code downloadLocation}.// www  .j  a v  a  2 s. c o m
 * 
 * @param urlc {@link URLConnection}, the url connection
 * @param downloadLocation {@link String}, the location to save the
 * resource content to
 * @throws IOException Thrown if an io error occurred downloading the
 * resource
 * @throws ResourceDownloadError Thrown if there was an I/O error
 * downloading the resource
 */
protected File downloadResource(URLConnection urlc, String downloadLocation) throws ResourceDownloadError {
    if (!urlc.getDoInput()) {
        urlc.setDoInput(true);
    }

    File downloadFile = new File(downloadLocation);
    try {
        File downloaded = File.createTempFile(ProtocolHandlerConstants.BEL_FRAMEWORK_TMP_FILE_PREFIX, null);

        IOUtils.copy(urlc.getInputStream(), new FileOutputStream(downloaded));

        FileUtils.copyFile(downloaded, downloadFile);

        // delete temp file holding download
        if (!downloaded.delete()) {
            downloaded.deleteOnExit();
        }
    } catch (IOException e) {
        final String url = urlc.getURL().toString();
        final String msg = "I/O error";
        throw new ResourceDownloadError(url, msg, e);
    }

    return downloadFile;
}

From source file:com.amalto.core.util.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)");
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = new String(Base64.encodeBase64("admin:talend".getBytes()));
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);/*from  www  .ja va  2  s . co m*/
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials);
            conn.setRequestProperty("Expect", "100-continue");
            InputStreamReader doc = new InputStreamReader(conn.getInputStream());
            BufferedReader reader = new BufferedReader(doc);
            String line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            return new InputSource(new StringReader(buffer.toString()));
        } else {
            int mark = systemId.indexOf("file:///");
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0));
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}

From source file:org.apache.servicemix.http.HttpAddressingTest.java

public void testOkFromUrl() throws Exception {
    URLConnection connection = new URL("http://localhost:8192/Service/").openConnection();
    connection.setDoOutput(true);// w w w  .  j a  v  a2 s.c  o m
    connection.setDoInput(true);
    OutputStream os = connection.getOutputStream();
    // Post the request file.
    InputStream fis = getClass().getResourceAsStream("addressing-request.xml");
    FileUtil.copyInputStream(fis, os);
    // Read the response.
    InputStream is = connection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileUtil.copyInputStream(is, baos);
    log.info(baos.toString());
}

From source file:it.infn.ct.GridEngine.SessionManagement.RobotProxy.java

public String getRobotProxy() {
    File proxyFile;/*  ww w.java 2s.  co  m*/

    if (!proxyPath.equals(""))
        deleteRobotProxy();

    System.out.println("----->New GET HTTP<--------");

    proxyPath = folderPath + UUID.randomUUID();
    proxyFile = new File(proxyPath);
    System.out.println("proxyPath=" + proxyPath);
    String proxyContent = "";
    try {
        URL proxyURL = new URL("http://" + eTokenServer + ":" + eTokenServerPort + "/eTokenServer/eToken/"
                + proxyId + "?voms=" + VO + ":" + FQAN + "&proxy-renewal=" + proxyRenewal);
        URLConnection proxyConnection = proxyURL.openConnection();
        proxyConnection.setDoInput(true);
        InputStream proxyStream = proxyConnection.getInputStream();
        BufferedReader input = new BufferedReader(new InputStreamReader(proxyStream));
        String line = "";
        while ((line = input.readLine()) != null) {
            //System.out.println(line);
            proxyContent += line + "\n";
        }
        FileUtils.writeStringToFile(proxyFile, proxyContent);
    } catch (Exception e) {
        return "";
    }

    return proxyPath;
}

From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java

@Validate
public void start() throws Exception {
    URL endpoint = new URL(endpointUrl);
    URLConnection connection = endpoint.openConnection();
    connection.setDoOutput(true);/*from   ww  w.  j a  v  a  2  s. co  m*/
    connection.setDoInput(true);

    InputStream stream = connection.getInputStream();
    config = new ObjectMapper().readValue(stream, WellKnownOpenIdConfiguration.class);
    stream.close();
    issuerId = config.getIssuer();
}

From source file:eu.europa.ec.markt.dss.validation.tsp.OnlineTSPSource.java

/**
 * Get timestamp token - communications layer
 * /*from  ww w.j a  v a 2s .  c om*/
 * @return - byte[] - TSA response, raw bytes (RFC 3161 encoded)
 */
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
    // Setup the TSA connection

    URL tspUrl = new URL(tspServer);
    URLConnection tsaConnection = tspUrl.openConnection();

    tsaConnection.setDoInput(true);
    tsaConnection.setDoOutput(true);
    tsaConnection.setUseCaches(false);
    tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
    // tsaConnection.setRequestProperty("Content-Transfer-Encoding",
    // "base64");
    tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");

    OutputStream out = tsaConnection.getOutputStream();
    out.write(requestBytes);
    out.close();

    // Get TSA response as a byte array
    InputStream inp = tsaConnection.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
        baos.write(buffer, 0, bytesRead);
    }
    byte[] respBytes = baos.toByteArray();

    String encoding = tsaConnection.getContentEncoding();
    if (encoding != null && encoding.equalsIgnoreCase("base64")) {
        respBytes = new Base64().decode(respBytes);
    }
    return respBytes;
}

From source file:eu.europa.esig.dss.client.http.NativeHTTPDataLoader.java

@Override
public byte[] post(String url, byte[] content) {
    OutputStream out = null;// w  w w  . j  a  v  a2  s.  c om
    InputStream inputStream = null;
    byte[] result = null;
    try {
        URLConnection connection = new URL(url).openConnection();

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

        out = connection.getOutputStream();
        IOUtils.write(content, out);
        inputStream = connection.getInputStream();
        result = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(inputStream);
    }
    return result;
}