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

The following examples show how to use java.net.URLDecoder#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UpdateGatewayApiDefinitionGroupCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: ContentTabHolder.java    From CapturePacket with MIT License 6 votes vote down vote up
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;
}
 
Example 3
Source File: FilesResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 4
Source File: DocumentCache.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 5
Source File: DriveUploaderBuilder.java    From Bhadoo-Cloud-Drive with MIT License 6 votes vote down vote up
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());
	}
 
Example 6
Source File: BaseController.java    From web-flash with MIT License 5 votes vote down vote up
/**
 * 获取前端传递过来的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 "";

    }

}
 
Example 7
Source File: StrUtil.java    From smartacus-mqtt-broker with Apache License 2.0 5 votes vote down vote up
/**
 * 将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;
    }
}
 
Example 8
Source File: ComTrackableLinkAction.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
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");
}
 
Example 9
Source File: ClassPathScanHandler.java    From enode with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: AbstractFileBridge.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
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";
    }
}
 
Example 11
Source File: LoginServlet.java    From smart-home-java with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: ComMailingImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
			}
		}
	}
}
 
Example 13
Source File: ZookeeperRegistryUtils.java    From sofa-dashboard-client with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: PluginJarUtil.java    From chaosblade-exec-jvm with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: BulkDataExportUtilTest.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 16
Source File: StringConverter.java    From halo-docs with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source File: NumberConverter.java    From halo-docs with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 18
Source File: URL.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 19
Source File: FileUtils.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 20
Source File: Roundtrip.java    From blog-codes with Apache License 2.0 4 votes vote down vote up
/**
 * 
 */
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 + "\"/>");
}