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:net.cloudkit.enterprises.infrastructure.utilities.EncodeHelper.java

/**
 * URL ?, EncodeUTF-8.//from  w w  w  .  j  a v a  2 s  . c om
 */
public static String urlDecode(String part) {

    try {
        return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw ExceptionHelper.unchecked(e);
    }
}

From source file:controllers.modules.cas.SecureCAS.java

public static void handleLogout(String body) throws Throwable {
    int i = StringUtils.indexOf(body, LOGOUT_REQ_PARAMETER);
    String postBody = URLDecoder.decode(body, "UTF-8");
    if (i == 0) {
        String logoutRequestMessage = StringUtils.substring(postBody, LOGOUT_REQ_PARAMETER.length() + 1);
        if (StringUtils.isNotEmpty(logoutRequestMessage)) {

            Document document = XML.getDocument(logoutRequestMessage);
            if (document != null) {
                NodeList nodeList = document.getElementsByTagName("samlp:SessionIndex");
                if (nodeList != null && nodeList.getLength() > 0) {
                    Node node = nodeList.item(0);
                    String ticket = node.getTextContent();
                    String stKey = ST + "_" + ticket;
                    String username = Cache.get(stKey, String.class);
                    if (username != null) {
                        Cache.delete(stKey);
                        Cache.set(LOGOUT_TAG + "_" + username, 1, TEN_YEARS_EXPIRATION);
                        Logger.debug("Mark that %s has been logout ", username);
                        return;
                    }/*from   ww w .  ja  v a2 s.c om*/
                }
            }
        }
    }
    Logger.warn("illegal logout message: %s", postBody);
}

From source file:com.googlecode.flyway.core.util.ClassUtils.java

/**
 * Retrieves the physical location on disk of this class.
 *
 * @param aClass The class to get the location for.
 * @return The absolute path of the .class file.
 *//*from w ww.ja  v a 2  s  .c om*/
public static String getLocationOnDisk(Class<?> aClass) {
    try {
        String url = aClass.getProtectionDomain().getCodeSource().getLocation().getPath();
        return URLDecoder.decode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        //Can never happen.
        return null;
    }
}

From source file:be.solidx.hot.utils.AbstractHttpDataDeserializer.java

@Override
public Object processRequestData(byte[] data, String contentType) {
    MediaType ct = MediaType.parseMediaType(contentType);

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Content-type: " + contentType);

    Charset charset = ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet();

    // Subtypes arre used because of possible encoding definitions
    if (ct.getSubtype().equals(MediaType.APPLICATION_OCTET_STREAM.getSubtype())) {
        return data;
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_JSON.getSubtype())) {
        try {//ww  w .ja va 2s  . c om
            return fromJSON(data);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_XML.getSubtype())) {
        try {
            return toXML(data, ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    } else if (ct.getSubtype().equals(MediaType.APPLICATION_FORM_URLENCODED.getSubtype())) {
        String decoded;
        try {
            decoded = URLDecoder.decode(new String(data, charset), charset.toString());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
        return fromFormUrlEncoded(decoded);
    } else {
        return new String(data, ct.getCharSet() == null ? Charset.forName("UTF-8") : ct.getCharSet());
    }
}

From source file:org.motechproject.server.ruleengine.FilesystemRuleLoader.java

/**
 * Load rule files from the internal and external rule folders
 * @throws Exception/* ww w  .j  a v  a2  s  .  co m*/
 */
public void load() throws Exception {
    List<File> ruleFiles = new ArrayList<File>();
    if (internalRuleFolder != null) {
        File[] internalRuleFiles = new File(
                URLDecoder.decode(getClass().getResource(internalRuleFolder).getFile(), "UTF-8")).listFiles();
        ruleFiles.addAll(Arrays.asList(internalRuleFiles));
    }

    if (externalRuleFolder != null) {
        File folder = new File(externalRuleFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        } else {
            File[] externalRuleFiles = folder.listFiles();
            ruleFiles.addAll(Arrays.asList(externalRuleFiles));
        }
    }

    Map<String, ClassLoader> bundleClassLoaderLookup = osgiFrameworkService.getBundleClassLoaderLookup();
    List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
    classLoaders.add(Thread.currentThread().getContextClassLoader());
    classLoaders.addAll(bundleClassLoaderLookup.values());

    for (File file : ruleFiles) {
        if (file.getName().toLowerCase().endsWith(".drl")) {
            try {
                knowledgeBaseManager.addOrUpdateRule(file,
                        classLoaders.toArray(new ClassLoader[classLoaders.size()]));
            } catch (IOException e) {
                logger.error("Failed to load the rule file [" + file.getName() + "]", e);
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:com.jpeterson.littles3.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets.//from  w  ww .  j  a  va 2  s.c o  m
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:controllers.DiscourseAuth.java

protected static String urlDecode(String input) throws UnsupportedEncodingException {
    return URLDecoder.decode(input, StandardCharsets.UTF_8.name());
}

From source file:eu.planets_project.tb.gui.backing.DownloadManager.java

/**
 * //from ww w .ja v a  2  s  . c o  m
 * @return
 * @throws IOException
 */
public String downloadExportedExperiment(String expExportID, String downloadName) {
    FacesContext ctx = FacesContext.getCurrentInstance();

    // Decode the file name (might contain spaces and on) and prepare file object.
    try {
        expExportID = URLDecoder.decode(expExportID, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    File file = expCache.getExportedFile(expExportID);

    HttpServletResponse response = (HttpServletResponse) ctx.getExternalContext().getResponse();

    // Check if file exists and can be read:
    if (!file.exists() || !file.isFile() || !file.canRead()) {
        return "fileNotFound";
    }

    // Get content type by filename.
    String contentType = new MimetypesFileTypeMap().getContentType(file);

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open the file:
        input = new BufferedInputStream(new FileInputStream(file));
        int contentLength = input.available();

        // Initialise the servlet response:
        response.reset();
        response.setContentType(contentType);
        response.setContentLength(contentLength);
        response.setHeader("Content-disposition", "attachment; filename=\"" + downloadName + ".xml\"");
        output = new BufferedOutputStream(response.getOutputStream());

        // Write file out:
        for (int data; (data = input.read()) != -1;) {
            output.write(data);
        }

        // Flush the stream:
        output.flush();

        // Tell Faces that we're finished:
        ctx.responseComplete();

    } catch (IOException e) {
        // Something went wrong?
        e.printStackTrace();

    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
    return "success";
}

From source file:models.service.UserInfoCookieService.java

private static String cookieValueToDecodedString(String cookieName) {
    Cookie cookie = Context.current().request().cookie(cookieName);
    if (null == cookie) {
        return null;
    }/*from   w  w w  .  j av a2s. c  o m*/
    String cookieValue = cookie.value();
    if (StringUtils.isNotBlank(cookieValue)) {
        try {
            cookieValue = URLDecoder.decode(cookieValue, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("URL?", e);
        }
    }
    return cookieValue;
}

From source file:net.chris54721.infinitycubed.utils.Utils.java

public static void restart() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*ww w  .  j  a v a2s.  c  om*/
        public void run() {
            try {
                File executable = new File(URLDecoder.decode(
                        (Launcher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()),
                        "UTF-8"));
                List<String> command = new ArrayList<String>();
                command.add(getJavaPath());
                command.add("-jar");
                command.add(executable.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.start();
            } catch (Exception e) {
                LogHelper.error("Failed restarting launcher, shutting down", e);
                System.exit(-1);
            }
        }
    });
    System.exit(0);
}