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.ala.spatial.web.services.SitesBySpeciesWSControllerTabulated.java

@RequestMapping(value = "/ws/sitesbyspeciestabulated", method = { RequestMethod.POST, RequestMethod.GET })
public @ResponseBody String processgeoq(HttpServletRequest req) {

    try {/*  w  ww.  ja va  2s.co m*/

        long currTime = System.currentTimeMillis();

        String currentPath = AlaspatialProperties.getBaseOutputDir() + "output" + File.separator
                + "sitesbyspecies";

        String speciesq = URLDecoder.decode(req.getParameter("q"), "UTF-8").replace("__", ".");
        String area = req.getParameter("area");

        String bs = req.getParameter("bs");
        String biocacheurl = URLDecoder.decode(bs == null ? AlaspatialProperties.getBiocacheWsURL() : bs,
                "UTF-8");

        double gridsize = Double.parseDouble(req.getParameter("gridsize"));
        String layers = req.getParameter("layers");
        if (layers != null) {
            layers = URLDecoder.decode(layers, "UTF-8");
        }
        String facetName = req.getParameter("facetname");
        if (facetName == null) {
            facetName = "names_and_lsid";
        }

        LayerFilter[] filter = null;
        SimpleRegion region = null;
        if (area != null && area.startsWith("ENVELOPE")) {
            filter = LayerFilter.parseLayerFilters(area);
        } else {
            region = SimpleShapeFile.parseWKT(area);
        }

        String pid = Long.toString(currTime);

        AnalysisJobSitesBySpeciesTabulated sbs = new AnalysisJobSitesBySpeciesTabulated(pid, currentPath, "",
                speciesq, gridsize, region, filter, biocacheurl, layers == null ? null : layers.split(","),
                true, facetName);

        StringBuffer inputs = new StringBuffer();
        inputs.append("pid:").append(pid);
        inputs.append(";speciesq:").append(speciesq);
        inputs.append(";gridsize:").append(gridsize);
        inputs.append(";area:").append(area);
        sbs.setInputs(inputs.toString());
        AnalysisQueue.addJob(sbs);

        return pid;

    } catch (Exception e) {
        e.printStackTrace(System.out);
    }

    return "";
}

From source file:com.janoz.usenet.processors.impl.NZBGetProcessor.java

