Example usage for java.net URLConnection addRequestProperty

List of usage examples for java.net URLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:com.fluidops.iwb.widget.ImportRDFWidget.java

private FButton createURLButton(final FTextInput2 context, final FTextInput2 baseURI, final FContainer stat,
        final FComboBox dataTypeBox, final FTextInput2 urlInput, final FCheckBox keepSourceCtx,
        final FCheckBox contextEditable) {
    return new FButton("urlButton", "Import RDF Data") {
        @Override//from   w ww.  j av a  2 s. com
        public void onClick() {
            try {
                getBasicInput(context, baseURI);
            } catch (Exception e) {
                stat.hide(true);
                logger.info(e.getMessage());
                return;
            }

            RDFFormat rf = null;
            if (!(dataTypeBox.getSelected().get(0) instanceof RDFFormat)) {
                rf = RDFFormat.forFileName(urlInput.getValue());
                if (rf == null) {
                    getPage().getPopupWindowInstance().showError(
                            "The system was not able to detect the RDF format automatically. Please select the RDF Format manually!");
                    return;
                }
            } else {
                rf = (RDFFormat) dataTypeBox.getSelected().get(0);
            }

            URL url = null;
            try {
                url = new URL(urlInput.getInput());
            } catch (MalformedURLException e) {
                stat.hide(true);
                getPage().getPopupWindowInstance()
                        .showError("\"" + urlInput.getInput() + "\" is not a valid URL");
                logger.error(e.getMessage(), e);
                return;
            }
            InputStream input = null;
            try {
                URLConnection uc = url.openConnection();
                uc.addRequestProperty("accept", rf.getDefaultMIMEType());
                input = uc.getInputStream();
                importData(this, input, baseUri, rf, contextUri, url.toString(), keepSourceCtx.getChecked(),
                        contextEditable.getChecked());
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                getPage().getPopupWindowInstance()
                        .showError("The data could not be imported. "
                                + "The following problem occured during the import: "
                                + e.getClass().getSimpleName() + " : " + e.getMessage());
            } finally {
                stat.hide(true);
            }
        }
    };
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Tries to download the contents of the provided url using commercially validated CA certificate from chosen provider.
 *
 * @param string_url/*from w  w w  .j  ava2  s. c  om*/
 * @return
 */
private String downloadWithCommercialCA(String string_url) {

    String json_file_content = "";

    URL provider_url = null;
    int seconds_of_timeout = 1;
    try {
        provider_url = new URL(string_url);
        URLConnection url_connection = provider_url.openConnection();
        url_connection.setConnectTimeout(seconds_of_timeout * 1000);
        if (!LeapSRPSession.getToken().isEmpty())
            url_connection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token = " + LeapSRPSession.getToken());
        json_file_content = new Scanner(url_connection.getInputStream()).useDelimiter("\\A").next();
    } catch (MalformedURLException e) {
        json_file_content = formatErrorMessage(R.string.malformed_url);
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    } catch (SSLHandshakeException e) {
        if (provider_url != null) {
            json_file_content = downloadWithProviderCA(string_url);
        } else {
            json_file_content = formatErrorMessage(R.string.certificate_error);
        }
    } catch (ConnectException e) {
        json_file_content = formatErrorMessage(R.string.service_is_down_error);
    } catch (FileNotFoundException e) {
        json_file_content = formatErrorMessage(R.string.malformed_url);
    } catch (Exception e) {
        e.printStackTrace();
        if (provider_url != null) {
            json_file_content = downloadWithProviderCA(string_url);
        }
    }

    return json_file_content;
}

From source file:com.tc.util.io.ServerURL.java

private HttpURLConnection createSecureConnection(PwProvider pwProvider) {
    if (securityInfo.isSecure()) {
        Assert.assertNotNull("Secured URL '" + theURL + "', yet PwProvider instance", pwProvider);
    }/*from   ww w.  j a  v a2  s  .c  o m*/

    URLConnection urlConnection;
    try {
        urlConnection = theURL.openConnection();
        String uri = null;

        if (securityInfo.isSecure()) {
            if (securityInfo.getUsername() != null) {
                String encodedUsername = URLEncoder.encode(securityInfo.getUsername(), "UTF-8").replace("+",
                        "%20");
                uri = "tc://" + encodedUsername + "@" + theURL.getHost() + ":" + theURL.getPort();
                final char[] passwordTo;
                try {
                    final URI theURI = new URI(uri);
                    passwordTo = pwProvider.getPasswordFor(theURI);
                } catch (URISyntaxException e) {
                    throw new TCRuntimeException("Couldn't create URI to connect to " + uri, e);
                }
                Assert.assertNotNull("No password for " + theURL + " found!", passwordTo);
                urlConnection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder()
                        .encode((securityInfo.getUsername() + ":" + new String(passwordTo)).getBytes()));
            }

            if (DISABLE_HOSTNAME_VERIFIER || TRUST_ALL_CERTS) {
                tweakSecureConnectionSettings(urlConnection);
            }
        }
    } catch (IOException e1) {
        throw new IllegalStateException(e1);
    }

    if (timeout > -1) {
        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
    }
    return (HttpURLConnection) urlConnection;
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

String loadPageBinaryData(AbstractPage p, String href, String type, boolean auth) throws Exception {
    String filename = href.substring(href.lastIndexOf('/') + 1);
    filename = filename.replace(' ', '_');
    if (filename.indexOf('?') != -1) {
        filename = filename.substring(0, filename.indexOf('?'));
    }/*w  ww.  ja va 2 s .com*/

    String dirName = p.getPath();
    dirName = dirName.substring(0, dirName.lastIndexOf(".")) + "." + type;
    File file = new File(outputDir, dirName);
    if (!file.exists()) {
        callSvn("mkdir", file.getAbsolutePath());
        file.mkdirs();
    }
    file = new File(file, filename);
    boolean exists = file.exists();
    FileOutputStream out = new FileOutputStream(file);
    if (auth) {
        if (href.indexOf('?') != -1) {
            href += "&os_authType=basic";
        } else {
            href += "?os_authType=basic";
        }
    }
    URL url = new URL(HOST + href);
    URLConnection con = url.openConnection();
    if (auth) {
        con.addRequestProperty("Authorization", getBasicAuthHeader());
    }
    InputStream ins = con.getInputStream();
    IOUtils.copy(ins, out);
    out.close();
    ins.close();
    if (!exists) {
        callSvn("add", file.getAbsolutePath());
        svnCommitMessage.append("Added: " + dirName + "/" + file.getName() + "\n");
    } else {
        svnCommitMessage.append("Modified: " + dirName + "/" + file.getName() + "\n");
    }
    return file.getName();
}

From source file:fromgate.weatherman.FGUtilCore.java

private void updateLastVersion() {
    if (!this.project_check_version)
        return;/* ww w . j  av  a2 s  .  co m*/
    URL url = null;
    try {
        url = new URL(this.project_curse_url);
    } catch (Exception e) {
        this.log("Failed to create URL: " + this.project_curse_url);
        return;
    }

    try {
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("X-API-Key", null);
        conn.addRequestProperty("User-Agent", this.project_name + " using FGUtilCore (by fromgate)");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            String plugin_name = (String) latest.get("name");
            this.project_last_version = plugin_name.replace(this.project_name + " v", "").trim();
            //String plugin_jar_url = (String) latest.get("downloadUrl");
            //this.project_file_url = plugin_jar_url.replace("http://servermods.cursecdn.com/", "http://dev.bukkit.org/media/");
        }
    } catch (Exception e) {
        this.log("Failed to check last version");
    }
}

