Example usage for java.net URLDecoder decode

List of usage examples for java.net URLDecoder decode

Introduction

In this page you can find the example usage for java.net URLDecoder decode.

Prototype

public static String decode(String s, Charset charset) 

Source Link

Document

Decodes an application/x-www-form-urlencoded string using a specific java.nio.charset.Charset Charset .

Usage

From source file:org.cytoscape.app.internal.net.server.CyHttpRequestImpl.java

public CyHttpRequestImpl(final HttpRequest request) {
    final String uriEncoded = request.getRequestLine().getUri();
    try {/*  w w  w . ja v  a2s.  c o m*/
        uri = URLDecoder.decode(uriEncoded, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unable to parse URI: " + uriEncoded, e);
    }

    method = request.getRequestLine().getMethod().toUpperCase();

    headers = new HashMap<String, String>();
    for (final Header header : request.getAllHeaders()) {
        final String name = header.getName();
        String value = header.getValue();
        if (headers.containsKey(name))
            value = headers.get(name) + '\n' + value;
        headers.put(name, value);
    }

    if (request instanceof HttpEntityEnclosingRequest) {
        final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        contentType = entity.getContentType().getValue();
        try {
            content = EntityUtils.toString(entity);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read entity as string", e);
        }
    } else {
        contentType = null;
        content = null;
    }
}

From source file:org.mobicents.servlet.sip.restcomm.util.HttpUtils.java

public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException {
    final int length = (int) entity.getContentLength();
    final byte[] data = new byte[length];
    entity.getContent().read(data, 0, length);
    final String input = new String(data);
    final String[] tokens = input.split("&");
    final Map<String, String> map = new HashMap<String, String>();
    for (final String token : tokens) {
        final String[] parts = token.split("=");
        if (parts.length == 1) {
            map.put(parts[0], null);//from ww  w .  j  a v  a  2  s.com
        } else if (parts.length == 2) {
            map.put(parts[0], URLDecoder.decode(parts[1], "UTF-8"));
        }
    }
    return map;
}

From source file:com.autentia.tnt.servlet.DocServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uri = request.getRequestURI();
    log.debug("doGet - uri='" + uri + "'");

    int i = uri.indexOf(URL_PREFIX);
    if (i != -1) {
        String relPath = uri.substring(i + URL_PREFIX.length());
        relPath = URLDecoder.decode(relPath, "UTF-8");
        log.debug("doGet - relPath='" + relPath + "'");

        File f = new File(ConfigurationUtil.getDefault().getUploadPath() + relPath);
        if (f.exists()) {
            response.setContentLength((int) f.length());

            String mime = request.getParameter(ARG_MIME);
            if (mime != null && !mime.equals("")) {
                response.setContentType(mime);
            }/*from ww w  .  jav a  2 s  .  c o m*/
            OutputStream out = response.getOutputStream();
            InputStream in = null;
            try {
                in = new FileInputStream(f);
                byte[] buffer = new byte[8192];
                int nr;
                while ((nr = in.read(buffer)) != -1) {
                    out.write(buffer, 0, nr);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Bad URL prefix for servlet: check your web.xml file");
    }
}

From source file:com.autentia.tnt.servlet.DocRootServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String uri = request.getRequestURI();
    log.debug("doGet - uri='" + uri + "'");

    int i = uri.indexOf(URL_PREFIX);
    if (i != -1) {
        String relPath = uri.substring(i + URL_PREFIX.length());

        relPath = URLDecoder.decode(relPath, "UTF-8");
        log.debug("doGet - relPath='" + relPath + "'");

        File f = new File(ConfigurationUtil.getDefault().getDocumentRootPath() + relPath);
        if (f.exists()) {
            response.setContentLength((int) f.length());

            String mime = request.getParameter(ARG_MIME);
            if (mime != null && !mime.equals("")) {
                response.setContentType(mime);
            }//w  ww. j a  va 2s.co  m
            OutputStream out = response.getOutputStream();
            InputStream in = null;
            try {
                in = new FileInputStream(f);
                byte[] buffer = new byte[8192];
                int nr;
                while ((nr = in.read(buffer)) != -1) {
                    out.write(buffer, 0, nr);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Bad URL prefix for servlet: check your web.xml file");
    }
}

From source file:org.geomajas.gwt2.example.base.server.mvc.AjaxProxyController.java

@RequestMapping(value = "/")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");

    HttpClient client = new DefaultHttpClient();
    try {/*from  w ww. ja  va2s . co  m*/
        HttpRequestBase proxyRequest;

        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!paramName.equalsIgnoreCase("url")) {
                    url = addParam(url, paramName, request.getParameter(paramName));
                }
            }

            proxyRequest = new HttpGet(url);
        } else if ("POST".equals(request.getMethod())) {
            proxyRequest = new HttpPost(url);

            // Set any eventual parameters that came with our original
            HttpParams params = new BasicHttpParams();
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!"url".equalsIgnoreCase("url")) {
                    params.setParameter(paramName, request.getParameter(paramName));
                }
            }
            proxyRequest.setParams(params);
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }

        // Execute the method
        HttpResponse proxyResponse = client.execute(proxyRequest);

        // Set the content type, as it comes from the server
        Header[] headers = proxyResponse.getAllHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }

        // Write the body, flush and close
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:com.opentok.test.Helpers.java

