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:io.wcm.sling.commons.util.Escape.java

/**
 * Applies URL-Encoding to the given parameter name or value. Uses {@link URLEncoder#encode(String, String)} with
 * UTF-8 character set, while avoiding the need to catch the UnsupportedEncodingException.
 * @param value the parameter name or value to encode
 * @return URL-encoded string - or empty string if the specified value was null
 * @throws RuntimeException in the very unlikely case that UTF-8 is not supported on the current system
 *///  www .  ja  va2s.c  o m
public static String urlEncode(String value) {
    if (value == null) {
        return "";
    }
    try {
        return URLEncoder.encode(value, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:net.shopxx.util.CookieUtils.java

/**
 * cookie/*from  w  w w . j  av a 2s.c  o m*/
 * 
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @param name
 *            cookie??
 * @param value
 *            cookie
 * @param path
 *            
 * @param maxAge
 *            (??: )
 * @param domain
 *            
 * @param secure
 *            ??
 */
public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, String path, Integer maxAge, String domain, Boolean secure) {
    Assert.notNull(request);
    Assert.notNull(response);
    Assert.hasText(name);
    try {
        value = URLEncoder.encode(value, "UTF-8");
        Cookie cookie = new Cookie(name, value);
        if (StringUtils.isNotEmpty(path)) {
            cookie.setPath(path);
        }
        if (maxAge != null) {
            cookie.setMaxAge(maxAge);
        }
        if (StringUtils.isNotEmpty(domain)) {
            cookie.setDomain(domain);
        }
        if (secure != null) {
            cookie.setSecure(secure);
        }
        response.addCookie(cookie);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}

From source file:Detect.java

/**
 * Detects the language of a supplied String.
 * //  w w  w. j  ava 2s.  c  o  m
 * @param text The String to detect the language of.
 * @return A DetectResult object containing the language, confidence and reliability.
 * @throws Exception on error.
 */
public static DetectResult execute(final String text) throws Exception {
    validateReferrer();

    final URL url = new URL(URL + URLEncoder.encode(text, ENCODING));

    final JSONObject json = retrieveJSON(url);

    return new DetectResult(Language.fromString(json.getJSONObject("responseData").getString("language")),
            json.getJSONObject("responseData").getBoolean("isReliable"),
            json.getJSONObject("responseData").getDouble("confidence"));
}

From source file:com.cognifide.aet.executor.xmlparser.xml.models.ModelConverterUtils.java

static List<ExtendedUrl> extendUrlsList(List<Url> urls) throws ParseException, UnsupportedEncodingException {
    List<ExtendedUrl> extendedUrls = Lists.newArrayList();
    List<ExtendedUrl> duplicatedUrls = Lists.newArrayList();
    Set<String> names = Sets.newHashSet();
    for (Url url : urls) {
        String urlName;/*from w  ww.java  2s.c o  m*/
        if (StringUtils.isBlank(url.getName())) {
            urlName = url.getHref().trim();
        } else {
            urlName = URLEncoder.encode(url.getName().trim(), StandardCharsets.UTF_8.displayName());
        }
        ExtendedUrl extendedUrl = new ExtendedUrl(url.getHref(), urlName, url.getDescription());
        if (!names.add(urlName)) {
            duplicatedUrls.add(extendedUrl);
        } else {
            extendedUrls.add(extendedUrl);
        }
    }
    if (!duplicatedUrls.isEmpty()) {
        StringBuilder builder = new StringBuilder("Duplicated urls:");
        for (ExtendedUrl url : duplicatedUrls) {
            builder.append(String.format("%n%s with name %s", url.getUrl(), url.getName()));
        }
        throw new ParseException(builder.toString());
    }
    return extendedUrls;
}

From source file:Main.java

private static String encode(final String content, final String encoding) {
    try {//from www.ja  v  a2  s . c  om
        return URLEncoder.encode(content, encoding != null ? encoding : "UTF-8");
    } catch (UnsupportedEncodingException problem) {
        throw new IllegalArgumentException(problem);
    }
}

From source file:us.askplatyp.kb.lucene.model.PartialCollection.java

private static String encode(String str) {
    try {/*from   w ww. ja va 2  s . co m*/
        return URLEncoder.encode(str, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return "";
    }
}

From source file:me.doshou.admin.maintain.editor.web.controller.utils.OnlineEditorUtils.java

public static Map<Object, Object> extractFileInfoMap(File currentFile, String rootPath)
        throws UnsupportedEncodingException {
    Map<Object, Object> info = Maps.newHashMap();
    String name = currentFile.getName();
    info.put("name", name);
    info.put("path",
            URLEncoder.encode(currentFile.getAbsolutePath().replace(rootPath, ""), Constants.ENCODING));
    info.put("canEdit", canEdit(name));
    info.put("hasParent", !currentFile.getPath().equals(rootPath));
    info.put("isParent", hasSubFiles(currentFile));
    info.put("isDirectory", currentFile.isDirectory());
    info.put("root", info.get("path").equals(""));
    info.put("open", info.get("path").equals(""));
    info.put("iconSkin", currentFile.isDirectory() ? CSS_DIRECTORY : CSS_FILE);
    info.put("size", currentFile.length());
    Date modifiedDate = new Date(currentFile.lastModified());
    info.put("lastModified", DateFormatUtils.format(modifiedDate, DATE_PATTERN));
    info.put("lastModifiedForLong", currentFile.lastModified());
    return info;/*  www.j av a 2s .c  om*/
}

From source file:de.jetwick.util.Translate.java

/**
 * Translates text from a given Language to another given Language using Google Translate.
 * //w ww  . ja  va2s . c om
 * @param text The String to translate.
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception on error.
 */
public static String execute(final String text, final Language from, final Language to) throws Exception {
    String url = URL.replaceAll("#FROM#", from.toString()).replaceAll("#TO#", to.toString())
            + URLEncoder.encode(text, "UTF8");
    JSONArray arr = new JSONArray(download(url));
    return arr.getJSONArray(0).getJSONArray(0).getString(0);
}

From source file:de.tudarmstadt.ukp.argumentation.data.roomfordebate.DataFetcher.java

/**
 * Crawls all URLs from the given list and stores them in the output folder; files that
 * already exist in the output folder are skipped
 *
 * @param urls      list of urls for Room for debate
 * @param outputDir output// w  ww .  j a v a 2  s .c  o m
 * @throws IOException ex
 */
public static void crawlPages(List<String> urls, File outputDir) throws IOException {
    for (String url : urls) {
        // file name
        File outFile = new File(outputDir, URLEncoder.encode(url, "utf-8") + ".html");

        if (!outFile.exists()) {
            NYTimesCommentsScraper nyTimesCommentsScraper = new NYTimesCommentsScraper();

            String html;
            try {
                html = nyTimesCommentsScraper.readHTML(url);
            } catch (InterruptedException e) {
                throw new IOException(e);
            }

            FileUtils.writeStringToFile(outFile, html);
        }
    }
}

From source file:edu.stolaf.cs.wmrserver.streaming.StreamJob.java

public static void setStreamMapper(JobConf conf, String mapCommand) {
    conf.setMapperClass(PipeMapper.class);
    conf.setMapRunnerClass(PipeMapRunner.class);
    try {/*from  ww  w  . j  a v  a  2  s  .  c  om*/
        conf.set("stream.map.streamprocessor", URLEncoder.encode(mapCommand, "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        // This is VERY likely to happen. Especially since the ENTIRE FREAKING
        // STRING IMPLEMENTATION is based on UTF-8. Thanks, Java.
        throw new RuntimeException("The sky is falling! Java doesn't support UTF-8.");
    }
}