From source file:fromgate.obscura.FGUtilCore.java

private void updateLastVersion() {
    if (!this.project_check_version)
        return;//from  w  w w.  j av  a 2  s.  c  o m
    URL url = null;
    try {
        url = new URL(this.project_curse_url);
    } catch (Exception e) {
        this.log("Failed to create URL: " + this.project_curse_url);
        return;
    }

    try {
        URLConnection conn = url.openConnection();
        conn.addRequestProperty("X-API-Key", this.project_apikey);
        conn.addRequestProperty("User-Agent", this.project_name + " using FGUtilCore (by fromgate)");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);
        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            String plugin_name = (String) latest.get("name");
            this.project_last_version = plugin_name.replace(this.project_name + " v", "").trim();
            //String plugin_jar_url = (String) latest.get("downloadUrl");
            //this.project_file_url = plugin_jar_url.replace("http://servermods.cursecdn.com/", "http://dev.bukkit.org/media/");
        }
    } catch (Exception e) {
        this.log("Failed to check last version");
    }
}

From source file:org.ow2.proactive.scheduler.rest.SchedulerClient.java

@Override
public JobId submit(URL job, Map<String, String> variables, Map<String, String> requestHeaderParams)
        throws NotConnectedException, PermissionException, SubmissionClosedException, JobCreationException {
    JobIdData jobIdData = null;/*from   w  ww  .ja  va 2  s .  co m*/
    try {
        URLConnection urlConnection = job.openConnection();

        for (Map.Entry<String, String> requestHeaderEntry : requestHeaderParams.entrySet()) {
            urlConnection.addRequestProperty(requestHeaderEntry.getKey(), requestHeaderEntry.getValue());
        }
        InputStream is = urlConnection.getInputStream();
        jobIdData = restApiClient().submitXml(sid, is, variables);
    } catch (Exception e) {
        throwNCEOrPEOrSCEOrJCE(e);
    }
    return jobId(jobIdData);
}

