Java Code Examples for java.net.URLDecoder

The following are top voted examples for showing how to use java.net.URLDecoder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: forweaver2.0   File: CommunityIntercepter.java   View source code 7 votes vote down vote up
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;
}
 
Example 2
Project: cas-server-4.2.1   File: FrontChannelLogoutActionTests.java   View source code 7 votes vote down vote up
@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>"));
}
 
Example 3
Project: sonar-quality-gates-plugin   File: JobConfigurationService.java   View source code 6 votes vote down vote up
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;
    }
 
Example 4
Project: weex-uikit   File: WXMetaModule.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 5
Project: RDF2PT   File: DefaultIRIConverterFrench.java   View source code 6 votes vote down vote up
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;
}
 
Example 6
Project: dubbox-hystrix   File: ExporterSideConfigUrlTest.java   View source code 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 7
Project: GitHub   File: AsyncHttpClient.java   View source code 6 votes vote down vote up
/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url             String with URL, should be valid URL without params
 * @param params          RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 */
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(), _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}
 
Example 8
Project: hadoop-oss   File: ClassUtil.java   View source code 6 votes vote down vote up
/** 
 * 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;
}
 
Example 9
Project: starcor.xul   File: XulDebugServer.java   View source code 6 votes vote down vote up
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;
}
 
Example 10
Project: illuminati   File: IlluminatiEsTemplateInterfaceModelImpl.java   View source code 6 votes vote down vote up
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()+")");
        }
    }
}
 
Example 11
Project: cf-java-client-sap   File: CloudControllerClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 12
Project: JavaQuarkBBS   File: CookieUtils.java   View source code 6 votes vote down vote up
/**
 * 得到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;
}
 
Example 13
Project: RxEasyHttp   File: CustomSignInterceptor.java   View source code 6 votes vote down vote up
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);
}
 
Example 14
Project: logistimo-web-service   File: OrderUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: minijax   File: ClassPathScanner.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 16
Project: RDF2PT   File: DefaultIRIConverter.java   View source code 6 votes vote down vote up
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;
}
 
Example 17
Project: fort_j   File: Files.java   View source code 6 votes vote down vote up
@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;
}
 
Example 18
Project: MVP-Practice-Project-Template   File: HttpLog.java   View source code 6 votes vote down vote up
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.";
    }
}
 
Example 19
Project: uroborosql   File: SqlLoaderImpl.java   View source code 6 votes vote down vote up
/**
 * {@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;
}
 
Example 20
Project: hadoop   File: TestNativeAzureFileSystemConcurrency.java   View source code 6 votes vote down vote up
@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));
}
 
Example 21
Project: boohee_v5.6   File: AsyncHttpClient.java   View source code 6 votes vote down vote up
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;
}
 
Example 22
Project: lucee-websocket   File: HandshakeHandler.java   View source code 6 votes vote down vote up
private static Map<String, String> parseRequestHeaderCookie(String requestHeaderCookie) {

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

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

		for (String c : cookies) {

			cookieParts = c.split("=");

			if (cookieParts.length != 2)
				continue;

			try {

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

		return result;
	}
 
Example 23
Project: OpenHub   File: WikiModel.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 24
Project: DWSurvey   File: MySurveyCreateAction.java   View source code 6 votes vote down vote up
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";
}
 
Example 25
Project: BBSSDK-for-Android   File: RichEditor.java   View source code 6 votes vote down vote up
@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);
}
 
Example 26
Project: ditb   File: ZKSplitLog.java   View source code 5 votes vote down vote up
static String decode(String s) {
  try {
    return URLDecoder.decode(s, "UTF-8");
  } catch (UnsupportedEncodingException e) {
    throw new RuntimeException("URLDecoder doesn't support UTF-8");
  }
}
 
Example 27
Project: opencron   File: TerminalController.java   View source code 5 votes vote down vote up
@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;
}
 
Example 28
Project: metanome-algorithms   File: BridgesFixture.java   View source code 5 votes vote down vote up
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;
}
 
Example 29
Project: urule   File: KnowledgePackageReceiverServlet.java   View source code 5 votes vote down vote up
@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();
}
 
Example 30
Project: flow-platform   File: MQLoader.java   View source code 5 votes vote down vote up
private String decode(String source) {
    if (Strings.isNullOrEmpty(source)) {
        return source;
    }

    try {
        return URLDecoder.decode(source, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example 31
Project: monarch   File: CliUtil.java   View source code 5 votes vote down vote up
public static String decodeWithDefaultCharSet(String urlToDecode) {
  try {
    return URLDecoder.decode(urlToDecode, Charset.defaultCharset().name());
  } catch (UnsupportedEncodingException e) {
    return urlToDecode;
  }
}
 
Example 32
Project: logistimo-web-service   File: BBoardMgrServlet.java   View source code 5 votes vote down vote up
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);
}
 
Example 33
Project: BasicsProject   File: ParseCodeUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 34
Project: openrasp   File: JarFileHelper.java   View source code 5 votes vote down vote up
/**
 * 获取当前所在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;
}
 
Example 35
Project: Equella   File: FileSystemHelper.java   View source code 5 votes vote down vote up
public static String decode(String url)
{
	try
	{
		return URLDecoder.decode(url, "UTF-8");
	}
	catch( UnsupportedEncodingException e )
	{
		throw new RuntimeException(e);
	}
}
 
Example 36
Project: aliyun-maxcompute-data-collectors   File: Jars.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 37
Project: ucar-weex-core   File: WXModalUIModule.java   View source code 5 votes vote down vote up
@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");
  }
}
 
Example 38
Project: webtrekk-android-sdk   File: Core.java   View source code 5 votes vote down vote up
private static String urlDecode(String string) {
	if (string == null || string.length() == 0) {
		return string;
	}
	
	try {
		return URLDecoder.decode(string, "UTF-8");
	}
	catch (UnsupportedEncodingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 39
Project: GitHub   File: CliMain.java   View source code 5 votes vote down vote up
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();
}
 
Example 40
Project: s-store   File: TestJDBCQueries.java   View source code 5 votes vote down vote up
@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();
}