Java 类java.net.URLDecoder 实例源码

项目:forweaver2.0    文件:CommunityIntercepter.java   
public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler)
                throws Exception {
    String uri = request.getRequestURI();
    Weaver weaver = weaverService.getCurrentWeaver();
    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;
        }

    }
    return true;
}
项目:sonar-quality-gates-plugin    文件:JobConfigurationService.java   
public JobConfigData createJobConfigData(JSONObject formData, GlobalConfig globalConfig) {

        JobConfigData firstInstanceJobConfigData = new JobConfigData();
        String projectKey = formData.getString("projectKey");

        if (!projectKey.startsWith("$")) {
            try {
                projectKey = URLDecoder.decode(projectKey, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new QGException("Error while decoding the project key. UTF-8 not supported.", e);
            }
        }

        String name;

        if (!globalConfig.fetchListOfGlobalConfigData().isEmpty()) {
            name = hasFormDataKey(formData, globalConfig);
        } else {
            name = "";
        }

        firstInstanceJobConfigData.setProjectKey(projectKey);
        firstInstanceJobConfigData.setSonarInstanceName(name);

        return firstInstanceJobConfigData;
    }
项目:weex-uikit    文件:WXMetaModule.java   
@JSMethod(uiThread = false)
public void setViewport(String param) {
    if (!TextUtils.isEmpty(param)) {
        try {
            param = URLDecoder.decode(param, "utf-8");
            JSONObject jsObj = JSON.parseObject(param);
            if (DEVICE_WIDTH.endsWith(jsObj.getString(WIDTH))) {
                mWXSDKInstance.setViewPortWidth(WXViewUtils.getScreenWidth(mWXSDKInstance.getContext()));
            } else {
                int width = jsObj.getInteger(WIDTH);
                if (width > 0) {
                    mWXSDKInstance.setViewPortWidth(width);
                }
            }
        } catch (Exception e) {
            WXLogUtils.e("[WXModalUIModule] alert param parse error ", e);
        }
    }
}
项目:RDF2PT    文件:DefaultIRIConverterFrench.java   
private String getLabelFromBuiltIn(String uri) {
    try {
        IRI iri = IRI.create(URLDecoder.decode(uri, "UTF-8"));

        // if IRI is built-in entity
        if (iri.isReservedVocabulary()) {
            // use the short form
            String label = sfp.getShortForm(iri);

            // if it is a XSD numeric data type, we attach "value"
            if (uri.equals(XSD.nonNegativeInteger.getURI()) || uri.equals(XSD.integer.getURI())
                    || uri.equals(XSD.negativeInteger.getURI()) || uri.equals(XSD.decimal.getURI())
                    || uri.equals(XSD.xdouble.getURI()) || uri.equals(XSD.xfloat.getURI())
                    || uri.equals(XSD.xint.getURI()) || uri.equals(XSD.xshort.getURI())
                    || uri.equals(XSD.xbyte.getURI()) || uri.equals(XSD.xlong.getURI())) {
                label += " value";
            }

            return label;
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("Getting short form of " + uri + "failed.", e);
    }
    return null;
}
项目:dubbox-hystrix    文件:ExporterSideConfigUrlTest.java   
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();
}
项目:hadoop-oss    文件:ClassUtil.java   
/** 
 * Find a jar that contains a class of the same name, if any.
 * It will return a jar file, even if that is not the first thing
 * on the class path that has a class with the same name.
 * 
 * @param clazz the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
public static String findContainingJar(Class<?> clazz) {
  ClassLoader loader = clazz.getClassLoader();
  String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
  try {
    for(final Enumeration<URL> itr = loader.getResources(classFile);
        itr.hasMoreElements();) {
      final URL url = itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn = url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn = toReturn.substring("file:".length());
        }
        toReturn = URLDecoder.decode(toReturn, "UTF-8");
        return toReturn.replaceAll("!.*$", "");
      }
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
项目:starcor.xul    文件:XulDebugServer.java   
private XulHttpServerResponse setItemStyle(XulHttpServerRequest request, String[] params) {
    if (params.length != 2 && params.length != 3) {
        return null;
    }
    XulHttpServerResponse response = getResponse(request);
    try {
        String name = URLDecoder.decode(params[1], "utf-8");
        String value = params.length > 2 ? URLDecoder.decode(params[2], "utf-8") : null;
        if (_monitor.setItemStyle(XulUtils.tryParseInt(params[0]), name, value, request, response)) {
            response.addHeader("Content-Type", "text/xml");
            response.writeBody("<result status=\"OK\"/>");
        } else {
            response.setStatus(404);
        }
    } catch (Exception e) {
        response.setStatus(501);
        e.printStackTrace(new PrintStream(response.getBodyStream()));
    }
    return response;
}
项目:illuminati    文件:IlluminatiEsTemplateInterfaceModelImpl.java   
private void setPostContentResultData () {
    final String postContentBody = this.header.getPostContentBody();

    if (StringObjectUtils.isValid(postContentBody)) {
        try {
            final String[] postContentBodyArray = URLDecoder.decode(postContentBody, "UTF-8").split("&");

            if (postContentBodyArray.length > 0) {
                this.postContentResultData = new HashMap<String, String>();
            }

            for (String element : postContentBodyArray) {
                final String[] elementArray = element.split("=");

                if (elementArray.length == 2) {
                    this.postContentResultData.put(elementArray[0], elementArray[1]);
                }
            }
        } catch (Exception ex) {
            ES_CONSUMER_LOGGER.error("Sorry. an error occurred during parsing of post content. ("+ex.toString()+")");
        }
    }
}
项目:cas-server-4.2.1    文件:FrontChannelLogoutActionTests.java   
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final SingleLogoutService service = new WebApplicationServiceFactory().createService(TEST_URL, SingleLogoutService.class);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID,
            service,
            new URL(TEST_URL));
    final Event event = getLogoutEvent(Arrays.asList(logoutRequest));

    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
    assertTrue(url.startsWith(TEST_URL + '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='));
    final byte[] samlMessage = CompressionUtils.decodeBase64ToByteArray(
            URLDecoder.decode(StringUtils.substringAfter(url, '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}
项目:cf-java-client-sap    文件:CloudControllerClientImpl.java   
@Override
public StartingInfo startApplication(String appName) {
    CloudApplication app = getApplication(appName);
    if (app.getState() != CloudApplication.AppState.STARTED) {
        HashMap<String, Object> appRequest = new HashMap<String, Object>();
        appRequest.put("state", CloudApplication.AppState.STARTED);

        HttpEntity<Object> requestEntity = new HttpEntity<Object>(appRequest);
        ResponseEntity<String> entity = getRestTemplate().exchange(getUrl("/v2/apps/{guid}?stage_async=true"), HttpMethod.PUT,
            requestEntity, String.class, app.getMeta().getGuid());

        HttpHeaders headers = entity.getHeaders();

        // Return a starting info, even with a null staging log value, as a non-null starting info
        // indicates that the response entity did have headers. The API contract is to return starting info
        // if there are headers in the response, null otherwise.
        if (headers != null && !headers.isEmpty()) {
            String stagingFile = headers.getFirst("x-app-staging-log");

            if (stagingFile != null) {
                try {
                    stagingFile = URLDecoder.decode(stagingFile, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    logger.error("unexpected inability to UTF-8 decode", e);
                }
            }
            // Return the starting info even if decoding failed or staging file is null
            return new StartingInfo(stagingFile);
        }
    }
    return null;
}
项目:JavaQuarkBBS    文件:CookieUtils.java   
/**
 * 得到Cookie的值,
 *
 * @param request
 * @param cookieName
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
    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)) {
                retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return retValue;
}
项目:RxEasyHttp    文件:CustomSignInterceptor.java   
private String sign(TreeMap<String, String> dynamicMap) {
    String url = getHttpUrl().url().toString();
    //url = url.replaceAll("%2F", "/");
    StringBuilder sb = new StringBuilder("POST");
    sb.append(url);
    for (Map.Entry<String, String> entry : dynamicMap.entrySet()) {
        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
    }

    sb.append(AppConstant.APP_SECRET);
    String signStr = sb.toString();
    try {
        signStr = URLDecoder.decode(signStr, UTF8.name());
    } catch (UnsupportedEncodingException exception) {
        exception.printStackTrace();
    }
    HttpLog.i(signStr);
    return MD5.encode(signStr);
}
项目:logistimo-web-service    文件:OrderUtils.java   
public static Map<String, String> getOrderFields(HttpServletRequest req, String statusCode,
                                                 FieldsConfig fc) {
  if (req == null || statusCode == null || statusCode.isEmpty() || fc == null || fc.isEmpty()) {
    return null;
  }
  Map<String, String> map = new HashMap<>();
  List<FieldsConfig.Field> fields = fc.getByStatus(statusCode);
  for (FieldsConfig.Field f : fields) {
    String key = f.getId();
    String val = req.getParameter(key);
    if (val != null) {
      try {
        val = URLDecoder.decode(val, "UTF-8").trim();
      } catch (UnsupportedEncodingException e) {
        xLogger.warn("Unsupported encoding exception: {0}", e.getMessage());
      }
      if (val.isEmpty()) {
        val = null;
      }
      map.put(key, val);
    }
  } // end while
  return map;
}
项目:minijax    文件:ClassPathScanner.java   
private void scanImpl(final String packageName, final ClassLoader classLoader) throws IOException {
    final Enumeration<URL> resources = classLoader.getResources(packageName.replace('.', '/'));

    while (resources.hasMoreElements()) {
        final URL url = resources.nextElement();
        final String protocol = url.getProtocol();

        if (protocol.equals("file")) {
            checkDirectory(classLoader, new File(URLDecoder.decode(url.getPath(), "UTF-8")), packageName);
        } else if (protocol.equals("jar")) {
            checkJarFile(classLoader, url, packageName);
        } else {
            throw new IllegalArgumentException("Unrecognized classpath protocol: " + protocol);
        }
    }
}
项目:RDF2PT    文件:DefaultIRIConverter.java   
private String getLabelFromBuiltIn(String uri){
    try {
        IRI iri = IRI.create(URLDecoder.decode(uri, "UTF-8"));

        // if IRI is built-in entity
        if(iri.isReservedVocabulary()) {
            // use the short form
            String label = sfp.getShortForm(iri);

             // if it is a XSD numeric data type, we attach "value"
            if(uri.equals(XSD.nonNegativeInteger.getURI()) || uri.equals(XSD.integer.getURI())
                    || uri.equals(XSD.negativeInteger.getURI()) || uri.equals(XSD.decimal.getURI())
                    || uri.equals(XSD.xdouble.getURI()) || uri.equals(XSD.xfloat.getURI())
                    || uri.equals(XSD.xint.getURI()) || uri.equals(XSD.xshort.getURI())
                    || uri.equals(XSD.xbyte.getURI()) || uri.equals(XSD.xlong.getURI())
                    ){
                label += " value";
            }

            return label;
        }
    } catch (UnsupportedEncodingException e) {
        logger.error("Getting short form of " + uri + "failed.", e);
    }
    return null;
}
项目:fort_j    文件:Files.java   
@ApiMethod
public static String getFilePath(String fileName)
{
   fileName = URLDecoder.decode(fileName);
   fileName = fileName.replace('\\', '/');

   if (fileName.endsWith("/"))
      return fileName;

   if (fileName.lastIndexOf("/") > 0)
   {
      fileName = fileName.substring(0, fileName.lastIndexOf("/"));
   }

   return fileName;
}
项目:MVP-Practice-Project-Template    文件:HttpLog.java   
private String bodyToString(final Request request) {
    try {
        final Request copy = request.newBuilder().build();
        final Buffer buffer = new Buffer();
        RequestBody body = copy.body();
        //get请求则body为空
        if (body == null) {
            return "";
        }
        body.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = body.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        return URLDecoder.decode(buffer.readString(charset), "UTF-8");
    } catch (final IOException e) {
        return "something error when show requestBody.";
    }
}
项目:uroborosql    文件:SqlLoaderImpl.java   
/**
 * {@inheritDoc}
 *
 * @see jp.co.future.uroborosql.store.SqlLoader#load()
 */
@Override
public ConcurrentHashMap<String, String> load() {
    ConcurrentHashMap<String, String> loadedSqlMap = new ConcurrentHashMap<>();
    try {
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(loadPath);
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            File rootDir = new File(URLDecoder.decode(resource.getFile(), StandardCharsets.UTF_8.toString()));

            if (!rootDir.exists() || !rootDir.isDirectory()) {
                if ("jar".equalsIgnoreCase(resource.getProtocol())) {
                    putAllIfAbsent(loadedSqlMap, load((JarURLConnection) resource.openConnection(), loadPath));
                    continue;
                }

                LOG.warn("Ignore because not directory.[{}]", rootDir.getAbsolutePath());
                continue;
            }

            LOG.debug("Start loading SQL template.[{}]", rootDir.getAbsolutePath());
            putAllIfAbsent(loadedSqlMap, load(new StringBuilder(), rootDir));
        }
    } catch (IOException e) {
        throw new UroborosqlRuntimeException("Failed to load SQL template.", e);
    }

    if (loadedSqlMap.isEmpty()) {
        LOG.warn("SQL template could not be found.");
        LOG.warn("Returns an empty SQL cache.");
    }

    return loadedSqlMap;
}
项目:hadoop    文件:TestNativeAzureFileSystemConcurrency.java   
@Test
public void testLinkBlobs() throws Exception {
  Path filePath = new Path("/inProgress");
  FSDataOutputStream outputStream = fs.create(filePath);
  // Since the stream is still open, we should see an empty link
  // blob in the backing store linking to the temporary file.
  HashMap<String, String> metadata = backingStore
      .getMetadata(AzureBlobStorageTestAccount.toMockUri(filePath));
  assertNotNull(metadata);
  String linkValue = metadata.get(AzureNativeFileSystemStore.LINK_BACK_TO_UPLOAD_IN_PROGRESS_METADATA_KEY);
  linkValue = URLDecoder.decode(linkValue, "UTF-8");
  assertNotNull(linkValue);
  assertTrue(backingStore.exists(AzureBlobStorageTestAccount
      .toMockUri(linkValue)));
  // Also, WASB should say the file exists now even before we close the
  // stream.
  assertTrue(fs.exists(filePath));
  outputStream.close();
  // Now there should be no link metadata on the final file.
  metadata = backingStore.getMetadata(AzureBlobStorageTestAccount
      .toMockUri(filePath));
  assertNull(metadata
      .get(AzureNativeFileSystemStore.LINK_BACK_TO_UPLOAD_IN_PROGRESS_METADATA_KEY));
}
项目:boohee_v5.6    文件:AsyncHttpClient.java   
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams
        params) {
    if (url == null) {
        return null;
    }
    if (shouldEncodeUrl) {
        try {
            URL _url = new URL(URLDecoder.decode(url, "UTF-8"));
            url = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url
                    .getPort(), _url.getPath(), _url.getQuery(), _url.getRef()).toASCIIString();
        } catch (Exception ex) {
            Log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }
    if (params != null) {
        String paramString = params.getParamString().trim();
        if (!(paramString.equals("") || paramString.equals("?"))) {
            url = (url + (url.contains("?") ? a.b : "?")) + paramString;
        }
    }
    return url;
}
项目:lucee-websocket    文件:HandshakeHandler.java   
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;
    }