From source file:org.sakaiproject.calendar.impl.BaseExternalCalendarSubscriptionService.java

ExternalSubscription loadCalendarSubscriptionFromUrl(String url, String context, String calendarName,
        String forcedEventType) {
    ExternalSubscription subscription = new BaseExternalSubscription(calendarName, url, context, null,
            INSTITUTIONAL_CONTEXT.equals(context));
    ExternalCalendarSubscription calendar = null;
    List<CalendarEvent> events = null;
    BufferedInputStream stream = null;
    try {/*from   w w  w . jav a2s. c om*/
        URL _url = new URL(url);
        if (calendarName == null)
            calendarName = _url.getFile();

        // connect
        URLConnection conn = _url.openConnection();
        // Must set user agent so we can detect loops.
        conn.addRequestProperty("User-Agent", m_calendarService.getUserAgent());
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);
        // Now make the connection.
        conn.connect();
        stream = new BufferedInputStream(conn.getInputStream());
        // import
        events = m_importerService.doImport(CalendarImporterService.ICALENDAR_IMPORT, stream, columnMap, null);

        String subscriptionId = getIdFromSubscriptionUrl(url);
        String reference = calendarSubscriptionReference(context, subscriptionId);
        calendar = new ExternalCalendarSubscription(reference);
        for (CalendarEvent event : events) {
            String eventType = event.getType();
            if (forcedEventType != null)
                eventType = forcedEventType;
            calendar.addEvent(event.getRange(), event.getDisplayName(), event.getDescription(), eventType,
                    event.getLocation(), event.getRecurrenceRule(), null);
        }
        calendar.setName(calendarName);
        subscription.setCalendar(calendar);
        subscription.setInstitutional(getInstitutionalSubscription(url) != null);
        m_log.info("Loaded calendar subscription: " + subscription.toString());
    } catch (ImportException e) {
        m_log.info("Error loading calendar subscription '" + calendarName + "' (will NOT retry again): " + url);
        String subscriptionId = getIdFromSubscriptionUrl(url);
        String reference = calendarSubscriptionReference(context, subscriptionId);
        calendar = new ExternalCalendarSubscription(reference);
        calendar.setName(calendarName);
        // By setting the calendar to be an empty one we make sure that we don't attempt to re-retrieve it
        // When 2 hours are up it will get refreshed through.
        subscription.setCalendar(calendar);
    } catch (PermissionException e) {
        // This will never be called (for now)
        e.printStackTrace();
    } catch (MalformedURLException e) {
        m_log.info("Mal-formed URL in calendar subscription '" + calendarName + "': " + url);
    } catch (IOException e) {
        m_log.info("Unable to read calendar subscription '" + calendarName + "' from URL (I/O Error): " + url);
    } catch (Exception e) {
        m_log.info("Unknown error occurred while reading calendar subscription '" + calendarName
                + "' from URL: " + url);
    } finally {
        if (stream != null) {
            // Also closes the underlying InputStream
            try {
                stream.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
    return subscription;
}

From source file:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {//from   w w  w . ja  va  2 s .  c o  m
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}

From source file:com.remobile.filetransfer.FileTransfer.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {// www  .  j  a va2  s  . co  m
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            /* RFC 2616 says that non-ASCII characters and control
             * characters are not allowed in header names or values.
             * Additionally, spaces are not allowed in header names.
             * RFC 2046 Quoted-printable encoding may be used to encode
             * arbitrary characters, but we donon- not do that encoding here.
             */
            String headerKey = iter.next().toString();
            String cleanHeaderKey = headerKey.replaceAll("\\n", "").replaceAll("\\s+", "").replaceAll(":", "")
                    .replaceAll("[^\\x20-\\x7E]+", "");

            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();

                /* RFC 2616 also says that any amount of consecutive linear
                 * whitespace within a header value can be replaced with a
                 * single space character, without affecting the meaning of
                 * that value.
                 */

                String headerValue = headers.getString(headerKey);
                String finalValue = headerValue.replaceAll("\\s+", " ").replaceAll("\\n", " ")
                        .replaceAll("[^\\x20-\\x7E]+", " ");
                headerValues.put(finalValue);
            }

            //Use the clean header key, not the one that we passed in
            connection.setRequestProperty(cleanHeaderKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}