java.net.URLDecoder Java Examples

The following examples show how to use java.net.URLDecoder. 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: ExporterSideConfigUrlTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
protected <T> void verifyExporterUrlGeneration(T config, Object[][] dataTable) {

        // 1. fill corresponding config with data
        ////////////////////////////////////////////////////////////
        fillConfigs(config, dataTable, TESTVALUE1);

        // 2. export service and get url parameter string from db
        ////////////////////////////////////////////////////////////
        servConf.export();
        String paramStringFromDb = getProviderParamString();
        try {
            paramStringFromDb = URLDecoder.decode(paramStringFromDb, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // impossible
        }


        assertUrlStringWithLocalTable(paramStringFromDb, dataTable, config.getClass().getName(), TESTVALUE1);


        // 4. unexport service
        ////////////////////////////////////////////////////////////
        servConf.unexport();
    }
 
Example #2
Source File: TraceFilter.java    From log-trace-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = ((HttpServletRequest) servletRequest);

    Map<String, String> formatMap = new HashMap<>(16);

    // 获取自定义参数
    Set<String> expandFormat = traceLogProperties.getFormat();
    for (String k : expandFormat) {
        String v = request.getHeader(k);
        if (!StringUtils.isEmpty(v)) {
            formatMap.put(k, URLDecoder.decode(v, "UTF-8"));
        }
    }

    // 写入 MDC
    TraceContentFactory.storageMDC(formatMap);

    filterChain.doFilter(servletRequest, servletResponse);
    MDC.clear();
}
 
Example #3
Source File: ImageSource.java    From pdfview-android with Apache License 2.0 6 votes vote down vote up
private ImageSource(@NonNull Uri uri) {
    // #114 If file doesn't exist, attempt to url decode the URI and try again
    String uriString = uri.toString();
    if (uriString.startsWith(FILE_SCHEME)) {
        File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1));
        if (!uriFile.exists()) {
            try {
                uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // Fallback to encoded URI. This exception is not expected.
            }
        }
    }
    this.bitmap = null;
    this.uri = uri;
    this.resource = null;
    this.tile = true;
}
 
Example #4
Source File: ModifyServerNamespaceSetHandler.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("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
        RecordLog.info("[ModifyServerNamespaceSetHandler] Receiving cluster server namespace set: " + data);
        Set<String> set = JSON.parseObject(data, new TypeReference<Set<String>>() {});
        ClusterServerConfigManager.loadServerNamespaceSet(set);
        return CommandResponse.ofSuccess("success");
    } catch (Exception e) {
        RecordLog.warn("[ModifyServerNamespaceSetHandler] Decode cluster server namespace set error", e);
        return CommandResponse.ofFailure(e, "decode client cluster config error");
    }
}
 
Example #5
Source File: HttpEventTask.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private void parseParams(String queryString, CommandRequest request) {
    for (String parameter : queryString.split("&")) {
        if (StringUtil.isBlank(parameter)) {
            continue;
        }

        String[] keyValue = parameter.split("=");
        if (keyValue.length != 2) {
            continue;
        }

        String value = StringUtil.trim(keyValue[1]);
        try {
            value = URLDecoder.decode(value, SentinelConfig.charset());
        } catch (UnsupportedEncodingException e) {
        }

        request.addParam(StringUtil.trim(keyValue[0]), value);
    }
}
 
Example #6
Source File: QueryGenerator.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
 * 高级查询
 * @param queryWrapper
 * @param parameterMap
 */
public static void doSuperQuery(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) {
	if(parameterMap!=null&& parameterMap.containsKey(SUPER_QUERY_PARAMS)){
		String superQueryParams = parameterMap.get(SUPER_QUERY_PARAMS)[0];
		// 解码
		try {
			superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("--高级查询参数转码失败!", e);
		}
		List<QueryCondition> conditions = JSON.parseArray(superQueryParams, QueryCondition.class);
		log.info("---高级查询参数-->"+conditions.toString());
		
		for (QueryCondition rule : conditions) {
			if(oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal())){
				addEasyQuery(queryWrapper, rule.getField(), QueryRuleEnum.getByValue(rule.getRule()), rule.getVal());
			}
		}
	}
}
 
