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:coria2015.server.ContentServlet.java

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

    final URL url;
    IMAGE_URI = "/recipe/image/";
    if (request.getRequestURI().startsWith(IMAGE_URI)) {

        String recipeName = URLDecoder.decode(request.getRequestURI().substring(IMAGE_URI.length()), "UTF-8")
                .replace(" ", "-");
        String name = recipeImages.get(recipeName);
        File file = new File(imagePath, name);
        url = file.toURI().toURL();/* ww  w. j  a v a  2s  . co  m*/
    } else {
        url = ContentServlet.class.getResource(format("/web%s", request.getRequestURI()));
    }

    if (url != null) {
        FileSystemManager fsManager = VFS.getManager();
        FileObject file = fsManager.resolveFile(url.toExternalForm());
        if (file.getType() == FileType.FOLDER) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            response.setHeader("Location", format("%sindex.html", request.getRequestURI()));
            return;
        }

        String filename = url.getFile();
        if (filename.endsWith(".html"))
            response.setContentType("text/html");
        else if (filename.endsWith(".png"))
            response.setContentType("image/png");
        else if (filename.endsWith(".css"))
            response.setContentType("text/css");
        response.setStatus(HttpServletResponse.SC_OK);

        final ServletOutputStream out = response.getOutputStream();
        InputStream in = url.openStream();
        byte[] buffer = new byte[8192];
        int read;
        while ((read = in.read(buffer)) > 0) {
            out.write(buffer, 0, read);
        }
        out.flush();
        in.close();
        return;
    }

    // Not found
    error404(request, response);

}

From source file:be.fedict.eid.applet.service.signer.asic.ASiCURIDereferencer.java

public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException {
    if (null == uriReference) {
        throw new URIReferenceException("URIReference cannot be null");
    }//w  ww. j av a2 s  .  c  om
    if (null == context) {
        throw new URIReferenceException("XMLCrytoContext cannot be null");
    }

    String uri = uriReference.getURI();
    try {
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("could not URL decode the uri: " + uri);
    }
    LOG.debug("dereference: " + uri);

    InputStream zipInputStream;
    if (null != this.tmpFile) {
        try {
            zipInputStream = new FileInputStream(this.tmpFile);
        } catch (FileNotFoundException e) {
            throw new URIReferenceException("file not found error: " + e.getMessage(), e);
        }
    } else {
        zipInputStream = new ByteArrayInputStream(this.data);
    }
    InputStream dataInputStream;
    try {
        dataInputStream = ODFUtil.findDataInputStream(zipInputStream, uri);
    } catch (IOException e) {
        throw new URIReferenceException("I/O error: " + e.getMessage(), e);
    }
    if (null == dataInputStream) {
        return this.baseUriDereferener.dereference(uriReference, context);
    }
    return new OctetStreamData(dataInputStream, uri, null);
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS
 * //from w  w w.  j  a  va  2  s . c  o m
 * @param folder
 * @return
 * @throws IOException
 */
public static URL[] getResources(String folder) throws IOException {
    List<URL> urls = new ArrayList<URL>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new IOException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(folder);
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            String resProtocol = res.getProtocol();
            if (resProtocol.equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {
                    if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) {
                        urls.add(new URL(
                                joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name
                    }
                }
            } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method toUrl = null;
                    for (Object o : files) {
                        if (toUrl == null) {
                            toUrl = o.getClass().getMethod("toURL");
                        }
                        urls.add((URL) toUrl.invoke(o));
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else if (resProtocol.equalsIgnoreCase("file")) {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            } else {
                throw new IOException("Unknown protocol for resource: " + res.toString());
            }
        }
    } catch (NullPointerException x) {
        throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)");
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file)));
            }
        } else {
            throw new IOException(
                    folder + " (" + directory.getPath() + ") does not appear to be a valid folder");
        }
    }
    URL[] urlsA = new URL[urls.size()];
    urls.toArray(urlsA);
    return urlsA;
}

From source file:com.digitalpebble.stormcrawler.protocol.file.FileResponse.java

public FileResponse(String u, Metadata md, FileProtocol fp) throws MalformedURLException, IOException {

    fileProtocol = fp;//from  w  w  w  . j ava 2  s . c om
    metadata = md;

    URL url = new URL(u);

    if (!url.getPath().equals(url.getFile())) {
        LOG.warn("url.getPath() != url.getFile(): {}.", url);
    }

    String path = "".equals(url.getPath()) ? "/" : url.getPath();

    File file = new File(URLDecoder.decode(path, fileProtocol.getEncoding()));

    if (!file.exists()) {
        statusCode = HttpStatus.SC_NOT_FOUND;
        return;
    }

    if (!file.canRead()) {
        statusCode = HttpStatus.SC_UNAUTHORIZED;
        return;
    }

    if (!file.equals(file.getCanonicalFile())) {
        metadata.setValue(HttpHeaders.LOCATION, file.getCanonicalFile().toURI().toURL().toString());
        statusCode = HttpStatus.SC_MULTIPLE_CHOICES;
        return;
    }

    if (file.isDirectory()) {
        getDirAsHttpResponse(file);
    } else if (file.isFile()) {
        getFileAsHttpResponse(file);
    } else {
        statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        return;
    }

    if (content == null) {
        content = new byte[0];
    }
}

