Example usage for java.net URLEncoder encode

List of usage examples for java.net URLEncoder encode

Introduction

In this page you can find the example usage for java.net URLEncoder encode.

Prototype

public static String encode(String s, Charset charset) 

Source Link

Document

Translates a string into application/x-www-form-urlencoded format using a specific java.nio.charset.Charset Charset .

Usage

From source file:com.tdclighthouse.prototype.beans.compounds.LatexBean.java

public String getEncodeLatex() {
    try {//from  ww w . j ava  2 s. c  o m
        String escaped = StringEscapeUtils.escapeXml(getLatex());
        return URLEncoder.encode(escaped, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.lyncode.jtwig.functions.internal.string.UrlEncode.java

@Override
public Object execute(Object... arguments) throws FunctionException {
    if (arguments.length != 1)
        throw new FunctionException("Invalid number of arguments");
    if (arguments[0] == null)
        return null;
    try {/*www . jav a 2 s  .  c o  m*/
        if (arguments[0] instanceof Map)
            return encodeMap((Map) arguments[0]);
        return URLEncoder.encode(arguments[0].toString(), Charset.defaultCharset().displayName());
    } catch (UnsupportedEncodingException e) {
        throw new FunctionException(e);
    }
}

From source file:io.pivotal.cla.mvc.util.UrlBuilder.java

@SneakyThrows
public static String createSyncUrl(HttpServletRequest request, String claName, String repositoryId,
        int pullRequestId) {
    String urlEncodedClaName = URLEncoder.encode(claName, "UTF-8");
    UrlBuilder url = UrlBuilder //
            .fromRequest(request) //
            .path("/sync/" + urlEncodedClaName) //
            .param("repositoryId", repositoryId) //
            .param("pullRequestId", String.valueOf(pullRequestId));
    return url.build();
}

From source file:com.integrareti.integraframework.util.RequestUtil.java

/**
 * Generates an encoded and compressed String from the specified
 * XML-formatted String. The String is encoded in the following order:
 * <p>/*  w  w  w . j  av  a2s  .c o m*/
 * 1. URL encode <br>
 * 2. Base64 encode <br>
 * 3. Deflate <br>
 * 
 * @param xmlString
 *            XML-formatted String that is to be encoded
 * @return String containing the encoded contents of the specified XML
 *         String
 */
public static String encodeMessage(String xmlString) throws IOException, UnsupportedEncodingException {
    // first DEFLATE compress the document (saml-bindings-2.0,
    // section 3.4.4.1)
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();
    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream.toByteArray());
    String base64EncodedMessage = new String(base64EncodedByteArray);
    // finally, URL encode it
    String urlEncodedMessage = URLEncoder.encode(base64EncodedMessage, "UTF-8");
    return urlEncodedMessage;
}

From source file:uk.ac.bbsrc.tgac.miso.core.util.TaxonomyUtils.java

public static String checkScientificNameAtNCBI(String scientificName) {
    try {//from ww w . j  a  v  a 2s  .com
        String query = ncbiEntrezUtilsURL + "db=taxonomy&term=" + URLEncoder.encode(scientificName, "UTF-8");
        final HttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(query);
        try {
            HttpResponse response = httpclient.execute(httpget);
            String out = parseEntity(response.getEntity());
            log.info(out);
            try {
                DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document d = docBuilder.newDocument();

                TransformerFactory.newInstance().newTransformer()
                        .transform(new StreamSource(new UnicodeReader(out)), new DOMResult(d));

                NodeList nl = d.getElementsByTagName("Id");
                for (int i = 0; i < nl.getLength(); i++) {
                    Element e = (Element) nl.item(i);
                    return e.getTextContent();
                }
            } catch (ParserConfigurationException e) {
                log.error("check scientific name at NCBI", e);
            } catch (TransformerException e) {
                log.error("check scientific name at NCBI", e);
            }
        } catch (ClientProtocolException e) {
            log.error("check scientific name at NCBI", e);
        } catch (IOException e) {
            log.error("check scientific name at NCBI", e);
        }
    } catch (UnsupportedEncodingException e) {
        log.error("check scientific name at NCBI", e);
    }
    return null;
}

From source file:net.http.DemoService.java

public void getJobsTask() {

    List<Job> allJobs = new ArrayList<Job>();
    boolean isLastPage = false;
    int pageCount = 1;

    // goes through pages and collects job and employers ids and links
    while (!isLastPage) {

        String urlParameters = null;

        try {/*from w w  w  . jav  a  2 s. c  o  m*/
            urlParameters = "?published=" + URLEncoder.encode("1", "UTF-8") + "&page="
                    + URLEncoder.encode(String.valueOf(pageCount), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("UnsupportedEncodingException: " + e.toString() + ". Parameters: " + urlParameters);
            e.printStackTrace();
        }

        // svi poslovi
        String response = null;
        try {
            response = HttpRequestHandling.sendGet("http://www.moj-posao.net/Pretraga-Poslova/", urlParameters);
        } catch (IOException e) {
            log.error("IOException: " + e.toString() + ". Parameters: " + urlParameters);
            e.printStackTrace();
        }

        jp.setHtml(response);

        if (jp.featuredJobsExist()) {
            allJobs = jp.getFeaturedJobIdAndLink(allJobs);
        }

        isLastPage = jp.checkIfLastPage();

        if (isLastPage) {
            if (jp.regionalJobFirst()) {
                break;
            } else {
                allJobs = jp.getJobIdAndLink(allJobs);
            }
        } else {
            allJobs = jp.getJobIdAndLink(allJobs);
        }

        pageCount++;
    }

    String response = null;

    // iterates through jobs and saves them into database if they don't
    // exist
    int count = 0;
    for (Job job : allJobs) {

        // if job doesn't exist in database
        if (jobDaoManager.getJobById(job.getId()) == null) {

            Employer employer = null;

            // if employer id is undefined on page
            if (job.getEmployer().getId() == 0 || job.getEmployer().getId() >= 10000000) {
                employer = employerDaoManager.getEmployerByName(job.getEmployer().getName());

                // if employer exists in database
                if (employer != null) {
                    job.setEmployer(employer);
                } else {
                    // employer doesn't exist in database
                    do {
                        int employerId = Utils.generateRandomNumber(10000000, 99999999);
                        employer = employerDaoManager.getEmployerById(employerId);
                        if (employer == null) {
                            job.getEmployer().setId(employerId);
                            employerDaoManager.saveEmployer(job.getEmployer());
                            break;
                        }
                    } while (employer != null);
                }
            } else {

                employer = employerDaoManager.getEmployerById(job.getEmployer().getId());

                // if employer exists in database
                if (employer != null) {
                    job.setEmployer(employer);
                } else {
                    try {
                        response = HttpRequestHandling.sendGet(job.getEmployer().getLink(), "");
                    } catch (IOException e) {
                        log.error("IOException: " + e.toString() + ". Employer link: "
                                + job.getEmployer().getLink());
                        e.printStackTrace();
                    }

                    jp.setHtml(response);
                    String address = jp.getEmployerAddress();
                    job.getEmployer().setAddress(address);

                    employerDaoManager.saveEmployer(job.getEmployer());
                }
            }

            try {
                response = HttpRequestHandling.sendGet(job.getLink(), "");
            } catch (IOException e) {
                log.error("IOException: " + e.toString() + ". Job link: " + job.getLink());
                e.printStackTrace();
            }

            jp.setHtml(response);

            String title = jp.getTitle();
            if (title == null || title.equals("")) {
                log.error("Title error = no title, job_id: " + job.getId());
                continue;
            }

            Date deadline = jp.getApplicationDeadline();
            if (deadline == null) {
                log.error("Deadline error = no deadline, job_id: " + job.getId());
                continue;
            }

            job.setTitle(title);
            job.setDeadline(jp.getApplicationDeadline());
            job.setDescription(jp.getDescription());
            job.setConditions(jp.getConditions());
            job.setQualifications(jp.getQualification());
            job.setYearsOfExperience(jp.getYearsOfExperience());
            job.setLanguages(jp.getLanguages());
            job.setSkills(jp.getSkills());
            job.setDrivingLicence(jp.getDrivingLicense());
            job.setEmployerOffer(jp.getEmployeeOffer());
            job.setJobTypes(jp.getJobTypes());
            job.setCategories(jp.getCategories());
            job.setCounties(jp.getCounties());

            jobDaoManager.saveJob(job);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("InterruptedException: " + e.toString());
                e.printStackTrace();
            }
            count++;
        }
    }

    System.out.println();
}

From source file:Main.java

private static String encodeUrlParam(String value, String charset) throws UnsupportedEncodingException {
    if (value == null) {
        return "";
    }//from ww w .j  a  v a  2  s .  c  om

    try {
        String decoded = URLDecoder.decode(value, charset);

        String result = "";
        for (int i = 0; i < decoded.length(); i++) {
            char ch = decoded.charAt(i);
            result += (ch == '#') ? "#" : URLEncoder.encode(String.valueOf(ch), charset);
        }

        return result;
    } catch (IllegalArgumentException e) {
        return value;
    }
}

From source file:fr.pasteque.client.utils.URLTextGetter.java

public static void getText(final String url, final Map<String, String> getParams,
        final Map<String, String> postParams, final Handler h) {
    new Thread() {
        @Override//from   w ww .j a va2  s  .co  m
        public void run() {
            try {
                String fullUrl = url;
                if (getParams != null && getParams.size() > 0) {
                    fullUrl += "?";
                    for (String param : getParams.keySet()) {
                        fullUrl += URLEncoder.encode(param, "utf-8") + "="
                                + URLEncoder.encode(getParams.get(param), "utf-8") + "&";
                    }
                }
                if (fullUrl.endsWith("&")) {
                    fullUrl = fullUrl.substring(0, fullUrl.length() - 1);
                }
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = null;
                if (postParams == null) {
                    HttpGet req = new HttpGet(fullUrl);
                    response = client.execute(req);
                } else {
                    HttpPost req = new HttpPost(fullUrl);
                    List<NameValuePair> args = new ArrayList<NameValuePair>();
                    for (String key : postParams.keySet()) {
                        String value = postParams.get(key);
                        args.add(new BasicNameValuePair(key, value));
                    }
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(args, HTTP.UTF_8);
                    req.setEntity(entity);
                    response = client.execute(req);
                }
                int status = response.getStatusLine().getStatusCode();
                if (status == HttpStatus.SC_OK) {
                    // Get http response
                    String content = "";
                    try {
                        final int size = 10240;
                        ByteArrayOutputStream bos = new ByteArrayOutputStream(size);
                        byte[] buffer = new byte[size];
                        BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent(),
                                size);
                        int read = bis.read(buffer, 0, size);
                        while (read != -1) {
                            bos.write(buffer, 0, read);
                            read = bis.read(buffer, 0, size);
                        }
                        content = new String(bos.toByteArray());
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    if (h != null) {
                        Message m = h.obtainMessage();
                        m.what = SUCCESS;
                        m.obj = content;
                        m.sendToTarget();
                    }
                } else {
                    if (h != null) {
                        Message m = h.obtainMessage();
                        m.what = STATUS_NOK;
                        m.obj = new Integer(status);
                        m.sendToTarget();
                    }
                }
            } catch (IOException e) {
                if (h != null) {
                    Message m = h.obtainMessage();
                    m.what = ERROR;
                    m.obj = e;
                    m.sendToTarget();
                }
            }
        }
    }.start();
}

From source file:EscapeHTML.java

/**
 * Synonym for <tt>URLEncoder.encode(String, "UTF-8")</tt>.
 *
 * <P>Used to ensure that HTTP query strings are in proper form, by escaping
 * special characters such as spaces./*from   w w w.  j a v a2s  .c  o  m*/
 *
 * <P>An example use case for this method is a login scheme in which, after successful
 * login, the user is redirected to the "original" target destination. Such a target
        
 * might be passed around as a request parameter. Such a request parameter
 * will have a URL as its value, as in "LoginTarget=Blah.jsp?this=that&blah=boo", and
 * would need to be URL-encoded in order to escape its special characters.
 *
 * <P>It is important to note that if a query string appears in an <tt>HREF</tt>
 * attribute, then there are two issues - ensuring the query string is valid HTTP
 * (it is URL-encoded), and ensuring it is valid HTML (ensuring the ampersand is escaped).
 */
public String escapeURL(String aURLFragment) {
    String result = null;
    try {
        result = URLEncoder.encode(aURLFragment, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException("UTF-8 not supported", ex);
    }
    return result;
}

From source file:com.grandcircus.controller.GoogleGeocode.java

/**
 * Build the url given the string of a physical address
 *
 * @param address the string representation of a physical address
 * @return full URL of API call, as String. null if address is empty
 *///from w  w w. j  a  v a2 s.  c o  m
private static String buildURL(String address) throws UnsupportedEncodingException {
    if (address == null || address.equals("")) {
        return null;
    }

    String requestUrl = GOOGLE_GEOCODE_URL_STUB;
    requestUrl += "address=" + URLEncoder.encode(address, "UTF-8");

    return requestUrl;
}