Java Code Examples for java.net.URLDecoder.decode()

The following are Jave code examples for showing how to use decode() of the java.net.URLDecoder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lucee-websocket   File: HandshakeHandler.java   View Source Code Vote up 6 votes
private static Map<String, String> parseRequestHeaderCookie(String requestHeaderCookie) {

		Map<String, String> result = new TreeMap();

		String name, value;
		String[] cookies = requestHeaderCookie.split(";"), cookieParts;

		for (String c : cookies) {

			cookieParts = c.split("=");

			if (cookieParts.length != 2)
				continue;

			try {

				name = cookieParts[0].trim();
				value = URLDecoder.decode(cookieParts[1].trim(), "UTF-8");
				result.put(name, value);
			}
			catch (UnsupportedEncodingException e) {
			} // UTF-8 is always supported
		}

		return result;
	}
 
Example 2
Project: BHBot   File: Misc.java   View Source Code Vote up 6 votes
/** 
 * https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file
 * @return path to the exe (without an exe). Example: "/E:/Eclipse/workspace/BHBot/bin/".
 */
public static String getExePath() {
	try {
		return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
	/*
	try {
		return (new File(Misc.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getAbsolutePath();
	} catch (URISyntaxException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return null;
	}
	*/
}
 
Example 3
Project: monarch   File: UriUtils.java   View Source Code Vote up 6 votes
/**
 * Decodes the encoded String value using the specified encoding (such as UTF-8). It is assumed
 * the String value was encoded with the URLEncoder using the specified encoding. This method
 * handles UnsupportedEncodingException by just returning the encodedValue. Since it is possible
 * for a String value to have been encoded multiple times, the String value is decoded until the
 * value stops changing (in other words, until the value is completely decoded).
 * <p/>
 * 
 * @param encodedValue the encoded String value to decode.
 * @param encoding a String value specifying the encoding.
 * @return the decoded value of the String. If the encoding is unsupported, then the encodedValue
 *         is returned.
 * @see java.net.URLDecoder
 */
public static String decode(String encodedValue, final String encoding) {
  try {
    if (encodedValue != null) {
      String previousEncodedValue;

      do {
        previousEncodedValue = encodedValue;
        encodedValue = URLDecoder.decode(encodedValue, encoding);
      } while (!encodedValue.equals(previousEncodedValue));
    }

    return encodedValue;
  } catch (UnsupportedEncodingException ignore) {
    return encodedValue;
  }
}
 
Example 4
Project: LJFramework   File: UrlUtil.java   View Source Code Vote up 6 votes
public static String getSortParamsString(String paramsString, boolean isDecode) {
    StringBuilder sortParamsString = new StringBuilder("");
    List<String> sortParamsNameList = getSortParamsName(paramsString);
    Map<String, String> paramsMap = convertParamsString2Map(paramsString);
    for (String paramName : sortParamsNameList) {
        if (StringUtils.isNotEmpty(paramName)) {
            if (StringUtils.isNotEmpty(sortParamsString.toString())) {
                sortParamsString.append('&');
            }
            sortParamsString.append(paramName).append('=').append(paramsMap.get(paramName));
        }
    }

    String result = null;
    if (!isDecode) {
        return sortParamsString.toString();
    }
    try {
        result = URLDecoder.decode(sortParamsString.toString(), ENCODING_UTF8);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    return result;
}
 
Example 5
Project: scmt-server   File: Utils.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
public static Map<String, Object> asMap(String urlencoded, String encoding) throws UnsupportedEncodingException
{

    Map<String, Object> map = new LinkedHashMap<>();

    for (String keyValue : urlencoded.trim().split("&"))
    {

        String[] tokens = keyValue.trim().split("=");
        String key = tokens[0];
        String value = tokens.length == 1 ? null : URLDecoder.decode(tokens[1], encoding);

        String[] keys = key.split("\\.");
        Map<String, Object> pointer = map;

        for (int i = 0; i < keys.length - 1; i++)
        {

            String currentKey = keys[i];
            Map<String, Object> nested = (Map<String, Object>) pointer.get(keys[i]);

            if (nested == null)
            {
                nested = new LinkedHashMap<>();
            }

            pointer.put(currentKey, nested);
            pointer = nested;
        }

        pointer.put(keys[keys.length - 1], value);
    }

    return map;
}
 
Example 6
Project: Android-App-Linking   File: Referrer.java   View Source Code Vote up 5 votes
@Nullable
private static String urlDecode(@NonNull String input) {
    try {
        return URLDecoder.decode(input, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 7
Project: sstore-soft   File: TestVoltCompiler.java   View Source Code Vote up 5 votes
public void testWithTPCCDDL() {
    String schemaPath = "";
    try {
        final URL url = TPCCClient.class.getResource("tpcc-ddl.sql");
        schemaPath = URLDecoder.decode(url.getPath(), "UTF-8");
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        System.exit(-1);
    }

    final String simpleProject =
        "<?xml version=\"1.0\"?>\n" +
        "<project>" +
        "<database name='database'>" +
        "<schemas><schema path='" + schemaPath + "' /></schemas>" +
        "<procedures><procedure class='org.voltdb.compiler.procedures.TPCCTestProc' /></procedures>" +
        "</database>" +
        "</project>";

    //System.out.println(simpleProject);

    final File projectFile = VoltProjectBuilder.writeStringToTempFile(simpleProject);
    final String projectPath = projectFile.getPath();

    final VoltCompiler compiler = new VoltCompiler();
    final ClusterConfig cluster_config = new ClusterConfig(1, 1, 0, "localhost");

    final boolean success = compiler.compile(projectPath, cluster_config,
                                             "testout.jar", System.out, null);

    assertTrue(success);

    final File jar = new File("testout.jar");
    jar.delete();
}
 
Example 8
Project: metanome-algorithms   File: AbaloneFixture.java   View Source Code Vote up 5 votes
public RelationalInputGenerator getInputGenerator()
    throws UnsupportedEncodingException, FileNotFoundException {
  String
      pathToInputFile =
      URLDecoder.decode(
          Thread.currentThread().getContextClassLoader().getResource(relationName).getPath(),
          "utf-8");
  RelationalInputGenerator
      inputGenerator =
      new DefaultFileInputGenerator(new File(pathToInputFile));
  return inputGenerator;
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: AbstractWebApplicationService.java   View Source Code Vote up 5 votes
@Override
public boolean matches(final Service service) {
    try {
        final String thisUrl = URLDecoder.decode(this.id, "UTF-8");
        final String serviceUrl = URLDecoder.decode(service.getId(), "UTF-8");

        logger.trace("Decoded urls and comparing [{}] with [{}]", thisUrl, serviceUrl);
        return thisUrl.equalsIgnoreCase(serviceUrl);
    } catch (final Exception e) {
        logger.error(e.getMessage(), e);
    }
    return false;
}
 
Example 10
Project: oscm   File: PSPResponse.java   View Source Code Vote up 5 votes
/**
 * Converts the input given in the request to a properties object.
 * 
 * @param request
 *            The received request.
 * @return The properties contained in the request.
 * @throws IOException
 *             Thrown in case the request information could not be
 *             evaluated.
 */
private boolean determinePSPParams(HttpServletRequest request, Properties p) {
    

    try {
        ServletInputStream inputStream = request.getInputStream();
        if (inputStream == null) {
            return false;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                inputStream, "UTF-8"));
        String line = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        String params = sb.toString();
        StringTokenizer st = new StringTokenizer(params, "&");
        while (st.hasMoreTokens()) {
            String nextToken = st.nextToken();
            String[] splitResult = nextToken.split("=");
            String key = splitResult[0];
            String value = "";
            if (splitResult.length > 1) {
                value = URLDecoder.decode(splitResult[1], "UTF-8");
            }
            p.setProperty(key, value);
        }
        return validateResponse(p);
    } catch (IOException e) {
        // if the request information cannot be read, we cannot determine
        // whether the registration worked or not. Hence we assume it
        // failed, log a warning and return the failure-URL to the PSP.
        logger.logWarn(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.WARN_HEIDELPAY_INPUT_PROCESS_FAILED);
    }
    
    return false;
}
 
Example 11
Project: openjdk-jdk10   File: MIMEMessage.java   View Source Code Vote up 5 votes
private MIMEPart getDecodedCidPart(String cid) {
    MIMEPart part = partsMap.get(cid);
    if (part == null) {
        if (cid.indexOf('%') != -1) {
            try {
                String tempCid = URLDecoder.decode(cid, "utf-8");
                part = partsMap.get(tempCid);
            } catch (UnsupportedEncodingException ue) {
                // Ignore it
            }
        }
    }
    return part;
}
 
Example 12
Project: java-debug   File: AdapterUtils.java   View Source Code Vote up 5 votes
/**
 * Decode the uri string.
 * @param uri
 *          the uri string
 * @return the decoded uri
 */
public static String decodeURIComponent(String uri) {
    try {
        return URLDecoder.decode(uri, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        return uri;
    }
}
 
Example 13
Project: unitimes   File: CalendarServlet.java   View Source Code Vote up 5 votes
QParams(String q) throws UnsupportedEncodingException {
	for (String p: QueryEncoderBackend.decode(q).split("&")) {
		String name = p.substring(0, p.indexOf('='));
		String value = URLDecoder.decode(p.substring(p.indexOf('=') + 1), "UTF-8");
		List<String> values = iParams.get(name);
		if (values == null) {
			values = new ArrayList<String>();
			iParams.put(name, values);
		}
		values.add(value);
	}
}
 
Example 14
Project: headb   File: HFileUtils.java   View Source Code Vote up 5 votes
/**
 * 获得类文件
 * @param clazz
 * @return File
 */
public static File getClassPath(Class<?> clazz) {
	String className=clazz.getSimpleName()+".class";
	String path =clazz.getResource(className).getPath();
	try {
		path=URLDecoder.decode(path,ENCODING);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	File file = new File(path);
	return file;
}
 
Example 15
Project: webtrekk-android-sdk   File: Core.java   View Source Code Vote up 5 votes
private static String urlDecode(String string) {
	if (string == null || string.length() == 0) {
		return string;
	}
	
	try {
		return URLDecoder.decode(string, "UTF-8");
	}
	catch (UnsupportedEncodingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Project: orbis-lps2ima-dev   File: MainController.java   View Source Code Vote up 5 votes
@Route(method = HttpMethod.POST, uri = "/login")
@Async
public Result login() throws IOException {
    String urlContent = URLDecoder.decode(context().reader().readLine(), "UTF-8");
    String[] split = urlContent.split("&");
    Session session = coreServerController.getSession(split[0].replaceAll(".*=", ""),
            split[1].replaceAll(".*=", ""));
    if(session != null) {
        return ok(session.getToken().toString());
    }
    else {
        return badRequest("Unrecognized credits.");
    }
}
 
Example 17
Project: M3U8_Video_demo   File: NanoHTTPD.java   View Source Code Vote up 5 votes
/**
 * Decode percent encoded <code>String</code> values.
 * 
 * @param str
 *            the percent encoded <code>String</code>
 * @return expanded form of the input, for example "foo%20bar" becomes
 *         "foo bar"
 */
protected static String decodePercent(String str) {
    String decoded = null;
    try {
        decoded = URLDecoder.decode(str, "UTF8");
    } catch (UnsupportedEncodingException ignored) {
        NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored);
    }
    return decoded;
}
 
Example 18
Project: forweaver2.0   File: RepositoryIntercepter.java   View Source Code Vote up 4 votes
public boolean preHandle(HttpServletRequest request, 
		HttpServletResponse response, Object handler)
				throws Exception {
	String uri = request.getRequestURI();
	
	String repositoryName = new String();
	if (uri.split("/").length>3){
		repositoryName= uri.split("/")[2]+"/"+uri.split("/")[3];
	}else
		return true;
	if(uri.endsWith("/join-cancel") || uri.endsWith("/join-ok") ||uri.endsWith("/join") || repositoryName.startsWith("sort:") || repositoryName.startsWith("tags:"))
		return true;
	Weaver weaver = weaverService.getCurrentWeaver();
	Repository repository = repositoryService.get(repositoryName);
	
	if(uri.contains("/tags:")){
		String tags = uri.substring(uri.indexOf("/tags:")+6);
		if(tags.contains("/"))
			tags = tags.substring(0, tags.indexOf("/"));
		tags = URLDecoder.decode(tags, "UTF-8");
		List<String> tagList = tagService.stringToTagList(tags);
		if(!tagService.validateTag(tagList, weaver)){
			response.sendError(400);
			return false;
		}
	}
	if(repository == null){
		response.sendError(404);
		return false;
	}
	
	if(repository.getAuthLevel() > 0){
		if(weaver == null){
			response.sendError(400);
			return false;
		}
		if(weaver.getPass(repositoryName) != null)
			return true;			
	}

	return true;
}
 
Example 19
Project: sbc-qsystem   File: CmdParams.java   View Source Code Vote up 4 votes
public final void initFromString(String params) {
    if (params == null || params.isEmpty()) {
        return;
    }
    for (String str : params.split("&")) {
        final String[] pp = str.split("=");

        final Field[] fs = getClass().getDeclaredFields();
        try {
            for (Field field : fs) {
                if (Modifier.isStatic(field.getModifiers()) && Modifier
                        .isFinal(field.getModifiers())) {
                    continue;
                }

                if (pp[0].equals(field.getName())) {
                    field.setAccessible(true);

                    if ("properties".equals(field.getName())) {
                        final List<QProperty> list = new LinkedList<>();
                        String lst = URLDecoder.decode(pp[1], "utf-8");
                        lst = lst.substring(1, lst.length() - 1);
                        final String[] ll = lst.split("\\}\\{");
                        for (String el : ll) {
                            final String[] ss = el.split("\\[|\\]|:");
                            if (ss.length == 4) {
                                list.add(new QProperty(ss[1], ss[2], ss[3]));
                            }
                        }
                        field.set(this, list);
                        continue;
                    }

                    switch (field.getType().getSimpleName().toLowerCase(Locale.US)) {
                        case "int":
                            field.set(this, Integer.parseInt(pp[1]));
                            break;
                        case "integer":
                            field.set(this, Integer.parseInt(pp[1]));
                            break;
                        case "string":
                            field.set(this, URLDecoder.decode(pp[1], "utf-8"));
                            break;
                        case "boolean":
                            field.set(this, Boolean.parseBoolean(pp[1]));
                            break;
                        case "long":
                            field.set(this, Long.parseLong(pp[1]));
                            break;
                        default:
                            throw new AssertionError();
                    }
                }

            }
        }
        catch (IllegalArgumentException | IllegalAccessException
                | UnsupportedEncodingException ex) {
            System.err.println(ex);
        }

    }
}
 
Example 20
Project: TIIEHenry-Android-SDK   File: EncodeUtils.java   View Source Code Vote up 3 votes
/**
 * URL解码
 * <p>若系统不支持指定的解码字符集,则直接将input原样返回</p>
 *
 * @param input   要解码的字符串
 * @param charset 字符集
 * @return URL解码为指定字符集的字符串
 */
public static String urlDecode(String input, String charset) {
    try {
        return URLDecoder.decode(input, charset);
    } catch (UnsupportedEncodingException e) {
        return input;
    }
}