private static Map<String, String> decodeFormData(String formData) throws UnsupportedEncodingException {
    Map<String, String> decodedFormData = new HashMap<String, String>();
    String[] pairs = formData.split("\\&");
    for (int i = 0; i < pairs.length; i++) {
        String[] fields = pairs[i].split("=");
        String name = URLDecoder.decode(fields[0], "UTF-8");
        String value = URLDecoder.decode(fields[1], "UTF-8");
        decodedFormData.put(name, value);
    }/*ww w .  ja  v a 2 s.  co m*/
    return decodedFormData;
}

From source file:mobile.controllers.MobileApp.java

@BodyParser.Of(value = BodyParser.Raw.class, maxLength = 5 * 1024 * 1024)
public static Result uploadLog(String from, String comment) {
    if (request().body().isMaxSizeExceeded()) {
        return MobileResult.error("290001", "?5M").getResult();
    }/*from  ww  w  .  ja v  a2 s  .  c om*/

    if (StringUtils.isNotBlank(comment)) {
        try {
            comment = URLDecoder.decode(comment, "utf-8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("url?", e);
        }
    }

    File file = request().body().asRaw().asFile();
    if (null == file || file.length() <= 0) {
        return MobileResult.error("100005", "?0").getResult();
    }

    ClientLogService.uploadLog(from, file, comment);

    return MobileResult.success().getResult();
}

From source file:io.lightlink.utils.ClasspathScanUtils.java

public static List<String> getResourcesFromPackage(String packageName) throws IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> packageURLs;
    ArrayList<String> names = new ArrayList<String>();

    packageName = packageName.replace(".", "/");
    packageURLs = classLoader.getResources(packageName);

    while (packageURLs.hasMoreElements()) {
        URL packageURL = packageURLs.nextElement();
        // loop through files in classpath

        if (packageURL.getProtocol().equals("jar")) {
            String jarFileName;//from   ww  w.ja va  2 s  . c  o m
            JarFile jf;
            Enumeration<JarEntry> jarEntries;
            String entryName;

            // build jar file name, then loop through zipped entries
            jarFileName = URLDecoder.decode(packageURL.getFile(), "UTF-8");
            jarFileName = jarFileName.substring(5, jarFileName.indexOf("!"));
            jf = new JarFile(jarFileName);
            jarEntries = jf.entries();
            while (jarEntries.hasMoreElements()) {
                entryName = jarEntries.nextElement().getName();
                if (entryName.startsWith(packageName) && entryName.length() > packageName.length() + 5) {
                    entryName = entryName.substring(packageName.length());
                    names.add(entryName);
                }
            }

        } else {

            findFromDirectory(packageURL, names);
        }
    }

    return names;
}

From source file:com.cloudera.sqoop.util.Jars.java

/**
 * Return the jar file path that contains a particular class.
 * Method mostly cloned from o.a.h.mapred.JobConf.findContainingJar().
 */// w w  w .ja v a2 s. co m
public static String getJarPathForClass(Class<? extends Object> classObj) {
    ClassLoader loader = classObj.getClassLoader();
    String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                // URLDecoder is a misnamed class, since it actually decodes
                // x-www-form-urlencoded MIME type rather than actual
                // URL encoding (which the file path has). Therefore it would
                // decode +s to ' 's which is incorrect (spaces are actually
                // either unencoded or encoded as "%20"). Replace +s first, so
                // that they are kept sacred during the decoding process.
                toReturn = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:me.rgcjonas.portableMinecraftLauncher.Main.java

/**
 * returns the working directory for the portable minecraft instance
 *///from   w w  w. j av  a 2 s  .co m
public static File getWorkingDirectory() {
    String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    String decodedPath = null;
    try {
        decodedPath = URLDecoder.decode(path, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        //this is very unlikely to happen, we're just making eclipse happy
        e.printStackTrace();
    }

    File ourDir = null;
    if (decodedPath.endsWith(".jar")) {
        //inside a jar file -> new dir named like the jar file
        ourDir = new File(decodedPath.substring(0, decodedPath.length() - 4));
    } else {
        //subdir 'minecraft'
        ourDir = new File(decodedPath, "minecraft");
    }

    //HACK: make it absolute here, since the other code requires
    File workDir = new File(ourDir.getAbsolutePath());
    return workDir;
}