From source file:com.niroshpg.android.gcm.RegisterServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    logger.warning(" start registering doPost");

    String regId = null;//from   w ww .  j a  va2s.  c  om
    //String regId = getParameter(req, PARAMETER_REG_ID);
    // logger.warning(" start registering " + regId);

    StringBuffer jb = new StringBuffer();
    logger.warning(" start registering : sb created");
    String line = null;
    try {
        BufferedReader reader = req.getReader();
        logger.warning(" start registering : reader created");
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /*report an error*/ }

    logger.warning(" start registering : jb append completed");
    JSONObject polygonJsonObject = null;

    Double minMagnitude = MIN_MAGNITUDE_DEFAULT; // default

    try {
        String encodeStr = new String(jb.toString().getBytes(), "UTF-8");
        //logger.warning(" start registering : encodeStr = " + encodeStr );
        String decodeStr = URLDecoder.decode(encodeStr, "UTF-8");
        // logger.warning(" start registering : decodeStr = " + decodeStr );
        JSONObject decodedJsonObj = new JSONObject(decodeStr);

        polygonJsonObject = decodedJsonObj.getJSONObject("polygon");
        Double minM = decodedJsonObj.getDouble("minMagnitude");
        if (minM != null) {
            minMagnitude = minM;
        }

        logger.warning(" start registering : from json regId = " + decodedJsonObj.getString("regId")
                + ", minM = " + minMagnitude);
        regId = decodedJsonObj.getString("regId");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        logger.warning(" start registering :json error : " + e.getMessage());
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        logger.warning(" start registering :encoding error");
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (polygonJsonObject == null) {
        logger.warning(" start registering : could not read json data");
    }

    // Work with the data using methods like...
    // int someInt = jsonObject.getInt("intParamName");
    // String someString = jsonObject.getString("stringParamName");
    // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
    // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
    // etc...
    if (regId != null && regId.length() > 0) {
        Datastore.register(regId, polygonJsonObject, minMagnitude);
    } else {
        logger.warning(" regId not found or invalid");
    }
    setSuccess(resp);
}

From source file:com.jaspersoft.jasperserver.api.security.externalAuth.sso.AbstractSsoAuthenticationProcessingFilter.java

/**
 * Attempt validation of SSO token./*from ww  w . j av  a2  s  . co m*/
 * @param request sso server request
 * @return {@link Authentication} with some of the principal information
 * @throws AuthenticationException if authentication fails
 */
@Override
public final Authentication attemptAuthentication(final HttpServletRequest request)
        throws AuthenticationException {
    try {

        logger.debug("Attempt authentication with SSO token ...");
        Object ticket = obtainTicket(request);

        logger.debug("SSO Token: " + ticket);
        String userName = obtainUsername(request);
        userName = userName != null ? URLDecoder.decode(userName, CharEncoding.UTF_8) : null;
        String password = obtainPassword(request);

        final SsoAuthenticationToken authToken = new SsoAuthenticationToken(ticket, userName, password);
        setDetails(request, authToken);
        return this.getAuthenticationManager().authenticate(authToken);
    } catch (UnsupportedEncodingException e) {
        logger.error("could not decode user name " + obtainUsername(request));
        throw new IllegalStateException(e);
    }
}

From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java