Example #7
Source File: LinkServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static List<LinkProperty> getLinkExtensions(String urlEncodedExtensionString) {
	List<LinkProperty> resultList = new ArrayList<>();
	if (StringUtils.isNotBlank(urlEncodedExtensionString)) {
		if (urlEncodedExtensionString.startsWith("?")) {
			urlEncodedExtensionString = urlEncodedExtensionString.substring(1);
		}
		for (String keyValueParamString : urlEncodedExtensionString.split("&")) {
			String[] parts = keyValueParamString.split("=");
			if (StringUtils.isNotBlank(parts[0])) {
				try {
					if (parts.length > 1 && StringUtils.isNotBlank(parts[1])) {
						resultList.add(new LinkProperty(PropertyType.LinkExtension, URLDecoder.decode(parts[0], "UTF-8"), URLDecoder.decode(parts[1], "UTF-8")));
					} else {
						resultList.add(new LinkProperty(PropertyType.LinkExtension, URLDecoder.decode(parts[0], "UTF-8"), ""));
					}
				} catch (UnsupportedEncodingException e) {
					logger.error("Error occured: " + e.getMessage(), e);
				}
			}
		}
	}
	return resultList;
}
 
Example #8
Source File: JoaDemoController.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
    * 导出excel
 *
 * @param request
 * @param response
 */
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
    // Step.1 组装查询条件
    QueryWrapper<JoaDemo> queryWrapper = null;
    try {
        String paramsStr = request.getParameter("paramsStr");
        if (oConvertUtils.isNotEmpty(paramsStr)) {
            String deString = URLDecoder.decode(paramsStr, "UTF-8");
            JoaDemo joaDemo = JSON.parseObject(deString, JoaDemo.class);
            queryWrapper = QueryGenerator.initQueryWrapper(joaDemo, request.getParameterMap());
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    //Step.2 AutoPoi 导出Excel
    ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
    List<JoaDemo> pageList = joaDemoService.list(queryWrapper);
    //导出文件名称
    mv.addObject(NormalExcelConstants.FILE_NAME, "流程测试列表");
    mv.addObject(NormalExcelConstants.CLASS, JoaDemo.class);
    mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("流程测试列表数据", "导出人:Jeecg", "导出信息"));
    mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
    return mv;
}
 
Example #9
Source File: RequestJsonToPoHandlerMethodArgumentResolver.java    From jframework with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {
    RequestJsonToPo parameterAnnotation = parameter.getParameterAnnotation(RequestJsonToPo.class);
    Objects.requireNonNull(parameterAnnotation);
    String value = parameterAnnotation.value();
    Class<?> clazz = parameter.getNestedParameterType();
    String jsonParameter = nativeWebRequest.getParameter(value);
    if (jsonParameter == null) {
        if (clazz.isAssignableFrom(List.class)) {
            return Lists.newArrayList();
        }
        return clazz.newInstance();
    }
    jsonParameter = URLDecoder.decode(jsonParameter, StandardCharsets.UTF_8.name());

    if (clazz.isAssignableFrom(List.class) || clazz.isAssignableFrom(ArrayList.class)) {
        String typeName = ((sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl) parameter.getGenericParameterType()).getActualTypeArguments()[0].getTypeName();
        Class<?> aClass = Class.forName(typeName);
        return JsonUtil.toList(jsonParameter, aClass);
    } else {
        return JsonUtil.toObject(jsonParameter, clazz);
    }
}
 
Example #10
Source File: CookieUtils.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * 获得指定Cookie的值
 * @param request 请求对象
 * @param response 响应对象
 * @param name 名字
 * @param isRemove 是否移除
 * @return 值
 */
