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:game.Clue.JerseyClient.java

public void isgameReady() {
    //Check to see if all players have joined game

    try {/*w  ww.j av  a2  s  . com*/
        // URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game/Status");
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game/");
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        //setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        //  while (in.readLine() != null) {
        //}
        System.out.println("\nGET Request for :" + "Game Ready Status?  " + "Sent");
        System.out.print(in.readLine());
        //close connection
        in.close();

    } catch (Exception e) {
        System.out.println("\nError while calling REST Get Service");
        System.out.println(e);

    }

}

From source file:org.deegree.enterprise.servlet.SimpleProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from  w ww.  j  a  v  a  2  s  .  c o m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        String query = request.getQueryString();
        Map<String, String> map = KVP2Map.toMap(query);
        if (removeCredentials) {
            map.remove("USER");
            map.remove("PASSWORD");
            map.remove("SESSIONID");
            query = "";
            for (String key : map.keySet()) {
                query += key + "=" + map.get(key) + "&";
            }
            query = query.substring(0, query.length() - 1);
        }
        String service = getService(map);
        String hostAddr = host.get(service);
        String req = hostAddr + "?" + query;
        URL url = new URL(req);
        LOG.logDebug("forward URL: " + url);

        URLConnection con = url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(false);
        is = con.getInputStream();
        response.setContentType(con.getContentType());
        response.setCharacterEncoding(con.getContentEncoding());
        os = response.getOutputStream();
        int read = 0;
        byte[] buf = new byte[16384];
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
                LOG.logDebug(new String(buf, 0, read,
                        con.getContentEncoding() == null ? "UTF-8" : con.getContentEncoding()));
            }
        } else {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setContentType("text/plain; charset=" + CharsetUtils.getSystemCharset());
        os.write(StringTools.stackTraceToString(e).getBytes());
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // try to do what ?
        }
        try {
            os.close();
        } catch (Exception e) {
            // try to do what ?
        }
    }
}

From source file:game.Clue.JerseyClient.java

public JSONObject getGameState() {

    JSONObject Object = null;//from www  .j  a v  a  2  s .co m
    try {
        URL url = new URL(
                "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player1");
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        //setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        Object = new JSONObject(in.readLine());
        //;
        // JsonParser parser=new JsonParser(in.readLine());

        //  while (in.readLine() != null) {
        //}
        // System.out.print(in.readLine());
        System.out.println(Object.getJSONArray("players").getJSONObject(0).getString("character"));
        System.out.println("\nREST Service Invoked Successfully..GET Request Sent");

        //sendPUT();
        //send JSON to Parser
        //Parser=new JsonParser(in.readLine());
        //System.out.println("Parser called");
        // sendPUT();
        //close connection
        // in.close();
    } catch (Exception e) {
        System.out.println("\nError while calling REST Service");
        System.out.println(e);
    }

    return Object;

}

From source file:game.Clue.JerseyClient.java

public void getAvailableSlot() {

    try {/*from ww  w  .  ja v a2s  .  c  o m*/
        for (int i = 1; i < 7; i++) {
            // URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game/Status");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i + "/");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.println("\nGET Request for :" + "Get Available slot " + "Sent");

            if ((in.readLine()).contains("no name")) {
                game_slot = i;
                i = 7;
            } else {

            }
            System.out.print("You have slot # " + game_slot);
            //close connection
            in.close();
        }

    } catch (Exception e) {
        System.out.println("\nError slot taken..Checking for another open slot...");
        System.out.println(e);

    }

}

From source file:org.wso2.es.integration.common.utils.AssetsRESTClient.java

/**
 * This methods make a call to ES-Publisher REST API and obtain a valid sessionID
 *
 * @return SessionId for the authenticated user
 *///from  w  w w.  j ava2  s  . c om
