Java Code Examples for java.net.URLEncoder
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project agile, under directory /agile-api/src/main/java/org/headsupdev/agile/api/.
Source file: LinkProvider.java

public String getLink(String params,Project project){ String encoded=params.replace('/',':'); try { encoded=URLEncoder.encode(encoded,"UTF-8"); } catch ( UnsupportedEncodingException e) { } String projectId=Project.ALL_PROJECT_ID; if (project != null) { projectId=project.getId(); } return "/" + projectId + "/"+ getPageName()+ "/"+ getParamName()+ "/"+ encoded; }
Example 2
From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/util/.
Source file: UriUtility.java

private static String encode(final String content,final String encoding){ try { return URLEncoder.encode(content,encoding != null ? encoding : "UTF-8"); } catch ( UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } }
Example 3
From project agorava-core, under directory /agorava-core-impl/src/main/java/org/agorava/core/utils/.
Source file: URLUtils.java

/** * Translates a string into application/x-www-form-urlencoded format * @param string to encode * @return form-urlencoded string */ private static String formURLEncode(String string){ try { return URLEncoder.encode(string,UTF_8); } catch ( UnsupportedEncodingException uee) { throw new IllegalStateException(ERROR_MSG,uee); } }
Example 4
From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.
Source file: URISupport.java

public static String createQueryString(Map options) throws URISyntaxException { try { if (options.size() > 0) { StringBuffer rc=new StringBuffer(); boolean first=true; for (Iterator iter=options.keySet().iterator(); iter.hasNext(); ) { if (first) { first=false; } else { rc.append("&"); } String key=(String)iter.next(); String value=(String)options.get(key); rc.append(URLEncoder.encode(key,"UTF-8")); rc.append("="); rc.append(URLEncoder.encode(value,"UTF-8")); } return rc.toString(); } else { return ""; } } catch ( UnsupportedEncodingException e) { throw (URISyntaxException)new URISyntaxException(e.toString(),"Invalid encoding").initCause(e); } }
Example 5
From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.
Source file: AlfrescoKickstartServiceImpl.java

protected void deleteFormConfig(String workflowId){ String url=SHARE_BASE_URL + "page/modules/module/delete?moduleId=" + URLEncoder.encode("kickstart_form_" + workflowId); int statusCode=executeDelete(url); int version=1; while (statusCode == 200) { statusCode=executeDelete(url + "_" + version); version++; } }
Example 6
From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/.
Source file: ArtifactGet.java

@Override protected void execute(ActivitiRequest req,Status status,Cache cache,Map<String,Object> model){ String connectorId=req.getMandatoryString("connectorId"); String artifactId=req.getString("artifactId"); String restProxyUri=req.getString("restProxyUri"); RepositoryArtifact artifact=repositoryService.getRepositoryArtifact(connectorId,artifactId); List<String> contentRepresentations=new ArrayList<String>(); for ( ContentRepresentation representation : contentService.getContentRepresentations(artifact)) { contentRepresentations.add(representation.getId()); } model.put("contentRepresentations",contentRepresentations); model.put("actions",pluginService.getParameterizedActions(artifact)); List<DownloadActionView> downloads=new ArrayList<DownloadActionView>(); for ( DownloadContentAction action : pluginService.getDownloadContentActions(artifact)) { try { String url=restProxyUri + "content?connectorId=" + URLEncoder.encode(connectorId,"UTF-8")+ "&artifactId="+ URLEncoder.encode(artifactId,"UTF-8")+ "&contentRepresentationId="+ URLEncoder.encode(action.getContentRepresentation().getId(),"UTF-8"); downloads.add(new DownloadActionView(action.getId(),url,action.getContentRepresentation().getRepresentationMimeType().getContentType(),action.getContentRepresentation().getId())); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } } model.put("downloads",downloads); model.put("links",pluginService.getArtifactOpenLinkActions(artifact)); model.put("artifactId",artifact.getNodeId()); model.put("connectorId",artifact.getConnectorId()); }
Example 7
From project agraph-java-client, under directory /src/com/franz/agraph/http/.
Source file: AGProtocol.java

public static String encode(String s){ try { return URLEncoder.encode(s,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("This JVM does not support UTF-8?"); } }
Example 8
From project aio-webos, under directory /portlet/webosadmin/src/main/java/org/exoplatform/dashboard/webui/component/.
Source file: UIWebOSTabPaneDashboard.java

public void execute(Event<UIWebOSTabPaneDashboard> event) throws Exception { UIWebOSTabPaneDashboard source=event.getSource(); WebuiRequestContext context=event.getRequestContext(); int removedNodeIndex=Integer.parseInt(context.getRequestParameter(UIComponent.OBJECTID)); PageNode selectedNode=source.removePageNode(removedNodeIndex); if (selectedNode != null) { UIPortal uiPortal=Util.getUIPortal(); UIPageBody uiPageBody=uiPortal.findFirstComponentOfType(UIPageBody.class); if (uiPageBody != null && uiPageBody.getMaximizedUIComponent() != null) { uiPageBody.setMaximizedUIComponent(null); } PortalRequestContext prContext=Util.getPortalRequestContext(); prContext.setResponseComplete(true); prContext.getResponse().sendRedirect(prContext.getPortalURI() + URLEncoder.encode(selectedNode.getUri(),"UTF-8")); } }
Example 9
From project akela, under directory /src/test/java/com/mozilla/pig/eval/regex/.
Source file: EncodeChromeUrlTest.java

@Test public void testExec3() throws IOException { Tuple input=tupleFactory.newTuple(); String inputStr="foochrome://global/locale/intl.propertiesbar"; input.append(inputStr); String encodedStr=URLEncoder.encode(inputStr,"UTF-8"); String outputStr=encoder.exec(input); assertEquals(encodedStr,outputStr); }
Example 10
From project Alerte-voirie-android, under directory /src/com/c4mprod/utils/.
Source file: ImageDownloader.java

/** * Download the specified image from the Internet and binds it to the provided ImageView. The binding is immediate if the image is found in the cache and will be done asynchronously otherwise. A null bitmap will be associated to the ImageView if an error occurs. * @param url * @param imageView * @param subfolder the subfolder in sdcard cache */ public void download(String url,ImageView imageView,String subfolder){ if (subfolder != null) { mSubfolder="/" + subfolder; } else { mSubfolder=""; } mfolder=Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + imageView.getContext().getPackageName()+ "/files/images"+ mSubfolder; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable=mExternalStorageWriteable=true; try { (new File(mfolder)).mkdirs(); (new File(mfolder + "/.nomedia")).createNewFile(); } catch ( IOException e) { e.printStackTrace(); } } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable=true; mExternalStorageWriteable=false; } else { mExternalStorageAvailable=mExternalStorageWriteable=false; } resetPurgeTimer(); Bitmap bitmap=getBitmapFromCache(url); if (bitmap == null) { forceDownload(url,imageView); } else { cancelPotentialDownload(url,imageView); imageView.setImageBitmap(bitmap); imageView.setBackgroundDrawable(null); if (listener != null) { listener.onImageDownloaded(imageView,url,mfolder + "/" + URLEncoder.encode(url),imageView.getDrawable().getIntrinsicWidth(),imageView.getDrawable().getIntrinsicWidth()); } } }
Example 11
From project Amantech, under directory /Android/cloudLogin/src/com/cloude/entropin/.
Source file: GAEConnector.java

/** * Get AuthCookie from App Engine */ private Cookie retrieveAuthCookie(String authToken) throws ClientProtocolException, IOException { String url=_gaeAppLoginUrl + "?continue=" + URLEncoder.encode(_gaeAppBaseUrl,"UTF-8")+ "&auth="+ URLEncoder.encode(authToken,"UTF-8"); Log.d("retrieveAuthCookie","cookieUrl = " + url); DefaultHttpClient httpClient=new DefaultHttpClient(); BasicHttpParams params=new BasicHttpParams(); HttpClientParams.setRedirecting(params,false); httpClient.setParams(params); HttpGet httpget=new HttpGet(url); HttpResponse response=httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() != 302) return null; Cookie theCookie=null; String cookieName=_usehttps ? "SACSID" : "ACSID"; for ( Cookie c : httpClient.getCookieStore().getCookies()) { if (c.getName().equals(cookieName)) { theCookie=c; Log.v("retrieveAuthCookie","TheCookie: " + theCookie.getName() + " = "+ theCookie.getValue()); } } return theCookie; }
Example 12
From project amber, under directory /oauth-2.0/common/src/main/java/org/apache/amber/oauth2/common/utils/.
Source file: OAuthUtils.java

private static String encode(final String content,final String encoding){ try { return URLEncoder.encode(content,encoding != null ? encoding : "UTF-8"); } catch ( UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } }
Example 13
From project AmDroid, under directory /AmenLib/src/main/java/com.jaeckel/amenoid/api/.
Source file: RequestFactory.java

private static String createQueryString(Map<String,String> params,boolean addTimeStamp){ StringBuilder nameValuePairs=new StringBuilder(); if (addTimeStamp || params != null) { nameValuePairs.append("?"); } if (params != null) { for ( String key : params.keySet()) { final String value=params.get(key); if (value == null) { log.error("Value for key " + key + " was null"); } else { nameValuePairs.append("&").append(key).append("=").append(URLEncoder.encode(value)); } } } if (addTimeStamp) { nameValuePairs.append("&_=" + new Date().getTime()); } return nameValuePairs.toString(); }
Example 14
From project andlytics, under directory /src/com/github/andlyticsproject/admob/.
Source file: AdmobRequest.java

public static String login(String email,String password) throws NetworkException, AdmobInvalidTokenException, AdmobGenericException, AdmobInvalidRequestException, AdmobRateLimitExceededException { String token=null; String params="client_key=" + clientKey + "&email="+ URLEncoder.encode(email)+ "&password="+ URLEncoder.encode(password); try { Log.d(TAG,email + " admob login request"); JSONArray data=getResponse("auth","login",params,true,true); token=data.getJSONObject(0).getString("token"); } catch ( JSONException e) { throw new AdmobGenericException(e); } return token; }
Example 15
From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.
Source file: VersionedCatchHttpClient.java

