Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:com.greatmancode.tools.utils.Updater.java

private boolean read() {
    try {/*from ww w .  j  a  v a2s .c  om*/
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", "Updater (by Gravity)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            caller.getLogger().warning("The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            caller.getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            caller.getLogger().warning("Please double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            caller.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
            caller.getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:com.otisbean.keyring.Ring.java

/**
 * Export data to the specified file./*from   www . j a  va2  s .c  o m*/
 * 
 * @param outFile Path to the output file
 * @throws IOException
 * @throws GeneralSecurityException
 */
public void save(String outFile) throws IOException, GeneralSecurityException {
    log("save(" + outFile + ")");
    if (outFile.startsWith("http")) {
        URL url = new URL(outFile);
        URLConnection urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
        String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8");
        dos.writeBytes(message);
        dos.flush();
        dos.close();

        // the server responds by saying 
        // "OK" or "ERROR: blah blah"

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String s = br.readLine();
        if (!s.equals("OK")) {
            StringBuilder sb = new StringBuilder();
            sb.append("Failed to save to URL '");
            sb.append(url);
            sb.append("': ");
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            throw new IOException(sb.toString());
        }
        br.close();
    } else {
        Writer writer = getWriter(outFile);
        getExportData().writeJSONString(writer);
        closeWriter(writer, outFile);
    }
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

public List<Group> findSimpleGroup(String search) {

    List<Group> searchResults = new ArrayList<Group>();
    Group entry = null;//from  w  ww .j  a  va2  s .com
    StringBuilder queryString = new StringBuilder();

    if (search != null && !search.trim().isEmpty()) {
        queryString.append("searchCriteria=");
        queryString.append(search.trim());
    }

    LOG.debug("Group serach QueryString will be : " + queryString.toString());
    try {
        URLConnection connection = new URL(GROUP_SEARCH_URL).openConnection();

        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
        OutputStream output = null;

        output = connection.getOutputStream();
        output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

        String jsonData = null;
        jsonData = IOUtils.toString(connection.getInputStream(), DEFAULT_CHARACTER_SET);

        LOG.debug("Attempting to parse JSON using JSON.simple.");
        LOG.debug(jsonData);

        JSONParser parser = new JSONParser();

        Object rootObj = parser.parse(jsonData);

        JSONObject jsonObject = (JSONObject) rootObj;

        JSONArray groups = (JSONArray) jsonObject.get("group");
        for (Object group : groups) {
            JSONObject g = (JSONObject) group;
            LOG.debug(g.toString());
            entry = (Group) getApplicationContext().getBean("directoryGroup");
            entry.setDN((String) g.get("distinguishedName"));
            if (null != g.get("errors") && (g.get("errors")) instanceof JSONObject) {
                JSONObject error = (JSONObject) g.get("errors");
                if (null != error.get("global")) {
                    JSONObject globalError = (JSONObject) error.get("global");
                    entry.setDisplayName("Error");
                    List<String> tDesc = new ArrayList<String>();
                    tDesc.add((String) globalError.get("description"));
                    entry.setDescriptions(tDesc);
                }
            } else {
                if (null != g.get("description")) {
                    if ((g.get("description")) instanceof String) {
                        List<String> tDesc = new ArrayList<String>();
                        tDesc.add((String) g.get("description"));
                        entry.setDescriptions(tDesc);
                    } else {
                        entry.setDescriptions((List) g.get("description"));
                    }
                }
                entry.setDisplayName((String) g.get("displayName"));
                entry.setEmail((String) g.get("email"));
            }
            searchResults.add(entry);
        }

    } catch (IOException ioe) {
        LOG.error(ioe.getLocalizedMessage(), ioe);
    } catch (ParseException pe) {
        LOG.error(pe.getLocalizedMessage(), pe);
    }
    return searchResults;
}

From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java

/**
 * Generate an XML-RPC request and send it to the server. Parse the result
 * and return the corresponding Java object.
 *
 * @exception XmlRpcException If the remote host returned a fault message.
 * @exception IOException If the call could not be made for lower level
 *          problems.//w w w.j a  va2 s .  c o  m
 */
public Object execute(String method, Vector arguments) throws XmlRpcException, IOException {
    fault = false;
    long now = System.currentTimeMillis();
    try {
        StringBuffer strbuf = new StringBuffer();
        XmlWriter writer = new XmlWriter(strbuf);
        writeRequest(writer, method, arguments);
        byte[] request = strbuf.toString().getBytes();
        URLConnection con = url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        // con.connect ();
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        InputStream in = con.getInputStream();
        parse(in);
        System.out.println("result = " + result);
    } catch (Exception x) {
        x.printStackTrace();
        throw new IOException(x.getMessage());
    }
    if (fault) {
        // generate an XmlRpcException
        XmlRpcException exception = null;
        try {
            Hashtable f = (Hashtable) result;
            String faultString = (String) f.get("faultString");
            int faultCode = Integer.parseInt(f.get("faultCode").toString());
            exception = new XmlRpcException(faultCode, faultString.trim());
        } catch (Exception x) {
            throw new XmlRpcException(0, "Invalid fault response");
        }
        throw exception;
    }
    System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request");
    return result;
}

From source file:org.gephi.streaming.impl.StreamingControllerImpl.java

private void sendEvent(final StreamingEndpoint endpoint, GraphEvent event) {
    logger.log(Level.FINE, "Sending event {0}", event.toString());
    try {// w  w  w . jav  a 2 s .co m
        URL url = new URL(endpoint.getUrl(), endpoint.getUrl().getFile() + "?operation=updateGraph&format="
                + endpoint.getStreamType().getType());

        URLConnection connection = url.openConnection();

        // Workaround for Bug https://issues.apache.org/jira/browse/CODEC-89
        String base64Encoded = Base64
                .encodeBase64String((endpoint.getUser() + ":" + endpoint.getPassword()).getBytes());
        base64Encoded = base64Encoded.replaceAll("\r\n?", "");

        connection.setRequestProperty("Authorization", "Basic " + base64Encoded);

        connection.setDoOutput(true);
        connection.connect();

        StreamWriterFactory writerFactory = Lookup.getDefault().lookup(StreamWriterFactory.class);

        OutputStream out = null;
        try {
            out = connection.getOutputStream();
        } catch (UnknownServiceException e) {
            // protocol doesn't support output
            return;
        }
        StreamWriter writer = writerFactory.createStreamWriter(endpoint.getStreamType(), out);
        writer.handleGraphEvent(event);
        out.flush();
        out.close();
        connection.getInputStream().close();

    } catch (IOException ex) {
        logger.log(Level.FINE, null, ex);
    }
}

From source file:com.net.h1karo.sharecontrol.ShareControl.java

public void updateCheck() {
    String CBuildString = "", NBuildString = "";

    int CMajor = 0, CMinor = 0, CMaintenance = 0, CBuild = 0, NMajor = 0, NMinor = 0, NMaintenance = 0,
            NBuild = 0;//from  w  w  w.j  av  a 2s . c o m

    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectids=90354");
        URLConnection conn = url.openConnection();
        conn.setReadTimeout(5000);
        conn.addRequestProperty("User-Agent", "ShareControl Update Checker");
        conn.setDoOutput(true);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();
        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            this.getLogger().warning("No files found, or Feed URL is bad.");
            result = UpdateResult.ERROR;
            return;
        }
        String newVersionTitle = ((String) ((JSONObject) array.get(array.size() - 1)).get("name"));
        newVersion = newVersionTitle.replace("ShareControl v", "").trim();

        /**\\**/
        /**\\**//**\\**/
        /**\    GET VERSIONS    /**\
          /**\\**/
        /**\\**//**\\**/

        String[] CStrings = currentVersion.split(Pattern.quote("."));

        CMajor = Integer.parseInt(CStrings[0]);
        if (CStrings.length > 1)
            if (CStrings[1].contains("-")) {
                CMinor = Integer.parseInt(CStrings[1].split(Pattern.quote("-"))[0]);
                CBuildString = CStrings[1].split(Pattern.quote("-"))[1];
                if (CBuildString.contains("b")) {
                    beta = true;
                    CBuildString = CBuildString.replace("b", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 1;
                } else if (CBuildString.contains("a")) {
                    alpha = true;
                    CBuildString = CBuildString.replace("a", "");
                    if (CBuildString != "")
                        CBuild = Integer.parseInt(CBuildString) - 10;
                } else
                    CBuild = Integer.parseInt(CBuildString);
            } else {
                CMinor = Integer.parseInt(CStrings[1]);
                if (CStrings.length > 2)
                    if (CStrings[2].contains("-")) {
                        CMaintenance = Integer.parseInt(CStrings[2].split(Pattern.quote("-"))[0]);
                        CBuildString = CStrings[2].split(Pattern.quote("-"))[1];
                        if (CBuildString.contains("b")) {
                            beta = true;
                            CBuildString = CBuildString.replace("b", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 1;
                        } else if (CBuildString.contains("a")) {
                            alpha = true;
                            CBuildString = CBuildString.replace("a", "");
                            if (CBuildString != "")
                                CBuild = Integer.parseInt(CBuildString) - 10;
                        } else
                            CBuild = Integer.parseInt(CBuildString);
                    } else
                        CMaintenance = Integer.parseInt(CStrings[2]);
            }

        String[] NStrings = newVersion.split(Pattern.quote("."));

        NMajor = Integer.parseInt(NStrings[0]);
        if (NStrings.length > 1)
            if (NStrings[1].contains("-")) {
                NMinor = Integer.parseInt(NStrings[1].split(Pattern.quote("-"))[0]);
                NBuildString = NStrings[1].split(Pattern.quote("-"))[1];
                if (NBuildString.contains("b")) {
                    beta = true;
                    NBuildString = NBuildString.replace("b", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 1;
                } else if (NBuildString.contains("a")) {
                    alpha = true;
                    NBuildString = NBuildString.replace("a", "");
                    if (NBuildString != "")
                        NBuild = Integer.parseInt(NBuildString) - 10;
                } else
                    NBuild = Integer.parseInt(NBuildString);
            } else {
                NMinor = Integer.parseInt(NStrings[1]);
                if (NStrings.length > 2)
                    if (NStrings[2].contains("-")) {
                        NMaintenance = Integer.parseInt(NStrings[2].split(Pattern.quote("-"))[0]);
                        NBuildString = NStrings[2].split(Pattern.quote("-"))[1];
                        if (NBuildString.contains("b")) {
                            beta = true;
                            NBuildString = NBuildString.replace("b", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 1;
                        } else if (NBuildString.contains("a")) {
                            alpha = true;
                            NBuildString = NBuildString.replace("a", "");
                            if (NBuildString != "")
                                NBuild = Integer.parseInt(NBuildString) - 10;
                        } else
                            NBuild = Integer.parseInt(NBuildString);
                    } else
                        NMaintenance = Integer.parseInt(NStrings[2]);
            }

        /**\\**/
        /**\\**//**\\**/
        /**\   CHECK VERSIONS   /**\
          /**\\**/
        /**\\**//**\\**/
        if ((CMajor < NMajor) || (CMajor == NMajor && CMinor < NMinor)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance < NMaintenance)
                || (CMajor == NMajor && CMinor == NMinor && CMaintenance == NMaintenance && CBuild < NBuild))
            result = UpdateResult.UPDATE_AVAILABLE;
        else
            result = UpdateResult.NO_UPDATE;
        return;
    } catch (Exception e) {
        console.sendMessage(" There was an issue attempting to check for the latest version.");
    }
    result = UpdateResult.ERROR;
}

From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java

public String addUserEntryForEmails(String loginid, User user, UserLogin userLogin, String pwdtext,
        boolean isPasswordText) throws ServiceException {
    String returnStr = "";
    try {//w w w . jav  a2  s .c  o m
        String baseURLFormat = storageHandlerImpl.GetSOAPServerUrl();
        String url = baseURLFormat + "defaultUserEntry.php";
        URL u = new URL(url);
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String userName = userLogin.getUserName() + "_" + user.getCompany().getSubDomain();
        String strParam = "loginid=" + loginid + "&userid=" + user.getUserID() + "&username=" + userName
                + "&password=" + userLogin.getPassword() + "&pwdtext=" + pwdtext + "&fullname="
                + (user.getFirstName() + user.getLastName()) + "&isadmin=0&ispwdtest=" + isPasswordText;
        PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.println(strParam);
        pw.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = "";
        while ((line = in.readLine()) != null) {
            returnStr += line;
        }
        in.close();
        returnStr = returnStr.replaceAll("\\s+", " ").trim();
        JSONObject emailresult = new JSONObject(returnStr);
        if (Boolean.parseBoolean(emailresult.getString("success"))) {
            user.setUser_hash(emailresult.getString("pwd"));
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (JSONException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return returnStr;
}

From source file:com.hqme.cm.cache.StreamingServer.java

public void stopServer() {
    UntenCacheService.debugLog(sTag, "stopServer");
    isStopping = true;/* w  w  w .  ja v  a 2 s .co m*/
    try {
        URL term = new URL("http://localhost:" + serverPortNumber + "/");
        URLConnection conn = term.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write("GET /favicon.ico HTTP/1.1");
        out.close();
    } catch (Throwable fault) {
        // UntenCacheService.debugLog(sTag, "stopServer", fault);
    }
}

From source file:org.kuali.mobility.people.dao.DirectoryDaoUMImpl.java

@Override
public SearchResultImpl findEntries(SearchCriteria search) {
    SearchResultImpl results = null;//from w  w w  .  j a va  2  s  .c  o m
    String searchText = search.getSearchText();
    if (searchText != null && searchText.contains("<script>")) {
        // Do not perform any search
    }
    if (searchText != null && searchText.contains(";")) {
        // Do not perform any search
    } else if (searchText != null && searchText.contains("eval")) {
        // Do not perform any search
    } else {
        results = (SearchResultImpl) getApplicationContext().getBean("searchResult");

        StringBuilder queryString = new StringBuilder();

        if (search.getSearchText() != null && !search.getSearchText().trim().isEmpty()) {
            searchText = searchText.replaceAll("[^\\w\\s]", ""); //Removes all special character
            queryString.append("searchCriteria=");
            queryString.append(searchText.trim());
        } else if (search.getUserName() != null && !search.getUserName().isEmpty()) {
            queryString.append("uniqname=");
            queryString.append(search.getUserName().trim());
        } else {
            if ("starts".equalsIgnoreCase(search.getExactness())) {
                search.setExactness("starts with");
            }
            if (search.getFirstName() != null && !search.getFirstName().trim().isEmpty()) {
                queryString.append("givenName=");
                queryString.append(search.getFirstName().trim());
                queryString.append("&givenNameSearchType=");
                queryString.append(search.getExactness());
                queryString.append("&");
            }
            if (search.getLastName() != null && !search.getLastName().trim().isEmpty()) {
                queryString.append("sn=");
                queryString.append(search.getLastName().trim());
                queryString.append("&snSearchType=");
                queryString.append(search.getExactness());
            }
        }

        LOG.debug("QueryString will be : " + queryString.toString());

        try {
            URLConnection connection = new URL(SEARCH_URL).openConnection();

            connection.setDoOutput(true); // Triggers POST.
            connection.setRequestProperty("Accept-Charset", DEFAULT_CHARACTER_SET);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=" + DEFAULT_CHARACTER_SET);
            OutputStream output = null;

            output = connection.getOutputStream();
            output.write(queryString.toString().getBytes(DEFAULT_CHARACTER_SET));

            InputStream response = connection.getInputStream();
            String contentType = connection.getHeaderField("Content-Type");

            if (contentType != null && "application/json".equalsIgnoreCase(contentType)) {
                //               LOG.debug("Attempting to parse JSON using Gson.");

                List<Person> peeps = new ArrayList<Person>();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(response, DEFAULT_CHARACTER_SET));

                    String jsonData = IOUtils.toString(response, DEFAULT_CHARACTER_SET);

                    LOG.debug("Attempting to parse JSON using JSON.simple.");
                    LOG.debug(jsonData);

                    JSONParser parser = new JSONParser();

                    Object rootObj = parser.parse(jsonData);

                    JSONObject jsonObject = (JSONObject) rootObj;
                    JSONArray jsonPerson = (JSONArray) jsonObject.get("person");
                    for (Object o : jsonPerson) {
                        peeps.add(parsePerson((JSONObject) o));
                    }
                } catch (UnsupportedEncodingException uee) {
                    LOG.error(uee.getLocalizedMessage());
                } catch (IOException ioe) {
                    LOG.error(ioe.getLocalizedMessage());
                } catch (ParseException pe) {
                    LOG.error(pe.getLocalizedMessage(), pe);
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException logOrIgnore) {
                            LOG.error(logOrIgnore.getLocalizedMessage());
                        }
                    }
                }
                results.setPeople(peeps);
            } else {
                LOG.debug("Content type was not application/json.");
            }
        } catch (IOException ioe) {
            LOG.error(ioe.getLocalizedMessage());
        }
        LOG.debug("Searching for groups.");
        results.setGroups(searchForGroup(search));
    }
    return results;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

private double doUpload(String phpFile, InputStream uploadFileIs, String fileName) {
    URLConnection conn = null;
    OutputStream os = null;/*from  w w w . ja  va2s . com*/
    InputStream is = null;
    double bw = 0.0;

    try {
        String response = "";
        Date oldTime = new Date();
        URL url = new URL(amazonDomain + "/" + phpFile);
        String boundary = "---------------------------4664151417711";
        conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        byte[] fileData = new byte[uploadFileIs.available()];
        uploadFileIs.read(fileData);
        uploadFileIs.close();

        String message1 = "--" + boundary + CrLf;
        message1 += "Content-Disposition: form-data;";
        message1 += "name=\"uploadedfile\"; filename=\"" + fileName + "\"" + CrLf;
        message1 += "Content-Type: text/plain; charset=UTF-8" + CrLf + CrLf;

        // the file is sent between the messages in the multipart message.
        String message2 = CrLf + "--" + boundary + "--" + CrLf;

        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        int contentLenght = message1.length() + message2.length() + fileData.length;

        // might not need to specify the content-length when sending chunked data.
        conn.setRequestProperty("Content-Length", String.valueOf(contentLenght));

        os = conn.getOutputStream();

        os.write(message1.getBytes());

        // SEND THE IMAGE
        int index = 0;
        int size = 1024;
        do {
            if ((index + size) > fileData.length) {
                size = fileData.length - index;
            }
            os.write(fileData, index, size);
            index += size;
        } while (index < fileData.length);

        os.write(message2.getBytes());
        os.flush();

        is = conn.getInputStream();

        char buff = 512;
        int len;
        byte[] data = new byte[buff];
        do {
            len = is.read(data);

            if (len > 0) {
                response += new String(data, 0, len);
            }
        } while (len > 0);

        if (response.equals("200")) {
            Date newTime = new Date();
            double milliseconds = newTime.getTime() - oldTime.getTime();
            bw = ((double) contentLenght * 8) / (milliseconds * (double) 1000);
        }
    } catch (Exception e) {
        System.out.println("Exception is fired in upload test. error:" + e.getMessage());
    } finally {
        try {
            os.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in os.close. error:" + e.getMessage());
        }
        try {
            is.close();
        } catch (Exception e) {
            //System.out.println("Exception is fired in is.close. error:" + e.getMessage());
        }
    }
    return bw;
}