public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) {

    // Decode url link
    try {/*from   ww w . jav  a2  s  .c o  m*/
        channelUrl = URLDecoder.decode(channelUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString());
    }

    // Parse url
    Uri uri = uri = Uri.parse(channelUrl);
    ;
    int event;
    String text = null;
    String torrent = null;
    boolean header = true;

    // TODO delete itemCount, as it's not really used
    this.itemCount = 0;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    XmlPullParserFactory xmlFactoryObject;
    XmlPullParser xmlParser = null;

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    RSSFeed rssFeed = new RSSFeed();
    rssFeed.setChannelTitle(channelTitle);
    rssFeed.setChannelLink(channelUrl);

    httpclient = null;

    try {

        // Making HTTP request
        HttpHost targetHost = new HttpHost(uri.getAuthority());

        // httpclient = new DefaultHttpClient(httpParameters);
        // httpclient = new DefaultHttpClient();
        httpclient = getNewHttpClient();

        httpclient.setParams(httpParameters);

        //            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        //            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        //
        //            httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        // set http parameters

        HttpGet httpget = new HttpGet(channelUrl);

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

        xmlFactoryObject = XmlPullParserFactory.newInstance();
        xmlParser = xmlFactoryObject.newPullParser();

        xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        xmlParser.setInput(is, null);

        event = xmlParser.getEventType();

        // Get Channel info
        String name;
        RSSFeedItem item = null;
        ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>();

        // Get items
        while (event != XmlPullParser.END_DOCUMENT) {

            name = xmlParser.getName();

            switch (event) {
            case XmlPullParser.START_TAG:

                if (name != null && name.equals("item")) {
                    header = false;
                    item = new RSSFeedItem();
                    itemCount = itemCount + 1;
                }

                try {
                    for (int i = 0; i < xmlParser.getAttributeCount(); i++) {

                        if (xmlParser.getAttributeName(i).equals("url")) {
                            torrent = xmlParser.getAttributeValue(i);

                            if (torrent != null) {
                                torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8"));
                            }
                            break;
                        }
                    }
                } catch (Exception e) {

                }

                break;

            case XmlPullParser.TEXT:
                text = xmlParser.getText();
                break;

            case XmlPullParser.END_TAG:

                if (name.equals("title")) {
                    if (!header) {
                        item.setTitle(text);
                        //                                Log.d("Debug", "PARSER - Title: " + text);
                    }
                } else if (name.equals("description")) {
                    if (header) {
                        //                                Log.d("Debug", "Channel Description: " + text);
                    } else {
                        item.setDescription(text);
                        //                                Log.d("Debug", "Description: " + text);
                    }
                } else if (name.equals("link")) {
                    if (!header) {
                        item.setLink(text);
                        //                                Log.d("Debug", "Link: " + text);
                    }

                } else if (name.equals("pubDate")) {

                    // Set item pubDate
                    if (item != null) {
                        item.setPubDate(text);
                    }

                } else if (name.equals("enclosure")) {
                    item.setTorrentUrl(torrent);
                    //                            Log.d("Debug", "Enclosure: " + torrent);
                } else if (name.equals("item") && !header) {

                    if (items != null & item != null) {

                        // Fix torrent url for no-standard rss feeds
                        if (torrent == null) {

                            String link = item.getLink();

                            if (link != null) {
                                link = Uri.decode(URLEncoder.encode(link, "UTF-8"));
                            }

                            item.setTorrentUrl(link);
                        }

                        items.add(item);
                    }

                }

                break;
            }

            event = xmlParser.next();

            //                if (!header) {
            //                    items.add(item);
            //                }

        }

        // Filter items

        //            Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<");
        if (filter != null && !filter.equals("")) {

            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {

                item = (RSSFeedItem) iterator.next();

                // If link doesn't match filter, remove it
                //                    Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<");

                Pattern patter = Pattern.compile(filter);

                Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object

                if (!(matcher.find())) {
                    iterator.remove();
                }

            }
        }

        rssFeed.setItems(items);
        rssFeed.setItemCount(itemCount);
        rssFeed.setChannelPubDate(items.get(0).getPubDate());
        rssFeed.setResultOk(true);

        is.close();
    } catch (Exception e) {
        Log.e("Debug", "RSSFeedParser - : " + e.toString());
        rssFeed.setResultOk(false);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }

    // return JSON String
    return rssFeed;

}

From source file:es.alvsanand.webpage.web.beans.cms.SearchBean.java

public void setEncodedQuery(String encodedQuery) throws UnsupportedEncodingException {
    this.query = URLDecoder.decode(encodedQuery, Globals.CHARACTER_ENCODING);
}

From source file:org.apache.servicecomb.demo.springmvc.server.DownloadSchema.java

public DownloadSchema() throws IOException {
    FileUtils.deleteQuietly(tempDir);/*from w w w .  j  av a 2s .  com*/
    FileUtils.forceMkdir(tempDir);

    // for download from net stream case
    HttpServer server = ServerBootstrap.bootstrap().setListenerPort(9000)
            .registerHandler("/download/netInputStream", (req, resp, context) -> {
                String uri = req.getRequestLine().getUri();
                String query = URI.create(uri).getQuery();
                int idx = query.indexOf('=');
                String content = query.substring(idx + 1);
                content = URLDecoder.decode(content, StandardCharsets.UTF_8.name());
                resp.setEntity(new StringEntity(content, StandardCharsets.UTF_8.name()));
            }).create();
    server.start();
}

From source file:com.mmd.mssp.util.WebUtil.java

public static String getHttpQueryParam(HttpServletRequest request, String key, String charset)
        throws UnsupportedEncodingException {
    String queryString = request.getQueryString();
    if (!StringUtils.isAsciiPrintable(queryString)) {// ? ASCII ??
        byte[] bytes = queryString.getBytes("iso-8859-1");
        queryString = new String(bytes, charset);
    }//from w w  w.  ja v a 2s  . co  m
    String val = StringUtil.searchKeyValue(queryString, key);
    if (val != null) {
        val = URLDecoder.decode(val, charset);
    }
    request.setAttribute("QueryDecodeCharset", val);
    return val;
}