public void setAccessToken(String accessToken){ try { mEncodedAccessToken="access_token=" + URLEncoder.encode(accessToken,HTTP.UTF_8); } catch ( UnsupportedEncodingException e) { throw new AssertionError(e); } }
Example 16
From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.
Source file: Requests.java

/** * Converts strings to UCS Transformation Format - 8-bit(UTF-8) for calling XWiki RESTful API Does URL encoding of the keyword. * @param keyword text to convert * @return converted text */ private String convertToUTF(String keyword){ try { keyword=URLEncoder.encode(keyword,"UTF-8"); } catch ( UnsupportedEncodingException e) { Log.d("Error","Unsupported keyword is found"); keyword="error in converting to UTF-8"; e.printStackTrace(); } return keyword; }
Example 17
From project android-joedayz, under directory /Proyectos/FBConnectTest/src/com/facebook/android/.
Source file: Util.java

public static String encodeUrl(Bundle parameters){ if (parameters == null) { return ""; } StringBuilder sb=new StringBuilder(); boolean first=true; for ( String key : parameters.keySet()) { Object parameter=parameters.get(key); if (!(parameter instanceof String)) { continue; } if (first) first=false; else sb.append("&"); sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } return sb.toString(); }
Example 18
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/facebook/extpack/com/facebook/android/.
Source file: Util.java

public static String encodeUrl(Bundle parameters){ if (parameters == null) { return ""; } StringBuilder sb=new StringBuilder(); boolean first=true; for ( String key : parameters.keySet()) { if (first) first=false; else sb.append("&"); sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } return sb.toString(); }
Example 19
From project android-tether, under directory /facebook/src/com/facebook/android/.
Source file: Util.java

public static String encodeUrl(Bundle parameters){ if (parameters == null) { return ""; } StringBuilder sb=new StringBuilder(); boolean first=true; for ( String key : parameters.keySet()) { if (first) first=false; else sb.append("&"); sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } return sb.toString(); }
Example 20
From project android-xbmcremote, under directory /src/org/xbmc/httpapi/.
Source file: Connection.java

/** * Returns the full URL of an HTTP API request * @param command Name of the command to execute * @param parameters Parameters, separated by ";". * @return Absolute URL to HTTP API */ public String getUrl(String command,String parameters){ StringBuilder sb=new StringBuilder(mUrlSuffix); sb.append(XBMC_HTTP_BOOTSTRAP); sb.append("?command="); sb.append(command); sb.append("("); sb.append(URLEncoder.encode(parameters)); sb.append(")"); return sb.toString(); }
Example 21
From project android_7, under directory /src/org/immopoly/android/app/.
Source file: UserLoginActivity.java

@Override protected ImmopolyUser doInBackground(String... params){ String username=params[0]; String password=params[1]; JSONObject obj=null; ImmopolyUser user=null; try { toggleProgress(); obj=WebHelper.getHttpsData(new URL(WebHelper.SERVER_HTTPS_URL_PREFIX + "/user/login?username=" + URLEncoder.encode(username)+ "&password="+ URLEncoder.encode(password)),false,UserLoginActivity.this); if (obj != null && obj.has(Const.MESSAGE_IMMOPOLY_EXCEPTION)) { result.exception=new ImmopolyException(UserLoginActivity.this,obj); } else { user=ImmopolyUser.getInstance(); user.fromJSON(obj); if (user != null && user.getToken().length() > 0) result.success=true; } } catch ( ImmopolyException e) { e.printStackTrace(); result.exception=e; } catch ( MalformedURLException e) { e.printStackTrace(); result.exception=new ImmopolyException(e); } toggleProgress(); return user; }
Example 22
From project android_external_oauth, under directory /core/src/main/java/net/oauth/.
Source file: OAuth.java

public static String percentEncode(String s){ if (s == null) { return ""; } try { return URLEncoder.encode(s,ENCODING).replace("+","%20").replace("*","%2A").replace("%7E","~"); } catch ( UnsupportedEncodingException wow) { throw new RuntimeException(wow.getMessage(),wow); } }
Example 23
From project android_packages_apps_Gallery2, under directory /src/com/android/gallery3d/data/.
Source file: UriSource.java

@Override public Path findPathByUri(Uri uri,String type){ String mimeType=getMimeType(uri); if ((type == null) || (IMAGE_TYPE_ANY.equals(type) && mimeType.startsWith(IMAGE_TYPE_PREFIX))) { type=mimeType; } if (type.startsWith(IMAGE_TYPE_PREFIX)) { return Path.fromString("/uri/" + URLEncoder.encode(uri.toString()) + "/"+ URLEncoder.encode(type)); } return null; }
Example 24
From project Anki-Android, under directory /src/com/ichi2/anki/.
Source file: AnkiDroidProxy.java

public String getDecks(){ String decksServer="{}"; try { String data="p=" + URLEncoder.encode(mPassword,"UTF-8") + "&client=ankidroid-0.4&u="+ URLEncoder.encode(mUsername,"UTF-8")+ "&d=None&sources="+ URLEncoder.encode("[]","UTF-8")+ "&libanki=0.9.9.8.6&pversion=5"; HttpPost httpPost=new HttpPost(SYNC_URL + "getDecks"); StringEntity entity=new StringEntity(data); httpPost.setEntity(entity); httpPost.setHeader("Accept-Encoding","identity"); httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); DefaultHttpClient httpClient=new DefaultHttpClient(); HttpResponse response=httpClient.execute(httpPost); Log.i(AnkiDroidApp.TAG,"Response = " + response.toString()); HttpEntity entityResponse=response.getEntity(); Log.i(AnkiDroidApp.TAG,"Entity's response = " + entityResponse.toString()); InputStream content=entityResponse.getContent(); Log.i(AnkiDroidApp.TAG,"Content = " + content.toString()); decksServer=Utils.convertStreamToString(new InflaterInputStream(content)); Log.i(AnkiDroidApp.TAG,"String content = " + decksServer); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } catch ( ClientProtocolException e) { Log.i(AnkiDroidApp.TAG,"ClientProtocolException = " + e.getMessage()); } catch ( IOException e) { Log.i(AnkiDroidApp.TAG,"IOException = " + e.getMessage()); } return decksServer; }
Example 25
From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/controlpanel/.
Source file: SearchOptionsPanel.java

public void updateSegmentationList(Set<String> corpora){ WebResource service=Helper.getAnnisWebResource(getApplication()); if (service != null) { List<AnnisAttribute> attributes=new LinkedList<AnnisAttribute>(); String lastSelection=(String)cbSegmentation.getValue(); cbSegmentation.removeAllItems(); for ( String corpus : corpora) { try { attributes.addAll(service.path("corpora").path(URLEncoder.encode(corpus,"UTF-8")).path("annotations").queryParam("fetchvalues","true").queryParam("onlymostfrequentvalues","true").get(new GenericType<List<AnnisAttribute>>(){ } )); } catch ( UnsupportedEncodingException ex) { log.error(null,ex); } CorpusConfig config=Helper.getCorpusConfig(corpus,getApplication(),getWindow()); if (config.getConfig().containsKey(DEFAULT_SEGMENTATION)) { lastSelection=config.getConfig().get(DEFAULT_SEGMENTATION); } } for ( AnnisAttribute att : attributes) { if (AnnisAttribute.Type.segmentation == att.getType() && att.getName() != null) { cbSegmentation.addItem(att.getName()); } } cbSegmentation.setValue(lastSelection); } }
Example 26
From project AntiCheat, under directory /src/main/java/net/h31ix/anticheat/util/.
Source file: PastebinReport.java