public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, String path, boolean isRemove) {
	String value = null;
	if (StringUtils.isNotBlank(name)){
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					try {
						value = URLDecoder.decode(cookie.getValue(), "utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					if (isRemove && response != null) {
						cookie.setPath(path);
						cookie.setMaxAge(0);
						response.addCookie(cookie);
					}
				}
			}
		}
	}
	return value;
}
 
Example #11
Source File: ConsumerNodeChangeListener.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcConsumer convert2Consumer(String serviceName, String providerData) {

        try {
            providerData = URLDecoder.decode(providerData, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        RpcConsumer rpcConsumer = new RpcConsumer();
        ProviderInfo consumerInfo = ProviderHelper.toProviderInfo(providerData);
        String appName = consumerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
        rpcConsumer.setAppName(appName);
        rpcConsumer.setServiceName(serviceName);
        rpcConsumer.setAddress(consumerInfo.getHost());
        rpcConsumer.setPort(consumerInfo.getPort());
        return rpcConsumer;
    }
 
Example #12
Source File: CookieUtils.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
/**
 * 得到Cookie的值,
 *
 * @param request
 * @param cookieName
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
        return null;
    }
    String retValue = null;
    try {
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                if (isDecoder) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                } else {
                    retValue = cookieList[i].getValue();
                }
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return retValue;
}
 
Example #13
Source File: ModifyClusterClientConfigHandler.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("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
        RecordLog.info("[ModifyClusterClientConfigHandler] Receiving cluster client config: " + data);
        ClusterClientStateEntity entity = JSON.parseObject(data, ClusterClientStateEntity.class);

        ClusterClientConfigManager.applyNewConfig(entity.toClientConfig());
        ClusterClientConfigManager.applyNewAssignConfig(entity.toAssignConfig());

        return CommandResponse.ofSuccess(CommandConstants.MSG_SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterClientConfigHandler] Decode client cluster config error", e);
        return CommandResponse.ofFailure(e, "decode client cluster config error");
    }
}
 
Example #14
Source File: PackageScanner.java    From api with Apache License 2.0 6 votes vote down vote up
public static Set<Class<?>> scan(String packageName, boolean recursive) {
    String packageDirName = packageName.replace('.', '/');
    try {
        Set<Class<?>> classSet = new LinkedHashSet<>();
        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            String protocol = url.getProtocol();
            // If it's file, storage on the server
            if ("file".equals(protocol)) {
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");

                classSet.addAll(findClassesInPackageByFile(packageName, filePath, recursive));
            } else if ("jar".equals(protocol)) {
                classSet.addAll(findClassesInPackageByJar(packageName, url, recursive));
            }
        }
        return classSet;
    } catch (IOException e) {
        logger.error("error happen while scanning package", e);
    }

    return Collections.emptySet();
}
 
Example #15
Source File: ResourceWebHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Check whether the given path contains invalid escape sequences.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 */
private boolean isInvalidEncodedPath(String path) {
	if (path.contains("%")) {
		try {
			// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
			String decodedPath = URLDecoder.decode(path, "UTF-8");
			if (isInvalidPath(decodedPath)) {
				return true;
			}
			decodedPath = processPath(decodedPath);
			if (isInvalidPath(decodedPath)) {
				return true;
			}
		}
		catch (IllegalArgumentException | UnsupportedEncodingException ex) {
			// Should never happen...
		}
	}
	return false;
}
 
Example #16
Source File: ProviderNodeChangeListener.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcProvider convert2Provider(String serviceName, String providerData) {

        try {
            providerData = URLDecoder.decode(providerData, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        RpcProvider rpcProvider = new RpcProvider();
        ProviderInfo providerInfo = ProviderHelper.toProviderInfo(providerData);

        rpcProvider.setServiceName(serviceName);
        rpcProvider.setAddress(providerInfo.getHost());
        rpcProvider.setPort(providerInfo.getPort());
        String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
        rpcProvider.setAppName(appName);
        rpcProvider.setWeight(providerInfo.getWeight());
        return rpcProvider;
    }
 
Example #17
Source File: ResourceWebHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Check whether the given path contains invalid escape sequences.
 * @param path the path to validate
 * @return {@code true} if the path is invalid, {@code false} otherwise
 */
private boolean isInvalidEncodedPath(String path) {
	if (path.contains("%")) {
		try {
			// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars
			String decodedPath = URLDecoder.decode(path, "UTF-8");
			if (isInvalidPath(decodedPath)) {
				return true;
			}
			decodedPath = processPath(decodedPath);
			if (isInvalidPath(decodedPath)) {
				return true;
			}
		}
		catch (IllegalArgumentException | UnsupportedEncodingException ex) {
			// Should never happen...
		}
	}
	return false;
}
 
Example #18
Source File: PathResourceResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private boolean isInvalidEncodedPath(String resourcePath) {
	if (resourcePath.contains("%")) {
		// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
		try {
			String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
			if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
				logger.warn("Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath);
				return true;
			}
		}
		catch (UnsupportedEncodingException ex) {
			// Should never happen...
		}
	}
	return false;
}
 
Example #19
Source File: QueryGenerator.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
/**
 * 高级查询
 * @param queryWrapper
 * @param parameterMap
 */
public static void doSuperQuery(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap) {
	if(parameterMap!=null&& parameterMap.containsKey(SUPER_QUERY_PARAMS)){
		String superQueryParams = parameterMap.get(SUPER_QUERY_PARAMS)[0];
		// 解码
		try {
			superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("--高级查询参数转码失败!", e);
		}
		List<QueryCondition> conditions = JSON.parseArray(superQueryParams, QueryCondition.class);
		log.info("---高级查询参数-->"+conditions.toString());
		
		for (QueryCondition rule : conditions) {
			if(oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal())){
				addEasyQuery(queryWrapper, rule.getField(), QueryRuleEnum.getByValue(rule.getRule()), rule.getVal());
			}
		}
	}
}
 
Example #20
Source File: UpdateGatewayRuleCommandHandler.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 rule data error", e);
        return CommandResponse.ofFailure(e, "decode gateway rule data error");
    }

    RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));

    String result = SUCCESS_MSG;
    List<GatewayFlowRule> flowRules = JSONArray.parseArray(data, GatewayFlowRule.class);
    GatewayRuleManager.loadRules(new HashSet<>(flowRules));
    return CommandResponse.ofSuccess(result);
}
 