@Override
public void validateResponse(InputStream responseStream) throws RetrieveException {
    Cookie uploadStatus = super.getCookie("upload_status");
    if (uploadStatus != null) {
        try {//from  w ww.  j  ava  2  s  . c  o m
            String status = stripTags(URLDecoder.decode(uploadStatus.getValue(), "UTF8"));
            if (status.startsWith("Error")) {
                throw new RetrieveException("NzbGetWeb " + status.replace('\n', ' '));
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error("UTF8 encoding not available. This should have been impossible");
            throw new RuntimeException("UTF8 encoding not available. This should have been impossible");
        }
    } else {
        if (isLoginResponse(responseStream)) {
            throw new RetrieveException("Authorization required.");
        }
        throw new RetrieveException("Unknown response from NzbGetWeb.");
    }

}

From source file:my.home.lehome.asynctask.LoadLongMsgAsyncTask.java

@Override
protected Integer doInBackground(String... params) {
    String url = params[0];//from   w w w  .j a v a 2  s . co m
    Log.d(TAG, "background task url: " + url);
    if (TextUtils.isEmpty(url))
        return 400;
    HttpResponse response = null;
    String content = null;
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        response = client.execute(request);
        content = EntityUtils.toString(response.getEntity());
    } catch (URISyntaxException | IOException e) {
        mHandler.getWhat().putString("err_msg", mContext.get().getString(R.string.long_msg_http_exception));
        return 400;
    }

    JSONTokener jsonParser = new JSONTokener(content);
    try {
        JSONObject cmdObject = (JSONObject) jsonParser.nextValue();
        content = cmdObject.getString("data");
    } catch (Exception e) {
        mHandler.getWhat().putString("err_msg", mContext.get().getString(R.string.long_msg_parse_exception));
        return 400;
    }

    content = content.substring(4);
    try {
        content = URLDecoder.decode(content, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        mHandler.getWhat().putString("err_msg", mContext.get().getString(R.string.long_msg_parse_exception));
        return 400;
    }

    mHandler.getWhat().putString("response", content);
    return 200;
}

From source file:io.cettia.transport.http.HttpTransportServer.java

/**
 * For internal use only.//from w  ww .  j a va2 s  .c om
 */
public static Map<String, String> parseQuery(String uri) {
    Map<String, String> map = new LinkedHashMap<>();
    String query = URI.create(uri).getQuery();
    if (query == null || query.equals("")) {
        return Collections.unmodifiableMap(map);
    }
    String[] params = query.split("&");
    for (String param : params) {
        try {
            String[] pair = param.split("=", 2);
            String name = URLDecoder.decode(pair[0], "UTF-8");
            if (name.equals("")) {
                continue;
            }
            map.put(name, pair.length > 1 ? URLDecoder.decode(pair[1], "UTF-8") : "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return Collections.unmodifiableMap(map);
}

From source file:org.jamwiki.servlets.ImageServlet.java

/**
 * If a file corresponding to the request is on the filesystem return it,
 * otherwise return <code>null</code>.
 *//*from   w ww .jav  a 2s . c  o  m*/
private File retrieveFile(HttpServletRequest request) {
    String filename = request.getRequestURI().substring(request.getContextPath().length());
    try {
        filename = URLDecoder.decode(filename, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // this doesn't happen - UTF-8 is always supported
    }
    File file = new File(Environment.getValue(Environment.PROP_BASE_FILE_DIR), filename);
    return (file.exists()) ? file : null;
}

From source file:org.ocpsoft.redoculous.tests.git.DeleteAndReinitializeRepositoryTest.java

@Test
public void testInitializeRepositoryAndServeAsciidoc() throws Exception {
    WebTest test = new WebTest(baseUrl);
    String repositoryURL = "file://" + repository.getAbsolutePath();
    HttpAction<HttpPost> post = test.post("/api/v1/manage?repo=" + repositoryURL);
    Assert.assertEquals(201, post.getResponse().getStatusLine().getStatusCode());
    String location = URLDecoder.decode(post.getResponseHeaderValue("location"), "UTF8");
    Assert.assertEquals(test.getBaseURL() + test.getContextPath() + "/api/v1/serve?repo=" + repositoryURL,
            location);/*from w  w w .ja v a  2  s. c o m*/

    HttpAction<HttpGet> document = test
            .get("/api/v1/serve?repo=" + repositoryURL + "&ref=master&path=document");
    HttpAction<HttpGet> documentFull = test
            .get("/api/v1/serve?repo=" + repositoryURL + "&ref=master&path=document");

    Assert.assertTrue(document.getResponseContent().startsWith("<h1"));
    Assert.assertTrue(documentFull.getResponseContent().startsWith("<h1"));

    HttpAction<HttpDelete> delete = test.delete("/api/v1/manage?repo=" + repositoryURL);
    Assert.assertEquals(200, delete.getStatusCode());

    Files.write(this.document, getClass().getClassLoader().getResourceAsStream("asciidoc/notoc.asciidoc"));
    repo.add().addFilepattern("document.asciidoc").call();
    repo.commit().setMessage("No table of contents.").call();

    document = test.get("/api/v1/serve?repo=" + repositoryURL + "&ref=master&path=document");
    documentFull = test.get("/api/v1/serve?repo=" + repositoryURL + "&ref=master&path=document");

    Assert.assertTrue(document.getResponseContent().contains("This is a simple document."));
    Assert.assertTrue(documentFull.getResponseContent().contains("This is a simple document."));

}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static byte[] createSignedAndZippedPkPassArchive(final PKPass pass, final URL fileUrlOfTemplateDirectory,
        final PKSigningInformation signingInformation) throws Exception {
    String pathToTemplateDirectory = URLDecoder.decode(fileUrlOfTemplateDirectory.getFile(), "UTF-8");
    return createSignedAndZippedPkPassArchive(pass, pathToTemplateDirectory, signingInformation);
}

From source file:com.visionet.platform.cooperation.controller.OrderController.java

/**
 * ?  ?//w w  w .  j  a  v  a  2  s. c o m
 *
 * @param orderNo        ??
 * @param partnerOrderNo ???
 * @param evaluateScore  
 * @param describe       
 * @param sign           ??
 * @param channel        ?
 * @return
 * @author ?
 */
@RequestMapping(value = "evaluateDriver", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(notes = "?  ?", httpMethod = "POST", response = Response.class, value = "?  ?")
@ApiResponses(value = { @ApiResponse(code = 405, message = "invalid input") })
public Response<?> evaluateDriver(
        @ApiParam(required = true, value = "??") @RequestParam("orderNo") String orderNo,
        @ApiParam(required = true, value = "???") @RequestParam("partnerOrderNo") String partnerOrderNo,
        @ApiParam(required = true, value = "?15") @RequestParam("evaluateScore") Integer evaluateScore,
        @ApiParam(required = true, value = "") @RequestParam("describe") String describe,
        @ApiParam(required = true, value = "??1.8 sign?") @RequestParam("sign") String sign,
        @ApiParam(required = true, value = "???") @RequestParam("channel") String channel)
        throws Exception {
    orderService.evaluateDriver(orderNo, partnerOrderNo, evaluateScore, URLDecoder.decode(describe, UTF_8));
    return Response.OK();
}

From source file:org.nlp2rdf.webservice.NIFParameterWebserviceFactory.java

/**
 * Factory method/* w  ww . j  av a2 s  .  c o m*/
 *
 * @param httpServletRequest
 * @return
 */
public static NIFParameters getInstance(HttpServletRequest httpServletRequest, String defaultPrefix)
        throws ParameterException, IOException {

    //twice the size to split key value
    String[] args = new String[httpServletRequest.getParameterMap().size() * 2];

    int x = 0;

    for (Object key : httpServletRequest.getParameterMap().keySet()) {
        String pname = (String) key;
        //transform key to CLI style
        pname = (pname.length() == 1) ? "-" + pname : "--" + pname;

        //collect CLI args
        args[x++] = pname;
        args[x++] = httpServletRequest.getParameter((String) key);

    }

    String line;
    String content = "";
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream()));

        while ((line = reader.readLine()) != null) {
            if (line.startsWith("---") || line.startsWith("Content") || line.startsWith("html"))
                continue;
            content += line;

        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (args.length == 0 && !content.isEmpty()) {
        args = new String[4];
        String[] params = content.split("&");
        if (params.length > 0) {
            String[] i = params[0].split("=");
            String[] id = params[1].split("=");
            if (i.length > 0) {
                args[0] = "--" + i[0];
                args[1] = URLDecoder.decode(i[1], "UTF-8");
            }
            if (id.length > 0) {
                args[2] = "-" + id[0];
                args[3] = URLDecoder.decode(id[1], "UTF-8");
            }
            content = "";
        }
    }

    //        System.out.println(content);

    //parse CLI args
    OptionParser parser = ParameterParser.getParser(args, defaultPrefix);
    OptionSet options = ParameterParser.getOption(parser, args);

    // print help screen
    if (options.has("h")) {
        String addHelp = "";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        parser.printHelpOn(baos);
        throw new ParameterException(baos.toString());
    }

    // parse options with webservice setted to true
    return ParameterParserMS.parseOptions(options, true, content);
}

From source file:TargetsAPI.java

/**
 * Takes an Array of Image URLs and converts them into the JSON object the
 * Wikitude Cloud Targets API requires when using a POST request.
 * /* ww w.  j av  a 2 s  .  co  m*/
 * Remark: We use the open source JSON reference implementation for Java
 * available at https://github.com/douglascrockford/JSON-java in order to
 * handle JSON objects.
 * 
 * @param imageUrls
 *            The imageUrls that point to the targets.
 * @return A JSON object that the Wikitude Cloud Targets API requires.
 */
private JSONObject buildPayLoad(String[] imageUrls) {

    try {
        // create the array of target objects
        JSONArray urls = new JSONArray();
        // add each url into the array
        for (String imageUrl : imageUrls) {
            JSONObject obj = new JSONObject().put("url", URLDecoder.decode(imageUrl, "UTF-8"));
            urls.put(obj);
        }

        // return the JSON object that follows the API structure
        return new JSONObject().put("targets", urls);

    } catch (UnsupportedEncodingException e) {
        // in case UTF-8 is not available on the platform
        System.err.println("Encoding UTF-8 is not supported");
        e.printStackTrace();
        return null;
    }
}