private void postReport(){ try { URL urls=new URL("http://pastebin.com/api/api_post.php"); HttpURLConnection conn=(HttpURLConnection)urls.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-type","application/x-www-form-urlencoded"); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); OutputStream out=conn.getOutputStream(); out.write(("api_option=paste" + "&api_dev_key=" + URLEncoder.encode("c0616def494dcb5b7632304f8c52c0f1","utf-8") + "&api_paste_code="+ URLEncoder.encode(report.toString(),"utf-8")+ "&api_paste_private="+ URLEncoder.encode("0","utf-8")+ "&api_paste_name="+ URLEncoder.encode("","utf-8")+ "&api_paste_expire_date="+ URLEncoder.encode("1D","utf-8")+ "&api_paste_format="+ URLEncoder.encode("text","utf-8")+ "&api_user_key="+ URLEncoder.encode("","utf-8")).getBytes()); out.flush(); out.close(); if (conn.getResponseCode() == 200) { InputStream receive=conn.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(receive)); String line; StringBuffer response=new StringBuffer(); while ((line=reader.readLine()) != null) { response.append(line); response.append("\r\n"); } reader.close(); String result=response.toString().trim(); if (!result.contains("http://")) { url="Failed to post. Check report.txt"; } else { url=result.trim(); } } else { url="Failed to post. Check report.txt"; } } catch ( Exception e) { url="Failed to post. Check report.txt"; } }
Example 27
From project any23, under directory /core/src/main/java/org/apache/any23/http/.
Source file: DefaultHTTPClient.java

/** * Opens an {@link java.io.InputStream} from a given URI.It follows redirects. * @param uri to be opened * @return {@link java.io.InputStream} * @throws IOException */ public InputStream openInputStream(String uri) throws IOException { GetMethod method=null; try { ensureClientInitialized(); String uriStr; try { URI uriObj=new URI(uri); final String path=uriObj.getPath(); final String query=uriObj.getQuery(); final String fragment=uriObj.getFragment(); uriStr=String.format("%s://%s%s%s%s%s%s",uriObj.getScheme(),uriObj.getAuthority(),path != null ? URLEncoder.encode(path,"UTF-8").replaceAll("%2F","/") : "",query == null ? "" : "?",query != null ? URLEncoder.encode(query,"UTF-8").replaceAll("%3D","=").replaceAll("%26","&") : "",fragment == null ? "" : "#",fragment != null ? URLEncoder.encode(fragment,"UTF-8") : ""); } catch ( URISyntaxException e) { throw new IllegalArgumentException("Invalid URI string.",e); } method=new GetMethod(uriStr); method.setFollowRedirects(true); client.executeMethod(method); _contentLength=method.getResponseContentLength(); final Header contentTypeHeader=method.getResponseHeader("Content-Type"); contentType=contentTypeHeader == null ? null : contentTypeHeader.getValue(); if (method.getStatusCode() != 200) { throw new IOException("Failed to fetch " + uri + ": "+ method.getStatusCode()+ " "+ method.getStatusText()); } actualDocumentURI=method.getURI().toString(); byte[] response=method.getResponseBody(); return new ByteArrayInputStream(response); } finally { if (method != null) { method.releaseConnection(); } } }
Example 28
From project apps-for-android, under directory /Translate/src/com/beust/android/translate/.
Source file: Translate.java

/** * Forms an HTTP request and parses the response for a translation. * @param text The String to translate. * @param from The language code to translate from. * @param to The language code to translate to. * @return The translated String. * @throws Exception */ private static String retrieveTranslation(String text,String from,String to) throws Exception { try { StringBuilder url=new StringBuilder(); url.append(URL_STRING).append(from).append("%7C").append(to); url.append(TEXT_VAR).append(URLEncoder.encode(text,ENCODING)); Log.d(TranslateService.TAG,"Connecting to " + url.toString()); HttpURLConnection uc=(HttpURLConnection)new URL(url.toString()).openConnection(); uc.setDoInput(true); uc.setDoOutput(true); try { Log.d(TranslateService.TAG,"getInputStream()"); InputStream is=uc.getInputStream(); String result=toString(is); JSONObject json=new JSONObject(result); return ((JSONObject)json.get("responseData")).getString("translatedText"); } finally { uc.getInputStream().close(); if (uc.getErrorStream() != null) uc.getErrorStream().close(); } } catch ( Exception ex) { throw ex; } }
Example 29
From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/ui/.
Source file: TagStreamFragment.java

@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){ ViewGroup root=(ViewGroup)inflater.inflate(R.layout.fragment_webview_with_spinner,null); root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner=root.findViewById(R.id.loading_spinner); mWebView=(WebView)root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable(){ public void run(){ mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl("http://www.google.com/search?tbs=" + "mbl%3A1&hl=en&source=hp&biw=1170&bih=668&q=" + URLEncoder.encode(mSearchString,"UTF-8") + "&btnG=Search"); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Could not construct the realtime search URL",e); } } } ); return root; }
Example 30
From project aranea, under directory /api/src/main/java/no/dusken/aranea/model/.
Source file: Page.java

public String getSafeTitle(){ if (safeTitle == null) { try { safeTitle=URLEncoder.encode(getTitle().toLowerCase(),"UTF-8"); } catch ( UnsupportedEncodingException e) { } } return safeTitle; }
Example 31
From project ardverk-commons, under directory /src/main/java/org/ardverk/utils/.
Source file: StringUtils.java

public static String encodeURL(String value,String encoding){ try { return URLEncoder.encode(value,encoding); } catch ( UnsupportedEncodingException err) { throw new IllegalArgumentException("UnsupportedEncodingException",err); } }
Example 32
From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.
Source file: CommonTomcatManager.java

public void deploy(String name,URL content) throws IOException, DeploymentException { final String contentType="application/octet-stream"; Validate.notNullOrEmpty(name,"Name must not be null or empty"); Validate.notNull(content,"Content to be deployed must not be null"); URLConnection conn=content.openConnection(); int contentLength=conn.getContentLength(); InputStream stream=new BufferedInputStream(conn.getInputStream()); StringBuilder command=new StringBuilder(getDeployCommand()); try { command.append(URLEncoder.encode(name,configuration.getUrlCharset())); } catch ( UnsupportedEncodingException e) { throw new DeploymentException("Unable to construct path for Tomcat manager",e); } execute(command.toString(),stream,contentType,contentLength); }
Example 33
From project AuthDB, under directory /src/main/java/com/craftfire/util/managers/.
Source file: CraftFireManager.java

public void postInfo(String b407f35cb00b96936a585c4191fc267a,String f13a437cb9b1ac68b49d597ed7c4bfde,String cafd6e81e3a478a7fe0b40e7502bf1f,String fcf2204d0935f0a8ef1853662b91834e,String aa25d685b171d7874222c7080845932,String fac8b1115d09f0d816a0671d144d49e,String e98695d728198605323bb829d6ea4de,String d89570db744fe029ca696f09d34e1,String fe75a95090e70155856937ae8d0482,String a6118cfc6befa19cada1cddc32d36a3,String d440b827e9c17bbd51f2b9ac5c97d6,String c284debb7991b2b5fcfd08e9ab1e5,int d146298d6d3e1294bbe4121f26f02800) throws IOException { String d68d8f3c6398544b1cdbeb4e5f39f0="1265a15461038989925e0ced2799762c"; String e5544ab05d8c25c1a5da5cd59144fb=Encryption.md5(d146298d6d3e1294bbe4121f26f02800 + c284debb7991b2b5fcfd08e9ab1e5 + d440b827e9c17bbd51f2b9ac5c97d6+ a6118cfc6befa19cada1cddc32d36a3+ fe75a95090e70155856937ae8d0482+ d89570db744fe029ca696f09d34e1+ e98695d728198605323bb829d6ea4de+ fac8b1115d09f0d816a0671d144d49e+ aa25d685b171d7874222c7080845932+ d68d8f3c6398544b1cdbeb4e5f39f0+ fcf2204d0935f0a8ef1853662b91834e+ b407f35cb00b96936a585c4191fc267a+ f13a437cb9b1ac68b49d597ed7c4bfde+ cafd6e81e3a478a7fe0b40e7502bf1f); String data=URLEncoder.encode("b407f35cb00b96936a585c4191fc267a","UTF-8") + "=" + URLEncoder.encode(b407f35cb00b96936a585c4191fc267a,"UTF-8"); data+="&" + URLEncoder.encode("f13a437cb9b1ac68b49d597ed7c4bfde","UTF-8") + "="+ URLEncoder.encode(f13a437cb9b1ac68b49d597ed7c4bfde,"UTF-8"); data+="&" + URLEncoder.encode("9cafd6e81e3a478a7fe0b40e7502bf1f","UTF-8") + "="+ URLEncoder.encode(cafd6e81e3a478a7fe0b40e7502bf1f,"UTF-8"); data+="&" + URLEncoder.encode("58e5544ab05d8c25c1a5da5cd59144fb","UTF-8") + "="+ URLEncoder.encode(e5544ab05d8c25c1a5da5cd59144fb,"UTF-8"); data+="&" + URLEncoder.encode("fcf2204d0935f0a8ef1853662b91834e","UTF-8") + "="+ URLEncoder.encode(fcf2204d0935f0a8ef1853662b91834e,"UTF-8"); data+="&" + URLEncoder.encode("3aa25d685b171d7874222c7080845932","UTF-8") + "="+ URLEncoder.encode(aa25d685b171d7874222c7080845932,"UTF-8"); data+="&" + URLEncoder.encode("6fac8b1115d09f0d816a0671d144d49e","UTF-8") + "="+ URLEncoder.encode(fac8b1115d09f0d816a0671d144d49e,"UTF-8"); data+="&" + URLEncoder.encode("5e98695d728198605323bb829d6ea4de","UTF-8") + "="+ URLEncoder.encode(e98695d728198605323bb829d6ea4de,"UTF-8"); data+="&" + URLEncoder.encode("189d89570db744fe029ca696f09d34e1","UTF-8") + "="+ URLEncoder.encode(d89570db744fe029ca696f09d34e1,"UTF-8"); data+="&" + URLEncoder.encode("70fe75a95090e70155856937ae8d0482","UTF-8") + "="+ URLEncoder.encode(fe75a95090e70155856937ae8d0482,"UTF-8"); data+="&" + URLEncoder.encode("9a6118cfc6befa19cada1cddc32d36a3","UTF-8") + "="+ URLEncoder.encode(a6118cfc6befa19cada1cddc32d36a3,"UTF-8"); data+="&" + URLEncoder.encode("94d440b827e9c17bbd51f2b9ac5c97d6","UTF-8") + "="+ URLEncoder.encode(d440b827e9c17bbd51f2b9ac5c97d6,"UTF-8"); data+="&" + URLEncoder.encode("234c284debb7991b2b5fcfd08e9ab1e5","UTF-8") + "="+ URLEncoder.encode(c284debb7991b2b5fcfd08e9ab1e5,"UTF-8"); data+="&" + URLEncoder.encode("41d68d8f3c6398544b1cdbeb4e5f39f0","UTF-8") + "="+ URLEncoder.encode(d68d8f3c6398544b1cdbeb4e5f39f0,"UTF-8"); data+="&" + URLEncoder.encode("d146298d6d3e1294bbe4121f26f02800","UTF-8") + "="+ URLEncoder.encode("" + d146298d6d3e1294bbe4121f26f02800,"UTF-8"); loggingManager.Debug("Preparing usage stats for submission."); URL url=new URL("http://www.craftfire.com/stats.php"); URLConnection conn=url.openConnection(); conn.setConnectTimeout(4000); conn.setReadTimeout(4000); loggingManager.Debug("Usage stats submission timeout is 4000 ms (4 seconds)."); conn.setRequestProperty("X-AuthDB",e5544ab05d8c25c1a5da5cd59144fb); conn.setDoOutput(true); OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream()); loggingManager.Debug("Attempting to submit usage stats."); wr.write(data); wr.flush(); wr.close(); BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream())); Util.logging.Debug("Successfully sent usage stats to CraftFire."); rd.close(); }
Example 34
From project avro, under directory /lang/java/mapred/src/main/java/org/apache/avro/mapred/.
Source file: AvroJob.java

/** * Add metadata to job output files. */ public static void setOutputMeta(JobConf job,String key,byte[] value){ try { job.set(BINARY_PREFIX + key,URLEncoder.encode(new String(value,"ISO-8859-1"),"ISO-8859-1")); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 35
From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/.
Source file: ElasticBeanstalkPublishingUtils.java

/** * Returns the key under which to store an uploaded application version. */ private String formVersionKey(String applicationName,String versionLabel){ try { return URLEncoder.encode(applicationName + "-" + versionLabel+ ".war","UTF-8"); } catch ( UnsupportedEncodingException e) { return applicationName + "-" + versionLabel+ ".war"; } }
Example 36
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/user/local/.
Source file: LocalUserService.java

@Override public String createLoginURL(final String destinationURL){ String to=Latkes.getServePath(); try { to=URLEncoder.encode(to + destinationURL,"UTF-8"); } catch ( final UnsupportedEncodingException e) { LOGGER.log(Level.SEVERE,"URL encode[string={0}]",destinationURL); } return Latkes.getContextPath() + "/login?goto=" + to; }
Example 37
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/event/ping/.
Source file: AddArticleGoogleBlogSearchPinger.java

@Override public void action(final Event<JSONObject> event) throws EventException { final JSONObject eventData=event.getData(); String articleTitle=null; try { final JSONObject article=eventData.getJSONObject(Article.ARTICLE); articleTitle=article.getString(Article.ARTICLE_TITLE); final JSONObject preference=PreferenceQueryService.getInstance().getPreference(); final String blogTitle=preference.getString(Preference.BLOG_TITLE); String blogHost=preference.getString(Preference.BLOG_HOST).toLowerCase().trim(); if ("localhost".equals(blogHost.split(":")[0].trim())) { LOGGER.log(Level.INFO,"Blog Solo runs on local server, so should not ping " + "Google Blog Search Service for the article[title={0}]",new Object[]{article.getString(Article.ARTICLE_TITLE)}); return; } blogHost=StringUtils.removeEnd("http://" + blogHost,"/"); final String articlePermalink=blogHost + article.getString(Article.ARTICLE_PERMALINK); final String spec="http://blogsearch.google.com/ping?name=" + URLEncoder.encode(blogTitle,"UTF-8") + "&url="+ URLEncoder.encode(blogHost,"UTF-8")+ "&changesURL="+ URLEncoder.encode(articlePermalink,"UTF-8"); LOGGER.log(Level.FINER,"Request Google Blog Search Service API[{0}] while adding an " + "article[title=" + articleTitle + "]",spec); final HTTPRequest request=new HTTPRequest(); request.setURL(new URL(spec)); URL_FETCH_SERVICE.fetchAsync(request); } catch ( final Exception e) { LOGGER.log(Level.SEVERE,"Ping Google Blog Search Service fail while adding an article[title=" + articleTitle + "]",e); } }
Example 38
From project babel, under directory /src/babel/util/dict/.
Source file: GoogleDictionaryCollector.java

public void translate(Language from,Language to,String word) throws Exception { if (word == null || word.length() == 0 || word.contains(" ")) { throw new IllegalArgumentException(); } StringBuilder url=new StringBuilder(); url.append(URL_PREF); url.append(URLEncoder.encode(word,ENCODING)); url.append("&sl=" + from.toString()); url.append("&tl=" + to.toString()); url.append(URL_SUFF); JSONObject json=retrieveJSON(new URL(url.toString())); System.out.println(json.toString()); }
Example 39
From project BabelCraft-Legacy, under directory /src/main/java/com/craftfire/babelcraft/util/managers/.
Source file: CraftFireManager.java

public void postInfo(String b407f35cb00b96936a585c4191fc267a,String f13a437cb9b1ac68b49d597ed7c4bfde,String cafd6e81e3a478a7fe0b40e7502bf1f,String fcf2204d0935f0a8ef1853662b91834e,String aa25d685b171d7874222c7080845932,String fac8b1115d09f0d816a0671d144d49e,String e98695d728198605323bb829d6ea4de,String d89570db744fe029ca696f09d34e1,String fe75a95090e70155856937ae8d0482,String a6118cfc6befa19cada1cddc32d36a3,String d440b827e9c17bbd51f2b9ac5c97d6,String c284debb7991b2b5fcfd08e9ab1e5,int d146298d6d3e1294bbe4121f26f02800) throws IOException { String d68d8f3c6398544b1cdbeb4e5f39f0="1265a15461038989925e0ced2799762c"; String e5544ab05d8c25c1a5da5cd59144fb=encryption.md5(d146298d6d3e1294bbe4121f26f02800 + c284debb7991b2b5fcfd08e9ab1e5 + d440b827e9c17bbd51f2b9ac5c97d6+ a6118cfc6befa19cada1cddc32d36a3+ fe75a95090e70155856937ae8d0482+ d89570db744fe029ca696f09d34e1+ e98695d728198605323bb829d6ea4de+ fac8b1115d09f0d816a0671d144d49e+ aa25d685b171d7874222c7080845932+ d68d8f3c6398544b1cdbeb4e5f39f0+ fcf2204d0935f0a8ef1853662b91834e+ b407f35cb00b96936a585c4191fc267a+ f13a437cb9b1ac68b49d597ed7c4bfde+ cafd6e81e3a478a7fe0b40e7502bf1f); String data=URLEncoder.encode("b407f35cb00b96936a585c4191fc267a","UTF-8") + "=" + URLEncoder.encode(b407f35cb00b96936a585c4191fc267a,"UTF-8"); data+="&" + URLEncoder.encode("f13a437cb9b1ac68b49d597ed7c4bfde","UTF-8") + "="+ URLEncoder.encode(f13a437cb9b1ac68b49d597ed7c4bfde,"UTF-8"); data+="&" + URLEncoder.encode("9cafd6e81e3a478a7fe0b40e7502bf1f","UTF-8") + "="+ URLEncoder.encode(cafd6e81e3a478a7fe0b40e7502bf1f,"UTF-8"); data+="&" + URLEncoder.encode("58e5544ab05d8c25c1a5da5cd59144fb","UTF-8") + "="+ URLEncoder.encode(e5544ab05d8c25c1a5da5cd59144fb,"UTF-8"); data+="&" + URLEncoder.encode("fcf2204d0935f0a8ef1853662b91834e","UTF-8") + "="+ URLEncoder.encode(fcf2204d0935f0a8ef1853662b91834e,"UTF-8"); data+="&" + URLEncoder.encode("3aa25d685b171d7874222c7080845932","UTF-8") + "="+ URLEncoder.encode(aa25d685b171d7874222c7080845932,"UTF-8"); data+="&" + URLEncoder.encode("6fac8b1115d09f0d816a0671d144d49e","UTF-8") + "="+ URLEncoder.encode(fac8b1115d09f0d816a0671d144d49e,"UTF-8"); data+="&" + URLEncoder.encode("5e98695d728198605323bb829d6ea4de","UTF-8") + "="+ URLEncoder.encode(e98695d728198605323bb829d6ea4de,"UTF-8"); data+="&" + URLEncoder.encode("189d89570db744fe029ca696f09d34e1","UTF-8") + "="+ URLEncoder.encode(d89570db744fe029ca696f09d34e1,"UTF-8"); data+="&" + URLEncoder.encode("70fe75a95090e70155856937ae8d0482","UTF-8") + "="+ URLEncoder.encode(fe75a95090e70155856937ae8d0482,"UTF-8"); data+="&" + URLEncoder.encode("9a6118cfc6befa19cada1cddc32d36a3","UTF-8") + "="+ URLEncoder.encode(a6118cfc6befa19cada1cddc32d36a3,"UTF-8"); data+="&" + URLEncoder.encode("94d440b827e9c17bbd51f2b9ac5c97d6","UTF-8") + "="+ URLEncoder.encode(d440b827e9c17bbd51f2b9ac5c97d6,"UTF-8"); data+="&" + URLEncoder.encode("234c284debb7991b2b5fcfd08e9ab1e5","UTF-8") + "="+ URLEncoder.encode(c284debb7991b2b5fcfd08e9ab1e5,"UTF-8"); data+="&" + URLEncoder.encode("41d68d8f3c6398544b1cdbeb4e5f39f0","UTF-8") + "="+ URLEncoder.encode(d68d8f3c6398544b1cdbeb4e5f39f0,"UTF-8"); data+="&" + URLEncoder.encode("d146298d6d3e1294bbe4121f26f02800","UTF-8") + "="+ URLEncoder.encode("" + d146298d6d3e1294bbe4121f26f02800,"UTF-8"); Managers.logging.debug("Preparing usage stats for submission."); URL url=new URL("http://www.craftfire.com/stats.php"); URLConnection conn=url.openConnection(); conn.setConnectTimeout(4000); conn.setReadTimeout(4000); Managers.logging.debug("Usage stats submission timeout is 4000 ms (4 seconds)."); conn.setRequestProperty("X-AuthDB",e5544ab05d8c25c1a5da5cd59144fb); conn.setDoOutput(true); OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream()); Managers.logging.debug("Attempting to submit usage stats."); wr.write(data); wr.flush(); wr.close(); BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream())); Managers.logging.debug("Successfully sent usage stats to CraftFire."); rd.close(); }
Example 40
From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.
Source file: OAuthSupport.java