项目:OpenHub    文件:WikiModel.java   
public String getName(){
    if(id != null && id.contains("wiki")){
        int start = id.indexOf("wiki/") + 5;
        int end = id.lastIndexOf("/");
        if(end > start){
            String name = id.substring(start, end).replaceAll("-", " ");
            try {
                name = URLDecoder.decode(name, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return name;
        } else {
            return "Home";
        }
    } else {
        return null;
    }
}
项目:DWSurvey    文件:MySurveyCreateAction.java   
public String save() throws Exception {
    String surveyName=Struts2Utils.getParameter("surveyName");
    SurveyDirectory survey = new SurveyDirectory();
    try{
        survey.setDirType(2);
        if(surveyName==null || "".equals(surveyName.trim())){
            surveyName="请输入问卷标题";
        }else{
            surveyName=URLDecoder.decode(surveyName,"utf-8");
        }
        survey.setSurveyName(surveyName);
        directoryManager.save(survey);
        surveyId = survey.getId();
    }catch(Exception e){
        e.printStackTrace();
    }
    return "design";
}
项目:BBSSDK-for-Android    文件:RichEditor.java   
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    String decode;
    try {
        decode = URLDecoder.decode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // No handling
        return false;
    }

    if (TextUtils.indexOf(url, CALLBACK_SCHEME) == 0) {
        callback(decode);
        return true;
    } else if (TextUtils.indexOf(url, STATE_SCHEME) == 0) {
        stateCheck(decode);
        return true;
    }

    return super.shouldOverrideUrlLoading(view, url);
}
项目:ditb    文件:ZKSplitLog.java   
static String decode(String s) {
  try {
    return URLDecoder.decode(s, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    throw new RuntimeException("URLDecoder doesn't support UTF-8");
  }
}
项目:opencron    文件:TerminalController.java   
@RequestMapping(value = "sendAll.do",method= RequestMethod.POST)
@ResponseBody
public boolean sendAll(String token, String cmd) throws Exception {
    cmd = URLDecoder.decode(cmd, "UTF-8");
    TerminalClient terminalClient = TerminalSession.get(token);
    if (terminalClient != null) {
        List<TerminalClient> terminalClients = TerminalSession.findClient(terminalClient.getHttpSessionId());
        for (TerminalClient client : terminalClients) {
            client.write(cmd);
        }
    }
    return true;
}
项目:metanome-algorithms    文件:BridgesFixture.java   
public RelationalInputGenerator getInputGenerator()
    throws InputGenerationException, InputIterationException, UnsupportedEncodingException,
           FileNotFoundException {
  String
      pathToInputFile =
      URLDecoder.decode(
          Thread.currentThread().getContextClassLoader().getResource(relationName).getPath(),
          "utf-8");
  RelationalInputGenerator
      inputGenerator =
      new DefaultFileInputGenerator(new File(pathToInputFile));
  return inputGenerator;
}
项目:urule    文件:KnowledgePackageReceiverServlet.java   
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String packageId=req.getParameter("packageId");
    if(StringUtils.isEmpty(packageId)){
        return;
    }
    packageId=URLDecoder.decode(packageId, "utf-8");
    if(packageId.startsWith("/")){
        packageId=packageId.substring(1,packageId.length());
    }
    String content=req.getParameter("content");
    if(StringUtils.isEmpty(content)){
        return;
    }
    content=URLDecoder.decode(content, "utf-8");
    ObjectMapper mapper=new ObjectMapper();
    mapper.getDeserializationConfig().withDateFormat(new SimpleDateFormat(Configure.getDateFormat()));
    KnowledgePackageWrapper wrapper=mapper.readValue(content, KnowledgePackageWrapper.class);
    wrapper.buildDeserialize();
    KnowledgePackage knowledgePackage=wrapper.getKnowledgePackage();
    Map<String, FlowDefinition> flowMap=knowledgePackage.getFlowMap();
    if(flowMap!=null && flowMap.size()>0){
        for(FlowDefinition fd:flowMap.values()){
            fd.buildConnectionToNode();
        }
    }
    CacheUtils.getKnowledgeCache().putKnowledge(packageId, knowledgePackage);
    SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("["+sd.format(new Date())+"] "+"Successfully receive the server side to pushed package:"+packageId);
    resp.setContentType("text/plain");
    PrintWriter pw=resp.getWriter();
    pw.write("ok");
    pw.flush();
    pw.close();
}
项目:flow-platform    文件:MQLoader.java   
private String decode(String source) {
    if (Strings.isNullOrEmpty(source)) {
        return source;
    }

    try {
        return URLDecoder.decode(source, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
项目:monarch    文件:CliUtil.java   
public static String decodeWithDefaultCharSet(String urlToDecode) {
  try {
    return URLDecoder.decode(urlToDecode, Charset.defaultCharset().name());
  } catch (UnsupportedEncodingException e) {
    return urlToDecode;
  }
}
项目:logistimo-web-service    文件:BBoardMgrServlet.java   
private void postMessage(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
  xLogger.fine("Entered postMessage");
  String message = request.getParameter("message");
  if (message != null && !message.isEmpty()) {
    message = URLDecoder.decode(message, "UTF-8");
  } else {
    xLogger.severe("No message to post to Bulletin Board");
    sendJsonResponse(response, 200, "{\"st\": \"0\", \"ms\": \"No message to post\" }");
  }
  String jsonResp = null;
  try {
    // Get the user Id
    SecureUserDetails sUser = SecurityMgr.getUserDetails(request.getSession());
    xLogger.fine("sUser: {0}", sUser);
    String userId = sUser.getUsername();
    Long domainId = SessionMgr.getCurrentDomain(request.getSession(), userId);
    // Create the BBoard message
    IBBoard bb = JDOUtils.createInstance(IBBoard.class);
    bb.setDomainId(domainId);
    bb.setMessage(message);
    bb.setTimestamp(new Date());
    bb.setType(IBBoard.TYPE_POST);
    bb.setUserId(userId);
    BBHandler.add(bb);
    // Get back to user
    jsonResp = "{ \"st\": \"1\" }"; // success
  } catch (Exception e) {
    jsonResp = "{\"st\": \"0\", \"ms\": \"" + e.getMessage() + "\" }";
  }
  xLogger.fine("Exiting postMessage: {0}", jsonResp);
  sendJsonResponse(response, 200, jsonResp);
}
项目:BasicsProject    文件:ParseCodeUtil.java   
public static final String decode(String obj, String type) {
    try {
        return URLDecoder.decode(obj, type);
    } catch (UnsupportedEncodingException e) {
        System.out.println("解析字符串失败:{}。"+e.toString());
    }
    return null;
}
项目:openrasp    文件:JarFileHelper.java   
/**
 * 获取当前所在jar包的路径
 *
 * @return jar包路径
 */
private static String getLocalJarPath() {
    URL localUrl = Agent.class.getProtectionDomain().getCodeSource().getLocation();
    String path = null;
    try {
        path = URLDecoder.decode(
                localUrl.getFile().replace("+", "%2B"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return path;
}
项目:Equella    文件:FileSystemHelper.java   
public static String decode(String url)
{
    try
    {
        return URLDecoder.decode(url, "UTF-8");
    }
    catch( UnsupportedEncodingException e )
    {
        throw new RuntimeException(e);
    }
}
项目:aliyun-maxcompute-data-collectors    文件:Jars.java   
/**
 * Return the jar file path that contains a particular class.
 * Method mostly cloned from o.a.h.mapred.JobConf.findContainingJar().
 */
public static String getJarPathForClass(Class<? extends Object> classObj) {
  ClassLoader loader = classObj.getClassLoader();
  String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
  try {
    for (Enumeration<URL> itr = loader.getResources(classFile);
        itr.hasMoreElements();) {
      URL url = (URL) itr.nextElement();
      if ("jar".equals(url.getProtocol())) {
        String toReturn = url.getPath();
        if (toReturn.startsWith("file:")) {
          toReturn = toReturn.substring("file:".length());
        }
        // URLDecoder is a misnamed class, since it actually decodes
        // x-www-form-urlencoded MIME type rather than actual
        // URL encoding (which the file path has). Therefore it would
        // decode +s to ' 's which is incorrect (spaces are actually
        // either unencoded or encoded as "%20"). Replace +s first, so
        // that they are kept sacred during the decoding process.
        toReturn = toReturn.replaceAll("\\+", "%2B");
        toReturn = URLDecoder.decode(toReturn, "UTF-8");
        return toReturn.replaceAll("!.*$", "");
      }
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  return null;
}
项目:ucar-weex-core    文件:WXModalUIModule.java   
@JSMethod(uiThread = true)
public void alert(String param, final JSCallback callback) {

  if (mWXSDKInstance.getContext() instanceof Activity) {

    String message = "";
    String okTitle = OK;
    if (!TextUtils.isEmpty(param)) {
      try {
        param = URLDecoder.decode(param, "utf-8");
        JSONObject jsObj = JSON.parseObject(param);
        message = jsObj.getString(MESSAGE);
        okTitle = jsObj.getString(OK_TITLE);
      } catch (Exception e) {
        WXLogUtils.e("[WXModalUIModule] alert param parse error ", e);
      }
    }
    if (TextUtils.isEmpty(message)) {
      message = "";
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(mWXSDKInstance.getContext());
    builder.setMessage(message);

    final String okTitle_f = TextUtils.isEmpty(okTitle) ? OK : okTitle;
    builder.setPositiveButton(okTitle_f, new OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        if (callback != null) {
          callback.invoke(okTitle_f);
        }
      }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.setCanceledOnTouchOutside(false);
    alertDialog.show();
    tracking(alertDialog);
  } else {
    WXLogUtils.e("[WXModalUIModule] when call alert mWXSDKInstance.getContext() must instanceof Activity");
  }
}
项目:webtrekk-android-sdk    文件:Core.java   
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);
    }
}
项目:GitHub    文件:CliMain.java   
private static void setRunningLocation(CliMain m) {
    mRunningLocation = m.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    try {
        mRunningLocation = URLDecoder.decode(mRunningLocation, "utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (mRunningLocation.endsWith(".jar")) {
        mRunningLocation = mRunningLocation.substring(0, mRunningLocation.lastIndexOf(File.separator) + 1);
    }
    File f = new File(mRunningLocation);
    mRunningLocation = f.getAbsolutePath();
}
项目:s-store    文件:TestJDBCQueries.java   
@BeforeClass
public static void setUp() throws Exception {

    URL url = TPCCClient.class.getResource("sqljdbc.sql");
    String schemaPath = URLDecoder.decode(url.getPath(), "UTF-8");
    pb = new VoltProjectBuilder("jdbcQueries");
    pb.addProcedures(org.voltdb.compiler.procedures.TPCCTestProc.class);
    pb.addSchema(schemaPath);
    testjar = "/tmp/jdbcdrivertest.jar";
    boolean success = pb.compile(testjar);
    assert(success);

    // Set up ServerThread and Connection
    startServer();
}
项目:112016.pizzeria-app    文件:ListerPizzaController.java   
@Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String message = req.getParameter("urlMessage");
if(message != null) {
    req.setAttribute("message", URLDecoder.decode(message, "UTF-8"));
}
   req.setAttribute("listePizzas", this.pizzaService.findAll());
   RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(VUE_LISTER_PIZZAS);
   dispatcher.forward(req, resp);
 }