private String login() throws IOException {
    String sessionID = null;
    Reader input = null;
    BufferedWriter writer = null;
    String authenticationEndpoint = getBaseUrl() + PUBLISHER_APIS_AUTHENTICATE_ENDPOINT;
    //construct full authenticate endpoint
    try {
        //authenticate endpoint URL
        URL endpointUrl = new URL(authenticationEndpoint);
        URLConnection urlConn = endpointUrl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        // Specify the content type.
        urlConn.setRequestProperty(CONTENT_TYPE_HEADER, CONTENT_TYPE);
        // Send POST output.
        writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
        String content = USERNAME + "=" + URLEncoder.encode(USERNAME_VAL, UTF_8) + "&" + PASSWORD + "="
                + URLEncoder.encode(PASSWORD_VAl, UTF_8);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Send Login Information : " + content);
        }
        writer.write(content);
        writer.flush();

        // Get response data.
        input = new InputStreamReader(urlConn.getInputStream());
        JsonElement elem = parser.parse(input);
        sessionID = elem.getAsJsonObject().getAsJsonObject(AUTH_RESPONSE_WRAP_KEY).get(SESSIONID).toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received SessionID : " + sessionID);
        }

    } catch (MalformedURLException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getLoginErrorMassage(authenticationEndpoint), e);
        throw e;
    } finally {
        if (input != null) {
            try {
                input.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close input stream ", e);
            }
        }
        if (writer != null) {
            try {
                writer.close();// will close the URL connection as well
            } catch (IOException e) {
                LOG.error("Failed to close output stream ", e);
            }
        }
    }
    return sessionID;
}

From source file:org.apache.jcs.auxiliary.lateral.http.remove.DeleteLateralCacheUnicaster.java

/** Description of the Method */
public void callClearCache(String ccServletURL) {
    URL clear;//from  w  w w .  java2  s  .co m
    URLConnection clearCon;
    InputStream in;
    OutputStream out;
    try {
        clear = new URL(ccServletURL);
        clearCon = clear.openConnection();
        clearCon.setDoOutput(true);
        clearCon.setDoInput(true);
        //clearCon.connect();
        out = clearCon.getOutputStream();
        in = clearCon.getInputStream();
        int cur = in.read();
        while (cur != -1) {
            cur = in.read();
        }
        out.close();
        in.close();
        // System.out.println("closed inputstream" );
    } catch (Exception e) {
        log.error(e);
    } finally {
        //in.close();
        out = null;
        in = null;
        clearCon = null;
        clear = null;
        log.info("called clear cache for " + ccServletURL);
        return;
    }
}

From source file:game.Clue.JerseyClient.java