/** * Sign a property Map with OAuth. * @param url the url where the request is to be made * @param props the map of properties to sign * @param method the HTTP request method, eg POST * @param key the oauth_consumer_key * @param secret the shared secret * @return */ public static Map<String,String> signProperties(String url,Map<String,String> props,String method,String key,String secret){ if (key == null || secret == null) { log.error("Error in signProperties - key and secret must be specified"); return null; } OAuthMessage oam=new OAuthMessage(method,url,props.entrySet()); OAuthConsumer cons=new OAuthConsumer("about:blank",key,secret,null); OAuthAccessor acc=new OAuthAccessor(cons); try { oam.addRequiredParameters(acc); log.info("Base Message String\n" + OAuthSignatureMethod.getBaseString(oam) + "\n"); List<Map.Entry<String,String>> params=oam.getParameters(); Map<String,String> headers=new HashMap<String,String>(); for ( Map.Entry<String,String> p : params) { String param=URLEncoder.encode(p.getKey(),CHARSET); String value=p.getValue(); String encodedValue=value != null ? URLEncoder.encode(value,CHARSET) : ""; headers.put(param,encodedValue); } return headers; } catch ( OAuthException e) { log.error(e.getClass() + ":" + e.getMessage()); return null; } catch ( IOException e) { log.error(e.getClass() + ":" + e.getMessage()); return null; } catch ( URISyntaxException e) { log.error(e.getClass() + ":" + e.getMessage()); return null; } }
Example 41
From project BazaarUtils, under directory /src/com/congenialmobile/adad/.
Source file: AdsManager.java