Example #21
Source File: CookieUtils.java    From leyou with Apache License 2.0 6 votes vote down vote up
/**
 * 得到Cookie的值,
 *
 * @param request
 * @param cookieName
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
        return null;
    }
    String retValue = null;
    try {
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                if (isDecoder) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                } else {
                    retValue = cookieList[i].getValue();
                }
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("Cookie Decode Error.", e);
    }
    return retValue;
}
 
Example #22
Source File: DocumentCache.java    From jdk1.8-source-analysis with Apache License 2.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 #23
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public DataHandler getAttachmentAsDataHandler(String contentId) {
	if (contentId.startsWith(CID)) {
		contentId = contentId.substring(CID.length());
		try {
			contentId = URLDecoder.decode(contentId, "UTF-8");
		}
		catch (UnsupportedEncodingException ex) {
			// ignore
		}
		contentId = '<' + contentId + '>';
	}
	DataHandler dataHandler = this.mimeContainer.getAttachment(contentId);
	if (dataHandler == null) {
		throw new IllegalArgumentException("No attachment found for " + contentId);
	}
	return dataHandler;
}
 
Example #24
Source File: KcaPacketStore.java    From GotoBrowser with GNU General Public License v3.0 5 votes vote down vote up
public void record(String url, String request, String response) {
    SQLiteDatabase db = this.getWritableDatabase();

    // filter out api_token
    String[] request_data = request.split("&");
    List<String> new_request_data = new ArrayList<>();
    for (String s: request_data) {
        String decodedData = null;
        try {
            decodedData = URLDecoder.decode(s, "utf-8");
            if (!decodedData.startsWith("api_token")) {
                new_request_data.add(s);
            }
        } catch (UnsupportedEncodingException e) {
            KcUtils.reportException(e);
        }
    }
    request = KcUtils.joinStr(new_request_data, "&");

    // insert value to db
    ContentValues values = new ContentValues();
    values.put("URL", url);
    values.put("REQUEST", request);
    values.put("RESPONSE", response);
    values.put("TIMESTAMP", System.currentTimeMillis());
    db.insert(table_name, null, values);

    // remove older rows
    db.delete(table_name, "ROWID NOT IN (SELECT ROWID FROM " + table_name +
            " ORDER BY DKEY DESC LIMIT " + String.valueOf(limit) + ")", null);
}
 
Example #25
Source File: UrlUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation") 
public static String decode(String url) { 
	if (isUTF8(url)) { 
		url = UTF8Decode(url); 
	} else { 
		url = URLDecoder.decode(url); 
	} 
	return url; 
}
 
Example #26
Source File: B6463990.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    boolean except = false;
    try {
        URLDecoder ud = new java.net.URLDecoder();
        String s = ud.decode("%-1", "iso-8859-1");
        System.out.println((int) s.charAt(0));
    } catch (Exception e) {
        except = true;
    }
    if (!except)
        throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
Example #27
Source File: HttpRequestSessionContext.java    From presto with Apache License 2.0 5 votes vote down vote up
private static String urlDecode(String value)
{
    try {
        return URLDecoder.decode(value, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
}
 
Example #28
Source File: UploadHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   long startTime = System.nanoTime();

   HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req);
   try {
      String place = null;
      int num = 0;
      while(decoder.hasNext()) {
         num++;

         InterfaceHttpData httpData = decoder.next();
         if(httpData.getHttpDataType() == HttpDataType.Attribute && httpData.getName().equalsIgnoreCase("place")) {
            place = ((Attribute) httpData).getValue();
         } else if(httpData.getHttpDataType() == HttpDataType.FileUpload) {
            String camProtAddr = URLDecoder.decode(httpData.getName(), "UTF-8");
            Device d = findCamera(camProtAddr);
            if(d == null) {
               UPLOAD_UNKNOWN.inc();
               logger.warn("ignoring preview upload for non-existent camera {}", camProtAddr);
               continue;
            }
            write(place, d, (FileUpload) httpData);
         }
      }
      HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
      ChannelFuture future = ctx.writeAndFlush(response);
      if(!HttpHeaders.isKeepAlive(req)) {
         future.addListener(ChannelFutureListener.CLOSE);
      }

      UPLOAD_NUM.update(num);
      UPLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } catch (Exception ex) {
      UPLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
   } finally {
      decoder.cleanFiles();
   }
}
 
Example #29
Source File: AutoGeneratorUtil.java    From erp-framework with MIT License 5 votes vote down vote up
/**
 * 获取项目的路径
 *
 * @return
 * @throws Exception
 */
public static String getProjectPath() throws Exception {
    URL url = ErpFrameworkApplication.class.getProtectionDomain().getCodeSource().getLocation();
    String filePath = URLDecoder.decode(url.getPath(), "utf-8");
    filePath = filePath.substring(1, filePath.length() - ("/target/classes").length());

    // 处理操作系统,mac系统需要添加一个/
    String osName = System.getProperty("os.name").toLowerCase();
    if (osName.contains("mac")) {
        filePath = "/" + filePath;
    }

    return filePath;
}
 
Example #30
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;
}