Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * set a "cookie" request header and expects the same value in the "cookie"
 * response header/*from   w ww .  j av a  2  s . c om*/
 * 
 * @throws Exception
 */
@Test
public void testMultipleRequestHeader() throws Exception {
    final String headerValue = "bla blah";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testMultipleRequestHeader");

            String receivedHeaderValue = request.getHeaderValues(HeaderName.COOKIE)[0];
            response.setHeader(HeaderName.COOKIE, receivedHeaderValue);
            assertEquals(headerValue, receivedHeaderValue);
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        URLConnection connection = serverURL.openConnection();
        connection.setRequestProperty("CoOkie", headerValue);
        connection.setRequestProperty("FOO", "bar");
        connection.connect();
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(headerValue, connection.getHeaderField("Cookie"));
        connection.getContentLength();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

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

/**
 * Export data to the specified file.//  ww w  . j  av a2  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 w w. j ava  2 s .c  o m
    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:net.dv8tion.jda.audio.player.URLPlayer.java

public void setAudioUrl(URL urlOfResource, int bufferSize) throws IOException, UnsupportedAudioFileException {
    if (urlOfResource == null)
        throw new IllegalArgumentException(
                "A null URL was provided to the Player! Cannot find resource to play from a null URL!");

    this.urlOfResource = urlOfResource;
    URLConnection conn = null;
    HttpHost jdaProxy = api.getGlobalProxy();
    if (jdaProxy != null) {
        InetSocketAddress proxyAddress = new InetSocketAddress(jdaProxy.getHostName(), jdaProxy.getPort());
        Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
        conn = urlOfResource.openConnection(proxy);
    } else {//from w w  w .java 2  s  .c  om
        conn = urlOfResource.openConnection();
    }
    if (conn == null)
        throw new IllegalArgumentException(
                "The provided URL resulted in a null URLConnection! Does the resource exist?");

    conn.setRequestProperty("user-agent", userAgent);
    this.resourceStream = conn.getInputStream();
    bufferedResourceStream = new BufferedInputStream(resourceStream, bufferSize);
    setAudioSource(AudioSystem.getAudioInputStream(bufferedResourceStream));
}

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 ww  .  ja  va 2  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:net.sf.jabref.importer.fileformat.FreeCiteImporter.java

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {//from   www.ja v a2  s  .co  m
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:adams.flow.sink.DownloadFile.java

/**
 * Executes the flow item.//from   w w  w .  j  a  va 2 s . c  o m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    BufferedOutputStream output;
    FileOutputStream fos;
    byte[] buffer;
    int len;
    int count;
    URLConnection conn;
    String basicAuth;

    input = null;
    output = null;
    fos = null;
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        fos = new FileOutputStream(m_OutputFile.getAbsoluteFile());
        output = new BufferedOutputStream(fos);
        buffer = new byte[m_BufferSize];
        count = 0;
        while ((len = input.read(buffer)) > 0) {
            count++;
            output.write(buffer, 0, len);
            if (count % 100 == 0)
                output.flush();
        }
        output.flush();

        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        FileUtils.closeQuietly(input);
        FileUtils.closeQuietly(output);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

/**
 * Retrieves user info from cookie/*w ww  . j av a2s  .co m*/
 */
public User getUser(HttpServletRequest req) {
    if (isLocal()) {
        return LOCAL_USER;
    }

    Cookie[] cookies = req.getCookies();
    String wpCookieName = null;
    String wpCookieValue = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().startsWith("wordpress_logged_in")) {
                wpCookieName = cookie.getName();
                wpCookieValue = cookie.getValue();
            }
        }
    }

    final String ip = req.getRemoteAddr();
    final String host = req.getRemoteHost();

    System.out.println("Session : " + wpCookieName + " " + wpCookieValue);

    if (wpCookieName == null) {
        return NO_USER;
    }

    try {
        URL u = new URL(URL_ROOT + "/kite9_user_info");
        URLConnection conn = u.openConnection();
        conn.setRequestProperty("Cookie", wpCookieName + "=" + wpCookieValue);
        conn.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = br.readLine();
        br.close();
        if (line.contains("<none>")) {
            return NO_USER;
        } else {
            String parts[] = line.split(",");
            int id = Integer.parseInt(parts[1]);
            return new User(id, parts[0], false, ip, host);
        }
    } catch (IOException e) {
        throw new Kite9ProcessingException("Couldn't handle user log-in", e);
    }
}

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

/**
 * This method sends a request to publisher logout api to invalidate the given sessionID
 *
 * @param sessionId String of valid session ID
 *///from  ww  w. ja  v a 2  s . c om
private void logOut(String sessionId) throws IOException {
    URLConnection urlConn = null;
    String logoutEndpoint = getBaseUrl() + PUBLISHER_APIS_LOGOUT_ENDPOINT;
    //construct APIs session invalidate endpoint
    try {
        URL endpointUrl = new URL(logoutEndpoint);
        urlConn = endpointUrl.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Invalidating session: " + sessionId);
        }
        urlConn.setRequestProperty(COOKIE, JSESSIONID + "=" + sessionId + ";");
        //send SessionId Cookie
        //send POST output.
        urlConn.getOutputStream().flush();
    } catch (MalformedURLException e) {
        LOG.error(getLogoutErrorMassage(logoutEndpoint), e);
        throw e;
    } catch (IOException e) {
        LOG.error(getLogoutErrorMassage(logoutEndpoint), e);
        throw e;
    } finally {
        if (urlConn != null) {
            try {
                urlConn.getOutputStream().close();//will close the connection as well
            } catch (IOException e) {
                LOG.error("Failed to close OutPutStream", e);
            }
        }
    }
}

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

@Override
public SearchResultImpl findEntries(SearchCriteria search) {
    SearchResultImpl results = null;//from   w ww.  j a va2  s .  c om
    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;
}