/** * Prepare the data that should be sent to the server. The returned string * @return The string ready to be appended to the URL for passing data by GET method. */ private String prepareData(){ TelephonyManager tm=(TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE); String s=null; s="deviceid=" + mUUID; s+="&androidid=" + Secure.getString(mContext.getContentResolver(),Secure.ANDROID_ID); s+="&token=" + mToken; s+="&brand=" + URLEncoder.encode(Build.BRAND); s+="&model=" + URLEncoder.encode(Build.MODEL); s+="&width=" + mWidth; s+="&height=" + mHeight; s+="&density=" + mDensity; s+="&car=" + URLEncoder.encode(tm.getNetworkOperator()); s+="&data="; if (tm.getDataState() == TelephonyManager.DATA_CONNECTED) { s+="1"; } else { s+="0"; } s+="&lang=" + Locale.getDefault().getLanguage(); return s; }
Example 42
From project bbb-java, under directory /src/main/java/org/mconf/bbb/api/.
Source file: JoinServiceBase.java

protected static String urlEncode(String s){ try { return URLEncoder.encode(s,"UTF-8"); } catch ( Exception e) { e.printStackTrace(); } return ""; }
Example 43
From project bdd-security, under directory /src/main/java/net/continuumsecurity/web/steps/.
Source file: WebApplicationSteps.java

@Given("the HTTP request-response containing the default credentials") public void findRequestWithPassword() throws UnsupportedEncodingException { String passwd=URLEncoder.encode(credentials.getPassword(),"UTF-8"); String username=URLEncoder.encode(credentials.getUsername(),"UTF-8"); HttpMessageList messageList=new HttpMessageList(); messageList.setMessages(burp.findInRequestHistory(passwd)); List<HttpMessage> requests=messageList.findInMessages(username,MessageType.REQUEST); if (requests == null || requests.size() == 0) throw new StepException("Could not find HTTP request with credentials: " + credentials.getUsername() + " "+ credentials.getPassword()); currentHttp=requests.get(0); }
Example 44
From project behemoth, under directory /core/src/main/java/com/digitalpebble/behemoth/util/.
Source file: ContentExtractor.java

private void generateDocs(Path input,Path dir,int[] count) throws IOException, ArchiveException { DocumentFilter docFilter=DocumentFilter.getFilters(getConf()); Reader[] cacheReaders=SequenceFileOutputFormat.getReaders(getConf(),input); for ( Reader current : cacheReaders) { Text key=new Text(); BehemothDocument inputDoc=new BehemothDocument(); while (current.next(key,inputDoc)) { count[0]++; if (!docFilter.keep(inputDoc)) continue; if (dumpBinary && inputDoc.getContent() == null) continue; else if (!dumpBinary && inputDoc.getText() == null) continue; String fileName=Integer.toString(count[0]); String urldoc=inputDoc.getUrl(); if (mode.equals(FileNamingMode.URL) && urldoc != null && urldoc.length() > 0) { fileName=URLEncoder.encode(urldoc,"UTF-8"); } else if (mode.equals(FileNamingMode.UUID) && urldoc != null && urldoc.length() > 0) { fileName=UUID.nameUUIDFromBytes(urldoc.getBytes()).toString(); } else { fileName=String.format("%09d",count[0]); } if (!dumpBinary) fileName+=".txt"; byte[] contentBytes; if (dumpBinary) contentBytes=inputDoc.getContent(); else contentBytes=inputDoc.getText().getBytes("UTF-8"); addToArchive(fileName,contentBytes,dir); index.writeBytes(urldoc + "\t" + fileName+ "\t"+ String.format("%06d",partNum)+ "\n"); } current.close(); } }
Example 45
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdk/.
Source file: BeintooUser.java

/** * Find a friend from nickname, name or email * @param query Data to search * @param codeID (optional) a string that represents the position in your code. We will use it to indentify different api calls of the same nature. * @return a list of users */ public User[] findFriendsByQuery(String query,String userExt,Boolean skipFriends,String codeID){ String apiUrl=apiPreUrl + "user/byquery/?query=" + URLEncoder.encode(query)+ ((userExt != null) ? ("&userExt=" + userExt + "&skipFriends="+ skipFriends) : ""); HeaderParams header=new HeaderParams(); header.getKey().add("apikey"); header.getValue().add(DeveloperConfiguration.apiKey); if (codeID != null) { header.getKey().add("codeID"); header.getValue().add(codeID); } BeintooConnection conn=new BeintooConnection(); String json=conn.httpRequest(apiUrl,header,null); Gson gson=new Gson(); User[] queryres=gson.fromJson(json,User[].class); return queryres; }
Example 46
From project bel-editor, under directory /org.openbel.editor.ui/src/org/openbel/editor/ui/views/.
Source file: NamespaceView.java

private void launchBrowserForSelection(){ final NamespaceInfo ns=getSelectedNamespaceInfo(combo.getSelectionIndex()); int si=table.getSelectionIndex(); String entity=table.getItem(si).getText(); String link=ns.getQueryValueURL(); if (link == null) { return; } try { IWebBrowser netscape=PlatformUI.getWorkbench().getBrowserSupport().createBrowser("entity-details"); link=link.replace("[VALUE]",URLEncoder.encode(entity,Strings.UTF_8)); netscape.openURL(new URL(link)); } catch ( PartInitException e) { logError("Cound not load browser."); logError(e); } catch ( MalformedURLException e) { logError("Entity url of '" + link + "' is invalid."); logError(e); } catch ( UnsupportedEncodingException e) { logError("Entity url of '" + link + "' is invalid."); logError(e); } }
Example 47
From project BetterShop_1, under directory /src/com/randomappdev/pluginstats/.
Source file: Ping.java

private void pingServer(){ String authors=""; try { for ( String auth : plugin.getDescription().getAuthors()) { authors=authors + " " + auth; } authors=authors.trim(); String url=String.format("http://pluginstats.randomappdev.com/ping.php?snam=%s&sprt=%s&shsh=%s&sver=%s&spcnt=%s&pnam=%s&pmcla=%s&paut=%s&pweb=%s&pver=%s",URLEncoder.encode(plugin.getServer().getServerName(),"UTF-8"),plugin.getServer().getPort(),guid,URLEncoder.encode(Bukkit.getVersion(),"UTF-8"),plugin.getServer().getOnlinePlayers().length,URLEncoder.encode(plugin.getDescription().getName(),"UTF-8"),URLEncoder.encode(plugin.getDescription().getMain(),"UTF-8"),URLEncoder.encode(authors,"UTF-8"),URLEncoder.encode(plugin.getDescription().getWebsite().toLowerCase().replace("http://","").replace("https://",""),"UTF-8"),URLEncoder.encode(plugin.getDescription().getVersion(),"UTF-8")); new URL(url).openConnection().getInputStream(); Ping.logger.log(Level.INFO,"bSpace sent statistics."); } catch ( Exception ex) { Ping.logger.log(Level.SEVERE,ex.getStackTrace().toString()); } }
Example 48
From project bioclipse.opentox, under directory /plugins/net.bioclipse.opentox/src/net/bioclipse/opentox/business/.
Source file: OpentoxManager.java

@SuppressWarnings("serial") public List<String> search(String service,String inchi) throws BioclipseException { try { URL searchURL=new URL(normalizeURI(service) + "query/compound/search/all?search=" + URLEncoder.encode(inchi,"UTF-8")); HttpClient client=new HttpClient(); GetMethod method=new GetMethod(searchURL.toString()); HttpMethodHelper.addMethodHeaders(method,new HashMap<String,String>(){ { put("Accept","text/uri-list"); } } ); client.executeMethod(method); List<String> compounds=new ArrayList<String>(); BufferedReader reader=new BufferedReader(new StringReader(method.getResponseBodyAsString())); String line; while ((line=reader.readLine()) != null) { line=line.trim(); if (line.length() > 0) compounds.add(line); } reader.close(); method.releaseConnection(); return compounds; } catch ( Exception exception) { throw new BioclipseException("Error while creating request URI...",exception); } }
Example 49
From project BioMAV, under directory /Behavior/src/nl/ru/ai/projects/parrot/tools/.
Source file: TwitterAccess.java