public JerseyClient() {

    String string = "";

    try {//from w  ww .  jav a  2  s  . c om
        //System.out.println("jerseyclient started");
        currentgame_state = new JSONObject(
                "{\"players\":[{\"position\":\"0,3\",\"name\":null,\"active\":\"true\",\"cards\":\"MR GREEN,CANDLESTICK,BALLROOM\",\"character\":\"scarlet\"},{\"position\":\"1,4\",\"name\":null,\"active\":\"true\",\"cards\":\"PROFESSOR PLUM,BILLARD ROOM,ROPE\",\"character\":\"mustard\"},{\"position\":\"4,3\",\"name\":null,\"active\":\"true\",\"cards\":\"DINING ROOM,REVOLVER,WRENCH\",\"character\":\"white\"},{\"position\":\"4,1\",\"name\":null,\"active\":\"true\",\"cards\":\"LIBRARY,COLONEL MUSTARD,STUDY\",\"character\":\"green\"},{\"position\":\"3,0\",\"name\":null,\"active\":\"true\",\"cards\":\"MISS SCARLET,MRS PEACOCK,KNIFE\",\"character\":\"peacock\"},{\"position\":\"1,0\",\"name\":null,\"active\":\"true\",\"cards\":\"HALL,CONSERVATORY,LOUNGE\",\"character\":\"plum\"}],\"move_state\":{\"player\":\"scarlet\",\"moves\":[[\"[0,4], [0,2]\",\"accusation\"]]},\"winner\":null}\"))");

        String username = "Mario";
        // Step1: Let's 1st read file from fileSystem
        InputStream crunchifyInputStream = new FileInputStream(
                "/Users/" + username + "/Documents/JsonTest/JSONFile.txt");
        InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream);
        BufferedReader br = new BufferedReader(crunchifyReader);
        String line;
        while ((line = br.readLine()) != null) {
            string += line + "\n";
        }

        JSONObject jsonObject = new JSONObject(string);
        //System.out.println(jsonObject);

        // Step2: Now get JSON File Data from REST Service
        try {

            JsonParser Parser;
            //URL url = new URL("http://192.168.1.7:8080/CluelessServer/webresources/service/game");
            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/game");
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            //setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            //  while (in.readLine() != null) {
            //}
            System.out.print(in.readLine());
            System.out.println("\nREST Service Invoked Successfully..GET Request Sent");
            //getGameState();

            // sendPUT(ClueGameUI.jTextField2.getText());
            //send JSON to Parser
            //Parser=new JsonParser(in.readLine());
            //System.out.println("Parser called");
            // sendPUT();
            //close connection
            in.close();

        } catch (Exception e) {
            System.out.println("\nError while calling REST Service");
            System.out.println(e);
        }

        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Returns a string representing robot proxy information.
 * /* ww w .  j  av  a2 s  .c  o  m*/
 * @return string representing robot proxy information.
 */
public String getRobotProxy() {
    File proxyFile;

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

    logger.info("----->New GET HTTP<--------");

    proxyPath = folderPath + UUID.randomUUID();
    proxyFile = new File(proxyPath);
    logger.info("proxyPath=" + proxyPath);

    String proxyContent = "";
    URL proxyURL = null;
    try {
        if (RFC) {
            proxyURL = new URL("http://" + eTokenServer + ":" + eTokenServerPort + "/eTokenServer/eToken/"
                    + proxyId + "?voms=" + VO + ":" + FQAN + "&disable-voms-proxy=false&proxy-renewal="
                    + proxyRenewal + "&rfc-proxy=" + RFC + "&cn-label=" + cnLabel);
        } else {
            proxyURL = new URL("http://" + eTokenServer + ":" + eTokenServerPort + "/eTokenServer/eToken/"
                    + proxyId + "?voms=" + VO + ":" + FQAN + "&proxy-renewal=" + proxyRenewal + "&cn-label="
                    + cnLabel);
        }
        logger.info("get proxy: " + proxyURL.toString());
        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) {
            proxyContent += line + "\n";
        }
        FileUtils.writeStringToFile(proxyFile, proxyContent);
    } catch (Exception e) {
        if (proxyURL != null)
            logger.error("Error in getting proxy: " + proxyURL.toString());
        return "";
    }

    return proxyPath;
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL size (content)/*from   ww w.  ja  v  a 2  s. c o  m*/
 *
 * @param url  URL for connect
 * @return     size in bytes of a url or 0 if broken or timed out connection
 */
public long getURLSize(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long contentLength = conn.getContentLength();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLSize() content lentgh=" + contentLength + " of URL='" + url + "'");
        }

        return contentLength;
    } catch (IOException ioe) {
        logger.error("getURLSize() failed for URL='" + url + "'", ioe);
        return 0;
    }
}

From source file:org.jab.docsearch.utils.NetUtils.java

/**
 * Gets URL modified date as long//from   ww  w  .ja  v  a2  s . c  o  m
 *
 * @param url  URL to connect
 * @return         date of URLs modification or 0 if an error occurs
 */
public long getURLModifiedDate(final String url) {
    try {
        URL tmpURL = new URL(url);
        URLConnection conn = tmpURL.openConnection();

        // set connection parameter
        conn.setDoInput(true);
        conn.setDoOutput(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", USER_AGENT);

        // connect
        conn.connect();

        long modifiedDate = conn.getLastModified();

        if (logger.isDebugEnabled()) {
            logger.debug("getURLModifiedDate() modified date=" + modifiedDate + " of URL='" + url + "'");
        }

        return modifiedDate;
    } catch (IOException ioe) {
        logger.error("getURLModifiedDate() failed for URL='" + url + "'", ioe);
        return 0;
    }
}