下面列出了java.net.URLDecoder# decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<? extends INameValue> getOverViewList(HarEntry harEntry) {
ArrayList<HarNameValuePair> pairs = new ArrayList<>();
HarRequest harRequest = harEntry.getRequest();
HarResponse harResponse = harEntry.getResponse();
if (harRequest != null) {
String url = harRequest.getUrl();
try {
url = URLDecoder.decode(url, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
pairs.add(new HarNameValuePair("URL", url));
pairs.add(new HarNameValuePair("Method", harRequest.getMethod()));
}
if (harResponse != null) {
pairs.add(new HarNameValuePair("Code", harResponse.getStatus() + ""));
pairs.add(new HarNameValuePair("Size", harResponse.getBodySize() + "Bytes"));
}
pairs.add(new HarNameValuePair("TotalTime", harEntry.getTime() + "ms"));
return pairs;
}
@ApiOperation(
value = "Get applications",
notes = "Gets the list of applications using the file",
response = Application.class,
responseContainer = "List"
)
@GET
@Path("/apps/{url}")
@Produces(MediaType.APPLICATION_JSON)
public Response getApplicationsForFile(@PathParam("url") @ApiParam("An URL referencing the file") String url) {
try {
String decodedUrl = URLDecoder.decode(url, "UTF-8");
return Response.OK(this.applicationDAO.getAllApplicationsByUrl(decodedUrl));
} catch (Exception e) {
logger.error("Unexpected error when getting the list of applications by URL", e);
return Response.INTERNAL_ERROR();
}
}
/**
* Returns the time-stamp for a document's last update
*/
private final long getLastModified(String uri) {
try {
URL url = new URL(uri);
URLConnection connection = url.openConnection();
long timestamp = connection.getLastModified();
// Check for a "file:" URI (courtesy of Brian Ewins)
if (timestamp == 0){ // get 0 for local URI
if ("file".equals(url.getProtocol())){
File localfile = new File(URLDecoder.decode(url.getFile()));
timestamp = localfile.lastModified();
}
}
return(timestamp);
}
// Brutal handling of all exceptions
catch (Exception e) {
return(System.currentTimeMillis());
}
}
private String findFileName(String contentDisposition) {
if (contentDisposition != null)
try {
Matcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
if (matcher.find()) {
String match = matcher.group(1);
if (match != null && !match.equals("")) {
match = URLDecoder.decode(match, "UTF-8");
return match;
}
}
} catch (IllegalStateException ex) {
// cannot find filename using content disposition http header.
// Use url to find filename;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return FilenameUtils.getName(downloadFileInfo.getUploadUrl().getPath());
}
@Test
public void testBatchJobIdEnDecryption() throws Exception {
String jobId = "100";
SecretKeySpec secretKey = BulkDataConfigUtil.getBatchJobIdEncryptionKey("test-key");
assertNotNull(secretKey);
String encryptedJobId = BulkDataExportUtil.encryptBatchJobId(jobId, secretKey);
assertNotNull(encryptedJobId);
assertFalse(encryptedJobId.equals(jobId));
encryptedJobId = URLDecoder.decode(encryptedJobId, StandardCharsets.UTF_8.toString());
assertNotNull(encryptedJobId);
String decryptedJobId = BulkDataExportUtil.decryptBatchJobId(encryptedJobId, secretKey);
assertNotNull(decryptedJobId);
assertEquals(decryptedJobId, jobId);
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
} catch (Exception e) {
RecordLog.info("Decode gateway API definition data error", e);
return CommandResponse.ofFailure(e, "decode gateway API definition data error");
}
RecordLog.info("[API Server] Receiving data change (type: gateway API definition): {0}", data);
String result = SUCCESS_MSG;
Set<ApiDefinition> apiDefinitions = parseJson(data);
GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions);
return CommandResponse.ofSuccess(result);
}
@SneakyThrows
public static String getExtension(String url) {
url = URLDecoder.decode(url, "utf8");
if (url.contains("?")) {
url = url.substring(0,url.lastIndexOf("?"));
}
if (url.contains("#")) {
url = url.substring(0,url.lastIndexOf("#"));
}
return FilenameUtils.getExtension(url);
}
/**
* 获取前端传递过来的json字符串<br>
* 如果前端使用axios的data方式传参则使用改方法接收参数
*
* @return
*/
public String getjsonReq() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(HttpUtil.getRequest().getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
if (sb.length() < 1) {
return "";
}
String reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
reqBody = reqBody.substring(reqBody.indexOf("{"));
return reqBody;
} catch (IOException e) {
logger.error("获取json参数错误!{}", e.getMessage());
return "";
}
}
public static String decode(String value) {
if (value == null || value.length() == 0) {
return "";
}
try {
return URLDecoder.decode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public Number convert(Conversion conversion, ConversionProvider provider) throws Exception {
if (!supports(conversion) || !conversion.name.equals(conversion.expression)) return (Number) conversion.value;
else if (conversion.type == BigInteger.class) return new BigInteger(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset));
else if (conversion.type == BigDecimal.class) return new BigDecimal(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset));
else if (conversion.type == AtomicInteger.class) return new AtomicInteger(Integer.valueOf(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset)));
else if (conversion.type == AtomicLong.class) return new AtomicLong(Long.valueOf(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset)));
else if (conversion.type == Number.class) return new BigDecimal(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset));
else return (Number) conversion.value;
}
@Override
public CharSequence convert(Conversion conversion, ConversionProvider provider) throws Exception {
if (!supports(conversion) || !conversion.name.equals(conversion.expression)) return (CharSequence) conversion.value;
else if (conversion.type == String.class) return conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset);
else if (conversion.type == StringBuilder.class) return new StringBuilder(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset));
else if (conversion.type == StringBuffer.class) return new StringBuffer(conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset));
else if (conversion.type == CharSequence.class) return conversion.decoded ? conversion.values[0] : URLDecoder.decode(conversion.values[0], conversion.charset);
else return (CharSequence) conversion.value;
}
private static String getAgentJarFileName(URL agentJarUrl) {
if (agentJarUrl == null) {
return null;
}
try {
return URLDecoder.decode(agentJarUrl.getFile().replace("+", "%2B"), "UTF-8");
} catch (IOException e) {}
return null;
}
private static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
Map<String, String> result = new LinkedHashMap<>();
String[] pairs = query.split(ZookeeperConstants.AND);
for (String pair : pairs) {
int idx = pair.indexOf(ZookeeperConstants.EQUAL);
String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
result.put(key, value);
}
return result;
}
private void setDefaultExtension(ComTrackableLink link, ApplicationContext con) throws UnsupportedEncodingException {
ConfigService configService = (ConfigService) con.getBean("ConfigService");
String defaultExtensionString = configService.getValue(ConfigValue.DefaultLinkExtension, link.getCompanyID());
if (StringUtils.isNotBlank(defaultExtensionString)) {
if (defaultExtensionString.startsWith("?")) {
defaultExtensionString = defaultExtensionString.substring(1);
}
String[] extensionProperties = defaultExtensionString.split("&");
for (String extensionProperty : extensionProperties) {
final int eqIndex = extensionProperty.indexOf('=');
final String[] extensionPropertyData = (eqIndex == -1) ? new String[] { extensionProperty, "" } : new String[] { extensionProperty.substring(0, eqIndex), extensionProperty.substring(eqIndex + 1) };
String extensionPropertyName = URLDecoder.decode(extensionPropertyData[0], "UTF-8");
String extensionPropertyValue = "";
if (extensionPropertyData.length > 1) {
extensionPropertyValue = URLDecoder.decode(extensionPropertyData[1], "UTF-8");
}
// Change link properties
List<LinkProperty> properties = link.getProperties();
boolean changedProperty = false;
for (LinkProperty property : properties) {
if (property.getPropertyType() == PropertyType.LinkExtension && property.getPropertyName().equals(extensionPropertyName)) {
property.setPropertyValue(extensionPropertyValue);
changedProperty = true;
}
}
if (!changedProperty) {
LinkProperty newProperty = new LinkProperty(PropertyType.LinkExtension, extensionPropertyName, extensionPropertyValue);
properties.add(newProperty);
}
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
// Here, you should validate the user account.
// In this sample, we do not do that.
String redirectURL = URLDecoder.decode(req.getParameter("responseurl"), "UTF-8");
res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
res.setHeader("Location", redirectURL);
res.getWriter().flush();
}
public static String getFileFromURL(String url) {
int last = url.lastIndexOf('/');
if (last < 0 || last == url.length() - 1)
return "file";
try {
return URLDecoder.decode(url.substring(last + 1), "UTF-8");
} catch (Exception e) {
return "file";
}
}
/**
* scan the package.
*
* @param basePackage the basic class package's string.
* @param recursive whether to search recursive.
* @return Set of the found classes.
*/
public Set<Class<?>> getPackageAllClasses(String basePackage, boolean recursive) {
if (basePackage == null) {
return new HashSet<>();
}
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
String packageName = basePackage;
if (packageName.endsWith(".")) {
packageName = packageName.substring(0, packageName.lastIndexOf('.'));
}
String package2Path = packageName.replace('.', '/');
try {
Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(package2Path);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
doScanPackageClassesByFile(classes, packageName, filePath, recursive);
} else if ("jar".equals(protocol)) {
doScanPackageClassesByJar(packageName, url, recursive, classes);
}
}
} catch (IOException e) {
LOGGER.error("ignore this IOException", e);
}
TreeSet<Class<?>> sortedClasses = new TreeSet<>(new ClassNameComparator());
sortedClasses.addAll(classes);
return sortedClasses;
}
protected ActionForward proceedWithList(ActionMapping mapping, ComTrackableLinkForm aForm, HttpServletRequest req, ComAdmin admin) throws Exception {
loadLinks(aForm, req);
loadMailing(aForm, req, admin);
setBulkID(aForm);
setAdminLinks(aForm, req);
setLinkItems(aForm);
aForm.setCompanyHasDefaultLinkExtension(StringUtils.isNotBlank(configService.getValue(ConfigValue.DefaultLinkExtension, admin.getCompanyID())));
Map<String, String> defaultExtensions = new HashMap<>();
String defaultExtensionString = configService.getValue(ConfigValue.DefaultLinkExtension, admin.getCompanyID());
if (StringUtils.isNotBlank(defaultExtensionString)) {
if (defaultExtensionString.startsWith("?")) {
defaultExtensionString = defaultExtensionString.substring(1);
}
String[] extensionProperties = defaultExtensionString.split("&");
for (String extensionProperty : extensionProperties) {
String[] extensionPropertyData = extensionProperty.split("=");
String extensionPropertyName = URLDecoder.decode(extensionPropertyData[0], "UTF-8");
String extensionPropertyValue = "";
if (extensionPropertyData.length > 1) {
extensionPropertyValue = URLDecoder.decode(extensionPropertyData[1], "UTF-8");
}
defaultExtensions.put(extensionPropertyName, extensionPropertyValue);
}
}
ObjectMapper mapper = new ObjectMapper();
String JSON = mapper.writeValueAsString(defaultExtensions);
req.setAttribute("defaultExtensions", JSON);
return mapping.findForward("list");
}
/**
* 将URL编码转化为字符串
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String strToDecoder(String str) {
try {
return URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return str;
}
}
/**
*
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String xml = URLDecoder.decode(request.getParameter("xml"), "UTF-8");
Document current = mxXmlUtils.parseXml(xml);
String tcn = current.getDocumentElement().getAttribute("tcn");
String id = current.getDocumentElement().getAttribute("id");
//System.out.println("POST: id=" + id + " tcn=" + tcn);
if (id == null || id.length() == 0)
{
// Creates an ID and initializes the transaction counter (TCN)
id = String.valueOf(counter++);
tcn = "0";
}
else
{
// Saves an existing diagram for the given ID in the store. Note
// that in production there would be a chec if the current user
// has access to this diagram.
Document stored = diagrams.get(id);
String storedTcn = stored.getDocumentElement().getAttribute("tcn");
// Handles conflicts "first come first serve" style. In production
// you have to make sure to properly deal with critical sections here.
if (Integer.parseInt(storedTcn) > Integer.parseInt(tcn))
{
response.setStatus(HttpServletResponse.SC_CONFLICT);
response.getWriter().println(
"Diagram was changed by another user.");
return;
}
else
{
// Increments the TCN by one
tcn = String.valueOf(Integer.parseInt(tcn) + 1);
}
}
// Updates the TCN and ID in the diagram and puts it into the store
current.getDocumentElement().setAttribute("tcn", tcn);
current.getDocumentElement().setAttribute("id", id);
diagrams.put(id, current);
// Sends the possibly new ID and the incremented TCN to the client
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(
"<result id=\"" + id + "\" tcn=\"" + tcn + "\"/>");
}