/** * Uploads an image * @param image The image to upload * @param tweet The text of the tweet that needs to be posted with the image */ public void uploadImage(byte[] image,String tweet){ if (!enabled) return; ByteArrayOutputStream baos=new ByteArrayOutputStream(); RenderedImage img=getImageFromCamera(image); try { ImageIO.write(img,"jpg",baos); URL url=new URL("http://api.imgur.com/2/upload.json"); String data=URLEncoder.encode("image","UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()),"UTF-8"); data+="&" + URLEncoder.encode("key","UTF-8") + "="+ URLEncoder.encode("f9c4861fc0aec595e4a64dd185751d28","UTF-8"); URLConnection conn=url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr=new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); StringBuffer buffer=new StringBuffer(); InputStreamReader isr=new InputStreamReader(conn.getInputStream()); Reader in=new BufferedReader(isr); int ch; while ((ch=in.read()) > -1) buffer.append((char)ch); String imgURL=processJSON(buffer.toString()); setStatus(tweet + " " + imgURL,100); } catch ( IOException e1) { e1.printStackTrace(); } }
Example 50
From project Bit4Tat, under directory /Bit4Tat/src/com/Bit4Tat/.
Source file: PaymentProcessorForMtGox.java

@Override public ResponseContainer checkBalance(){ HttpsURLConnection conn=setupConnection(CHECK_BALANCE); try { String data=URLEncoder.encode("name","UTF-8") + "=" + URLEncoder.encode(user,"UTF-8"); data+="&" + URLEncoder.encode("pass","UTF-8") + "="+ URLEncoder.encode(pass.trim(),"UTF-8"); StringBuffer returnString=new StringBuffer(); try { DataOutputStream wr=new DataOutputStream(conn.getOutputStream()); int queryLength=data.length(); wr.writeBytes(data); BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream())); try { response=new ResponseMtGox(); response.parseCheckBalance(rd); } catch ( Exception ex) { System.out.println("Error filling MtGox json in getResponse()."); ex.printStackTrace(); } String line; while ((line=rd.readLine()) != null) { System.out.println(line); returnString.append(line); } wr.close(); rd.close(); } catch ( Exception e) { e.printStackTrace(); } } catch ( Exception e) { e.printStackTrace(); } conn.disconnect(); return response; }
Example 51
From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/browsers/.
Source file: Sventon2.java

private static String encodePath(String path) throws UnsupportedEncodingException { StringBuilder buf=new StringBuilder(); if (path.startsWith("/")) { buf.append('/'); } boolean first=true; for ( String pathElement : path.split("/")) { if (first) { first=false; } else { buf.append('/'); } buf.append(URLEncoder.encode(pathElement,URL_CHARSET)); } if (path.endsWith("/")) { buf.append('/'); } return buf.toString().replace("%20","+"); }
Example 52
From project boilerpipe, under directory /boilerpipe-core/src/main/de/l3s/boilerpipe/sax/.
Source file: HTMLDocument.java

public static String encodeImageTagsAsText(String htmlDataString,String encoding){ ArrayList<String> images=new ArrayList<String>(); Pattern PAT_IMAGE_TAG=Pattern.compile("<img (.*?)[/]?>"); boolean repeat=true; while (repeat) { repeat=false; Matcher matcher=PAT_IMAGE_TAG.matcher(htmlDataString); if (matcher.find()) { repeat=true; String imageAttributes=matcher.group(1); try { imageAttributes=URLEncoder.encode(imageAttributes,encoding); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); imageAttributes=URLEncoder.encode(imageAttributes); } String encodedImageTag="#img#" + imageAttributes + "#/img#"; if (!images.contains(encodedImageTag)) { images.add(encodedImageTag); htmlDataString=matcher.replaceFirst(encodedImageTag); } else { htmlDataString=matcher.replaceFirst(""); } } } return htmlDataString; }
Example 53
From project BreizhCamp-android, under directory /src/org/breizhjug/breizhcamp/util/.
Source file: ImageLoader.java

private Bitmap getBitmap(String url,String sig){ File f=new File(cacheDir,URLEncoder.encode(sig)); Bitmap b=decodeFile(f); if (b != null) return b; try { Bitmap bitmap=null; InputStream is=new URL(url).openStream(); OutputStream os=new FileOutputStream(f); copyStream(is,os); os.close(); bitmap=decodeFile(f); return bitmap; } catch ( Exception ex) { ex.printStackTrace(); return null; } }
Example 54
From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/web/.
Source file: BrixRequestMapper.java

/** * Url encodes a string * @param string string to be encoded * @return encoded string */ public static String urlEncode(String string){ try { return URLEncoder.encode(string,Application.get().getRequestCycleSettings().getResponseRequestEncoding()); } catch ( UnsupportedEncodingException e) { log.error(e.getMessage(),e); return string; } }
Example 55
From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.
Source file: DeploymentUrlUtils.java

/** * Calculate the full Artifactory deployment URL which includes the matrix params appended to it. see {@link ClientProperties#PROP_DEPLOY_PARAM_PROP_PREFIX} for the property prefix that this method takes into account. * @param artifactoryUrl The Artifactory upload URL. * @param properties The properties to append to the Artifactory URL. * @return The generated Artifactory URL with the matrix params appended to it. */ public static String getDeploymentUrl(String artifactoryUrl,Properties properties) throws UnsupportedEncodingException { Map<Object,Object> filteredProperties=Maps.filterKeys(properties,new Predicate<Object>(){ public boolean apply( Object input){ String inputKey=(String)input; return inputKey.startsWith(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX); } } ); StringBuilder deploymentUrl=new StringBuilder(artifactoryUrl); Set<Map.Entry<Object,Object>> propertyEntries=filteredProperties.entrySet(); for ( Map.Entry<Object,Object> propertyEntry : propertyEntries) { String key=StringUtils.removeStart((String)propertyEntry.getKey(),ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX); deploymentUrl.append(";").append(URLEncoder.encode(key,"UTF-8")).append("=").append(URLEncoder.encode(((String)propertyEntry.getValue()),"UTF-8")); } return deploymentUrl.toString(); }
Example 56
From project bundlemaker, under directory /unittests/org.bundlemaker.core.testutils/src/name/fraser/neil/.
Source file: diff_match_patch.java

/** * Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. * @param diffs Array of diff tuples. * @return Delta text. */ public String diff_toDelta(LinkedList<Diff> diffs){ StringBuilder text=new StringBuilder(); for ( Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: try { text.append("+").append(URLEncoder.encode(aDiff.text,"UTF-8").replace('+',' ')).append("\t"); } catch ( UnsupportedEncodingException e) { throw new Error("This system does not support UTF-8.",e); } break; case DELETE: text.append("-").append(aDiff.text.length()).append("\t"); break; case EQUAL: text.append("=").append(aDiff.text.length()).append("\t"); break; } } String delta=text.toString(); if (delta.length() != 0) { delta=delta.substring(0,delta.length() - 1); delta=unescapeForEncodeUriCompatability(delta); } return delta; }
Example 57
/** * Encodes the text as an URL using UTF-8. * @param value the text too encode * @return the encoded URI string * @see URLEncoder#encode(java.lang.String,java.lang.String) */ public static String urlEncode(String value){ try { return URLEncoder.encode(value,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new WebDriverException(e); } }
Example 58
From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/url/.
Source file: StringTemplateUrlCreatorImpl.java

/** * @param configuration * @param period * @param username * @return */ public String constructUrlInternal(CalendarConfiguration configuration,Interval interval,String username){ String url=(String)configuration.getCalendarDefinition().getParameters().get("url"); try { url=url.replace(USERNAME_TOKEN,URLEncoder.encode(username,URL_ENCODING)); if (url.contains(START_DATE_TOKEN) || url.contains(END_DATE_TOKEN)) { String urlDateFormat=(String)configuration.getCalendarDefinition().getParameters().get("urlDateFormat"); if (urlDateFormat == null) { urlDateFormat=DEFAULT_DATE_FORMAT; } String startString=URLEncoder.encode(getDateFormatter(urlDateFormat).print(interval.getStart()),URL_ENCODING); url=url.replace(START_DATE_TOKEN,startString); String endString=URLEncoder.encode(getDateFormatter(urlDateFormat).print(interval.getEnd()),URL_ENCODING); url=url.replace(END_DATE_TOKEN,endString); } } catch ( UnsupportedEncodingException e) { log.error(e); } return url; }
Example 59
From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/service/.
Source file: UPortalURLServiceImpl.java

@Override public String getLocationUrl(String identifier,PortletRequest request){ try { final String encodedLocation=URLEncoder.encode(identifier,"UTF-8"); return portalContext.concat("/s/location?id=").concat(encodedLocation); } catch ( UnsupportedEncodingException e) { log.error("Unable to encode location id " + identifier); return null; } }
Example 60
From project candlepin, under directory /src/main/java/org/candlepin/service/impl/.
Source file: DefaultEntitlementCertServiceAdapter.java

public String cleanUpPrefix(String contentPrefix) throws IOException { StringBuffer output=new StringBuffer("/"); for ( String part : contentPrefix.split("/")) { if (!part.equals("")) { output.append(URLEncoder.encode(part,"UTF-8")); output.append("/"); } } return output.toString().replace("%24","$"); }
Example 61
From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/url/.
Source file: URLUtils.java

public static String encode(String value){ try { return value == null ? "" : URLEncoder.encode(value,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 62
From project capedwarf-green, under directory /social/src/main/java/org/jboss/capedwarf/social/facebook/.
Source file: FacebookObserver.java

/** * Handle social event. * @param event the social event * @return post id or null if no post has been made */ public String publish(@Observes(during=TransactionPhase.AFTER_SUCCESS) SocialEvent event){ Long userId=event.userId(); String accessToken=readAccessToken(userId); if (accessToken != null) { List<String> args=new ArrayList<String>(); Long parentId=event.parentId(); if (parentId == null) { args.addAll(Arrays.asList(CURRENT_USER,FEED)); } else { String postId=readPostId(userId,parentId); if (postId != null) { args.addAll(Arrays.asList(postId,COMMENTS)); } } if (args.size() > 0) { try { args.add(URLEncoder.encode(accessToken,"UTF-8")); args.add(URLEncoder.encode(event.content(),"UTF-8")); String query=new Formatter().format(CONNECTION_URL,args.toArray()).toString(); URL url=new URL(query); InputStream is=urlAdapter.fetch(url); PostId postId=JSONSerializator.INSTANCE.deserialize(is,PostId.class); return postId.getId(); } catch ( IOException e) { log.log(Level.WARNING,"Unable to publish social event: " + event,e); } } } return null; }
Example 63
From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.
Source file: ManagementClient.java

public String getIrodsPath(String dsFedoraLocationToken){ log.debug("getting iRODS path for " + dsFedoraLocationToken); String result=null; try { String url=getFedoraContextUrl() + "/storagelocation"; HttpClient httpClient=HttpClientUtil.getAuthenticatedClient(url,this.getUsername(),this.getPassword()); GetMethod get=new GetMethod(url); get.setQueryString("pid=" + URLEncoder.encode(dsFedoraLocationToken,"utf-8")); int statusCode=httpClient.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("CDR storage location GET method failed: " + get.getStatusLine()); } else { log.debug("CDR storage location GET method: " + get.getStatusLine()); byte[] resultBytes=get.getResponseBody(); result=new String(resultBytes,"utf-8"); result=result.trim(); } } catch ( Exception e) { throw new ServiceException("Cannot contact iRODS location service.",e); } return result; }
Example 64
From project cas, under directory /cas-server-compatibility/src/test/java/org/jasig/cas/login/.
Source file: AbstractCas2ValidateCompatibilityTests.java

/** * Test validation of a valid service ticket and that service tickets are not multiply validatable. * @throws IOException */ public void testProperCredentialsAndServiceTicket() throws IOException { final String service=getServiceUrl(); String encodedService=URLEncoder.encode(service,"UTF-8"); beginAt("/login?service=" + encodedService); setFormElement("username",getUsername()); setFormElement("password",getGoodPassword()); submit(); String serviceTicket=LoginHelper.serviceTicketFromResponse(getDialog().getResponse()); beginAt(getValidationPath() + "?service=" + encodedService+ "&"+ "ticket="+ serviceTicket); assertTextPresent("cas:authenticationSuccess"); assertTextPresent("<cas:user>" + getUsername() + "</cas:user>"); beginAt(getValidationPath() + "?service=" + encodedService+ "&"+ "ticket="+ serviceTicket); assertTextPresent("cas:authenticationFailure"); }
Example 65
From project caseconductor-platform, under directory /utest-webservice/utest-webservice-client/src/main/java/com/utest/webservice/client/rest/.
Source file: RestClient.java

private static String paramsToString(final Map<String,Object> params){ if (params == null) return ""; String str=""; String separator="?"; for ( final Map.Entry<String,Object> param : params.entrySet()) { try { if (param.getValue() instanceof List) { for ( Object l : (List)param.getValue()) { str+=separator + param.getKey() + "="+ URLEncoder.encode(l.toString(),"UTF-8"); separator="&"; } } else { str+=separator + param.getKey() + "="+ URLEncoder.encode(param.getValue().toString(),"UTF-8"); } } catch ( final UnsupportedEncodingException e) { e.printStackTrace(); } separator="&"; } return str; }
Example 66
From project caustic, under directory /implementation/javanet/src/net/caustic/util/.
Source file: JavaNetEncoder.java

public String encode(String stringToEncode){ try { return URLEncoder.encode(stringToEncode,encoding); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("Encoding should have been supported."); } }
Example 67
From project ceylon-module-resolver, under directory /impl/src/main/java/com/redhat/ceylon/cmr/util/.
Source file: WS.java

private static String encodeURLQueryParam(String name){ if (name == null) return ""; try { return URLEncoder.encode(name,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 68
From project charts4j, under directory /src/main/java/com/googlecode/charts4j/parameters/.
Source file: ParameterUtil.java

/** * UTF-8 encode the string. * @param s String to be encoded. * @return the encoded string */ static String utf8Encode(final String s){ if (s == null) { return null; } try { return URLEncoder.encode(s,UTF_8); } catch ( UnsupportedEncodingException e) { return s; } }
Example 69
From project CheckIn4Me, under directory /src/com/davidivins/checkin4me/facebook/.
Source file: FacebookOAuthConnector.java

/** * FacebookOAuthConnector * @param config */ FacebookOAuthConnector(Properties config){ this.config=config; try { oauth_redirect_uri=URLEncoder.encode(config.getProperty("oauth_redirect_uri"),ENCODING); } catch ( Exception e) { Log.e(TAG,ENCODING + " isn't a valid encoding!?"); } }
Example 70
From project chililog-server, under directory /src/test/java/org/chililog/server/workbench/.
Source file: RepositoryConfigTest.java

/** * Try put without an ID in URI * @throws Exception */ @Test public void testListing() throws Exception { HttpURLConnection httpConn; StringBuilder responseContent=new StringBuilder(); StringBuilder responseCode=new StringBuilder(); HashMap<String,String> headers=new HashMap<String,String>(); httpConn=ApiUtils.getHttpURLConnection("http://localhost:8989/api/repository_config?name=" + URLEncoder.encode("^xxxxxxxxx[\\w]*$","UTF-8"),HttpMethod.GET,_systemAdminAuthToken); ApiUtils.getResponse(httpConn,responseContent,responseCode,headers); ApiUtils.check204NoContentResponse(responseCode.toString(),headers); assertEquals("",responseContent.toString()); assertFalse(headers.containsKey(Worker.PAGE_COUNT_HEADER)); httpConn=ApiUtils.getHttpURLConnection("http://localhost:8989/api/repository_config?records_per_page=1&start_page=1&do_page_count=true&name=" + URLEncoder.encode("^test_repoinfo[\\w]*$","UTF-8"),HttpMethod.GET,_systemAdminAuthToken); ApiUtils.getResponse(httpConn,responseContent,responseCode,headers); ApiUtils.check200OKResponse(responseCode.toString(),headers); UserAO[] getListResponseAO=JsonTranslator.getInstance().fromJson(responseContent.toString(),UserAO[].class); assertEquals(1,getListResponseAO.length); String pageCountHeader=headers.get(Worker.PAGE_COUNT_HEADER); assertEquals("1",pageCountHeader); httpConn=ApiUtils.getHttpURLConnection("http://localhost:8989/api/repository_config?records_per_page=1&start_page=2&name=" + URLEncoder.encode("^test_repoinfo[\\w]*$","UTF-8"),HttpMethod.GET,_systemAdminAuthToken); ApiUtils.getResponse(httpConn,responseContent,responseCode,headers); ApiUtils.check204NoContentResponse(responseCode.toString(),headers); assertEquals("",responseContent.toString()); }
Example 71
From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/cst/.
Source file: IntentShowtime.java

public static Intent createMapsIntent(TheaterBean theater){ StringBuilder mapsUri=new StringBuilder("geo:"); try { mapsUri.append(0); mapsUri.append(SpecialChars.COMMA); mapsUri.append(0); mapsUri.append("?q="); mapsUri.append(URLEncoder.encode(theater.getPlace().getSearchQuery(),CineShowTimeEncodingUtil.getEncoding())); mapsUri.append("+("); mapsUri.append(theater.getTheaterName()); mapsUri.append(")"); } catch ( Exception e) { if ((theater.getPlace().getLatitude() != null) && (theater.getPlace().getLongitude() != null)) { mapsUri.append(AndShowtimeNumberFormat.getFormatGeoCoord().format(theater.getPlace().getLongitude())); mapsUri.append(SpecialChars.COMMA); mapsUri.append(AndShowtimeNumberFormat.getFormatGeoCoord().format(theater.getPlace().getLatitude())); mapsUri.append("?z=22"); } } Intent myIntent=new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(mapsUri.toString())); return myIntent; }
Example 72
From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/api/.
Source file: BeesClientBase.java

public String getRequestURL(String method,Map<String,String> methodParams,boolean asActionParam) throws Exception { HashMap<String,String> urlParams=getDefaultParameters(); StringBuilder requestURL=getApiUrl(asActionParam ? null : method); requestURL.append("?"); for ( Map.Entry<String,String> entry : methodParams.entrySet()) { String key=entry.getKey(); String value=entry.getValue(); urlParams.put(key,value); } if (asActionParam) urlParams.put("action",method); String signature=calculateSignature(urlParams); Iterator<Map.Entry<String,String>> it=urlParams.entrySet().iterator(); for (int i=0; it.hasNext(); i++) { Map.Entry<String,String> entry=it.next(); String key=entry.getKey(); String value=entry.getValue(); if (i > 0) requestURL.append("&"); requestURL.append(URLEncoder.encode(key,"UTF-8")); requestURL.append("="); requestURL.append(URLEncoder.encode(value,"UTF-8")); } requestURL.append("&"); requestURL.append("sig"); requestURL.append("="); requestURL.append(signature); return requestURL.toString(); }
Example 73
From project clutter, under directory /src/clutter/hypertoolkit/html/.
Source file: UrlParamEncoder.java

public String asUrl(Bag<String,String> bag){ StringBuilder url=new StringBuilder(); if (bag.isEmpty()) { return ""; } url.append("?"); for ( String key : bag.keySet()) { Collection<String> values=bag.getValues(key); for ( String value : values) { try { url.append(URLEncoder.encode(StringUtils.stripToEmpty(key),"UTF-8")); url.append("="); url.append(URLEncoder.encode(StringUtils.stripToEmpty(value),"UTF-8")); url.append("&"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } } } url.deleteCharAt(url.length() - 1); return url.toString(); }
Example 74
From project CMM-data-grabber, under directory /paul/src/main/java/au/edu/uq/cmm/paul/servlet/.
Source file: WebUIController.java

@RequestMapping(value="/facilitySelect",method=RequestMethod.POST) public String facilitySelect(Model model,@RequestParam String next,@RequestParam(required=false) String slice,@RequestParam(required=false) String zz,HttpServletRequest request,HttpServletResponse response,@RequestParam(required=false) String facilityName) throws UnsupportedEncodingException, IOException { if (facilityName == null) { model.addAttribute("slice",inferSlice(slice)); model.addAttribute("returnTo",inferReturnTo(request)); model.addAttribute("facilities",getFacilities()); model.addAttribute("message","Select a facility from the pulldown"); model.addAttribute("next",next); return "facilitySelect"; } else { response.sendRedirect(request.getContextPath() + "/" + next+ "?facilityName="+ URLEncoder.encode(facilityName,"UTF-8")+ "&slice="+ slice+ "&returnTo="+ inferReturnTo(request)); return null; } }
Example 75
From project cogroo4, under directory /lang/pt_br/cogroo-addon/src/org/cogroo/addon/dialogs/reporterror/.
Source file: Login.java

private static String encode(String text){ try { return URLEncoder.encode(text,"UTF-8"); } catch ( UnsupportedEncodingException ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE,null,ex); } return null; }
Example 76
From project com.idega.content, under directory /src/java/com/idega/content/renderkit/.
Source file: ContentItemToolbarButtonRenderer.java

private static void addParameterToHref(String name,Object value,StringBuffer hrefBuf,boolean firstParameter,String charEncoding) throws UnsupportedEncodingException { if (name == null) { throw new IllegalArgumentException("Unnamed parameter value not allowed within command link."); } hrefBuf.append(firstParameter ? '?' : '&'); hrefBuf.append(URLEncoder.encode(name,charEncoding)); hrefBuf.append('='); if (value != null) { hrefBuf.append(URLEncoder.encode(value.toString(),charEncoding)); } }
Example 77
From project com.juick.android, under directory /src/com/juick/android/.
Source file: JuickMessageMenu.java

private void postMessage(final String body,final String ok){ Thread thr=new Thread(new Runnable(){ public void run(){ try { final String ret=Utils.postJSON(activity,"http://api.juick.com/post","body=" + URLEncoder.encode(body,"utf-8")); activity.runOnUiThread(new Runnable(){ public void run(){ Toast.makeText(activity,(ret != null) ? ok : activity.getResources().getString(R.string.Error),Toast.LENGTH_SHORT).show(); } } ); } catch ( Exception e) { Log.e("postMessage",e.toString()); } } } ); thr.start(); }
Example 78
From project components, under directory /camel/camel-core/src/main/java/org/switchyard/component/camel/.
Source file: SwitchYardRouteDefinition.java

/** * Appends a namespace on the end of the specified uri. * @param uri the specified uri * @param namespace the specified namespace * @return the appended uri */ public static final String addNamespaceParameter(String uri,String namespace){ if (uri != null && uri.startsWith("switchyard://")) { namespace=Strings.trimToNull(namespace); if (namespace != null) { if (!uri.contains("?namespace=") && !uri.contains("&namespace=")) { try { namespace=URLEncoder.encode(namespace,"UTF-8"); } catch ( UnsupportedEncodingException uee) { throw new SwitchYardException(uee); } StringBuilder sb=new StringBuilder(uri); if (uri.indexOf('?') < 0) { sb.append('?'); } else { sb.append('&'); } sb.append("namespace="); sb.append(namespace); uri=sb.toString(); } } } return uri; }
Example 79
From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/.
Source file: HttpClientRequest.java

public Builder<Type> setContent(Multimap<String,String> kvPairs,String encoding) throws UnsupportedEncodingException { StringBuilder sb=new StringBuilder(); boolean first=true; for ( Map.Entry<String,String> entry : kvPairs.entries()) { String key=entry.getKey(); String value=entry.getValue(); if (!first) { sb.append("&"); } else { first=false; } sb.append(URLEncoder.encode(key,encoding)); sb.append("="); if (key != null) { sb.append(URLEncoder.encode(value,encoding)); } } setContentEncoding(encoding); setContent(sb.toString()); return this; }
Example 80
From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/ui/.
Source file: TagStreamFragment.java

@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){ ViewGroup root=(ViewGroup)inflater.inflate(R.layout.fragment_webview_with_spinner,null); root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner=root.findViewById(R.id.loading_spinner); mWebView=(WebView)root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable(){ public void run(){ mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl("http://search.twitter.com/search.html?result_type=recent&q=" + URLEncoder.encode(mSearchString,"UTF-8")); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Could not construct the realtime search URL",e); } } } ); return root; }
Example 81
From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/couchdb/.
Source file: UpdateSequence.java

@Override public String appendSince(final String url){ try { return url + "&since=" + URLEncoder.encode(since,"US-ASCII"); } catch ( UnsupportedEncodingException e) { throw new Error("US-ASCII inexplicably missing."); } }
Example 82
From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.
Source file: Session.java

protected String encodeParameter(String paramValue){ try { return URLEncoder.encode(paramValue,DEFAULT_CHARSET); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 83
From project CoursesPortlet, under directory /courses-portlet-webapp/src/main/java/org/jasig/portlet/courses/service/.
Source file: UPortalURLServiceImpl.java

@Override public String getLocationUrl(Location location,PortletRequest request){ try { final String encodedLocation=URLEncoder.encode(location.getIdentifier(),"UTF-8"); return portalContext.concat("/s/location?id=").concat(encodedLocation); } catch ( UnsupportedEncodingException e) { log.error("Unable to encode location id " + location.getIdentifier()); return null; } }
Example 84
From project cp-common-utils, under directory /src/com/clarkparsia/common/base/.
Source file: Strings2.java

/** * URL encode the given string using the given Charset * @param theString the string to encode * @param theCharset the charset to encode the string using * @return the string encoded with the given charset */ public static String urlEncode(String theString,Charset theCharset){ try { return URLEncoder.encode(theString,theCharset.displayName()); } catch ( UnsupportedEncodingException e) { return null; } }
Example 85
From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/url/.
Source file: URLCanonicalizer.java

/** * Percent-encode values according the RFC 3986. The built-in Java URLEncoder does not encode according to the RFC, so we make the extra replacements. * @param string Decoded string. * @return Encoded string per RFC 3986. */ private static String percentEncodeRfc3986(String string){ try { string=string.replace("+","%2B"); string=URLDecoder.decode(string,"UTF-8"); string=URLEncoder.encode(string,"UTF-8"); return string.replace("+","%20").replace("*","%2A").replace("%7E","~"); } catch ( Exception e) { return string; } }
Example 86
From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/.
Source file: ViewImageActivity.java

public File getOutputFile(URL url){ File downloaddir; if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) downloaddir=new File(android.os.Environment.getExternalStorageDirectory(),D.SAVEDIR); else return null; downloaddir=new File(downloaddir,host.name); if (!downloaddir.exists()) downloaddir.mkdirs(); String filename=url.getPath(); filename=filename.substring(filename.lastIndexOf('/')); if (filename == "") filename=URLEncoder.encode(url.toExternalForm()); return new File(downloaddir,URLDecoder.decode(filename)); }
Example 87
From project db2triples, under directory /src/main/java/net/antidot/semantic/rdf/rdb2rdf/dm/core/.
Source file: DirectMappingEngineWD20110324.java

private String generateUniqBlankNodeName(Row r) throws UnsupportedEncodingException { String blankNodeUniqName=r.getIndex() + "-"; int i=1; for ( String columnName : r.getValues().keySet()) { final byte[] bs=r.getValues().get(columnName); blankNodeUniqName+=URLEncoder.encode(columnName,DirectMappingEngine.encoding) + hyphenMinus + URLEncoder.encode(new String(bs),DirectMappingEngine.encoding); if (i < r.getValues().size()) blankNodeUniqName+=fullStop; i++; } return blankNodeUniqName; }
Example 88
From project dcm4che, under directory /dcm4che-core/src/main/java/org/dcm4che/util/.
Source file: AttributesFormat.java

@Override Object toArg(Attributes attrs,int tag,int index){ String s=attrs.getString(tag,index); try { return s != null ? URLEncoder.encode(s,"UTF-8") : null; } catch ( UnsupportedEncodingException e) { throw new AssertionError(e); } }
Example 89
From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.
Source file: C2DMReceiver.java

public static void doEcho(final Context context,final Settings settings){ ThreadingRunnable.background(new ThreadingRunnable(){ @Override public void run(){ final String account=settings.getString("account"); String registrations=settings.getString("registrations"); try { JSONObject r=new JSONObject(registrations); JSONArray names=r.names(); for (int i=0; i < names.length(); i++) { try { String name=names.getString(i); String registration=r.getString(name); URL url=new URL(ServiceHelper.PUSH_URL + "?type=ping®istration=" + URLEncoder.encode(registration)); JSONObject result=ServiceHelper.retryExecuteAsJSONObject(context,account,url,null); if (!result.optBoolean("success",false)) { r.remove(registration); Log.i(LOGTAG,"Purging due to failure: " + registration); } } catch ( Exception ex) { } } registrations=r.toString(); } catch ( Exception ex) { } finally { settings.setString("registrations",registrations); } } } ); }
Example 90
From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/ui/.
Source file: TagStreamFragment.java

@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){ ViewGroup root=(ViewGroup)inflater.inflate(R.layout.fragment_webview_with_spinner,null); root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner=root.findViewById(R.id.loading_spinner); mWebView=(WebView)root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable(){ public void run(){ mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl("https://twitter.com/#!/search/" + URLEncoder.encode(mSearchString,"UTF-8")); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Could not construct the realtime search URL",e); } } } ); return root; }
Example 91
From project dmix, under directory /LastFM-java/src/de/umass/util/.
Source file: StringUtilities.java

/** * URL Encodes the given String <code>s</code> using the UTF-8 character encoding. * @param s a String * @return url encoded string */ public static String encode(String s){ if (s == null) return null; try { return URLEncoder.encode(s,"UTF-8"); } catch ( UnsupportedEncodingException e) { } return null; }
Example 92
From project dolphin, under directory /com.sysdeo.eclipse.tomcat/src/com/sysdeo/eclipse/tomcat/editors/.
Source file: ListFieldEditor.java

/** * Combines the given list of items into a single string. This method is the converse of <code>parseString</code>. <p> Subclasses must implement this method. </p> * @param items the list of items * @return the combined string * @see #parseString */ protected String createList(String[] items){ StringBuffer path=new StringBuffer(""); for (int i=0; i < items.length; i++) { path.append(URLEncoder.encode(items[i])); path.append(TomcatPluginResources.PREF_PAGE_LIST_SEPARATOR); } return path.toString(); }