Java Code Examples for java.io.UnsupportedEncodingException
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 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpPoster.java

public HttpPoster(URI uri,List<? extends NameValuePair> values){ httppost=new HttpPost(uri); try { httppost.setEntity(new UrlEncodedFormEntity(values,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Error: Unsupported encoding exception on " + httppost.getURI()); } }
Example 2
From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/helper/.
Source file: EncodeHelper.java

public static String encodeURIComponent(String input){ if (Strings.isEmpty(input)) { return input; } int l=input.length(); StringBuilder o=new StringBuilder(l * 3); try { for (int i=0; i < l; i++) { String e=input.substring(i,i + 1); if (ALLOWED_CHARS.indexOf(e) == -1) { byte[] b=e.getBytes("utf-8"); o.append(getHex(b)); continue; } o.append(e); } return o.toString(); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } return input; }
Example 3
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 4
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.
Source file: Utils.java

public static Hashtable<String,Object> parseQueryString(String query,String encoding){ Hashtable<String,Object> result=new Hashtable<String,Object>(); if (encoding == null) encoding="UTF-8"; StringTokenizer st=new StringTokenizer(query,"&"); while (st.hasMoreTokens()) { String pair=st.nextToken(); int ep=pair.indexOf('='); String key=ep > 0 ? pair.substring(0,ep) : pair; String value=ep > 0 ? pair.substring(ep + 1) : ""; try { key=decode(key,encoding); if (value != null) value=decode(value,encoding); } catch ( UnsupportedEncodingException uee) { } String[] values=(String[])result.get(key); String[] newValues; if (values == null) { newValues=new String[1]; newValues[0]=value; } else { newValues=new String[values.length + 1]; System.arraycopy(values,0,newValues,0,values.length); newValues[values.length]=value; } result.put(key,newValues); } return result; }
Example 5
From project accesointeligente, under directory /src/org/accesointeligente/server/.
Source file: BCrypt.java

/** * Hash a password using the OpenBSD bcrypt scheme * @param password the password to hash * @param salt the salt to hash with (perhaps generatedusing BCrypt.gensalt) * @return the hashed password */ public static String hashpw(String password,String salt){ BCrypt B; String real_salt; byte passwordb[], saltb[], hashed[]; char minor=(char)0; int rounds, off=0; StringBuffer rs=new StringBuffer(); if (salt.charAt(0) != '$' || salt.charAt(1) != '2') throw new IllegalArgumentException("Invalid salt version"); if (salt.charAt(2) == '$') off=3; else { minor=salt.charAt(2); if (minor != 'a' || salt.charAt(3) != '$') throw new IllegalArgumentException("Invalid salt revision"); off=4; } if (salt.charAt(off + 2) > '$') throw new IllegalArgumentException("Missing salt rounds"); rounds=Integer.parseInt(salt.substring(off,off + 2)); real_salt=salt.substring(off + 3,off + 25); try { passwordb=(password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); } catch ( UnsupportedEncodingException uee) { throw new AssertionError("UTF-8 is not supported"); } saltb=decode_base64(real_salt,BCRYPT_SALT_LEN); B=new BCrypt(); hashed=B.crypt_raw(passwordb,saltb,rounds); rs.append("$2"); if (minor >= 'a') rs.append(minor); rs.append("$"); if (rounds < 10) rs.append("0"); rs.append(Integer.toString(rounds)); rs.append("$"); rs.append(encode_base64(saltb,saltb.length)); rs.append(encode_base64(hashed,bf_crypt_ciphertext.length * 4 - 1)); return rs.toString(); }
Example 6
From project aether-core, under directory /aether-api/src/main/java/org/eclipse/aether/repository/.
Source file: AuthenticationDigest.java

/** * Updates the digest with the specified strings. * @param strings The strings to update the digest with, may be {@code null} or contain {@code null} elements. */ public void update(String... strings){ if (strings != null) { for ( String string : strings) { if (string != null) { try { digest.update(string.getBytes("UTF-8")); } catch ( UnsupportedEncodingException e) { throw new IllegalStateException(e); } } } } }
Example 7
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: ViewTools.java

public String escapeForURL(String string){ String encoded=string; try { encoded=string.replaceAll("\\s","gtpb_special_variable_space"); encoded=encoded.replaceAll("\\n","gtpb_special_variable_newline"); if (encoded.contains("/")) { String filename=encoded.replaceAll("^.*\\/",""); String path=encoded.substring(0,encoded.length() - filename.length()); encoded=path + java.net.URLEncoder.encode(filename,"UTF-8"); } else { encoded=java.net.URLEncoder.encode(encoded,"UTF-8"); } encoded=encoded.replace("gtpb_special_variable_space","%20"); encoded=encoded.replace("gtpb_special_variable_newline","\n"); } catch ( UnsupportedEncodingException ueex) { logger.error("Error URL encoding string '" + string + "': "+ ueex); } return encoded; }
Example 8
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 9
From project ACLS-protocol-library, under directory /aclslib/src/test/java/au/edu/uq/cmm/aclslib/message/.
Source file: RequestReaderTest.java

private InputStream source(String text){ try { return new ByteArrayInputStream(text.getBytes("UTF-8")); } catch ( UnsupportedEncodingException ex) { throw new AssertionError("UTF-8??"); } }
Example 10
From project activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.
Source file: URISupport.java

public static Map<String,String> parseQuery(String uri) throws URISyntaxException { try { Map<String,String> rc=new HashMap<String,String>(); if (uri != null) { String[] parameters=uri.split("&"); for (int i=0; i < parameters.length; i++) { int p=parameters[i].indexOf("="); if (p >= 0) { String name=URLDecoder.decode(parameters[i].substring(0,p),"UTF-8"); String value=URLDecoder.decode(parameters[i].substring(p + 1),"UTF-8"); rc.put(name,value); } else { rc.put(parameters[i],null); } } } return rc; } catch ( UnsupportedEncodingException e) { throw (URISyntaxException)new URISyntaxException(e.toString(),"Invalid encoding").initCause(e); } }
Example 11
From project activiti-explorer, under directory /src/main/java/org/activiti/explorer/util/.
Source file: UriUtility.java

private static String decode(final String content,final String encoding){ try { return URLDecoder.decode(content,encoding != null ? encoding : "UTF-8"); } catch ( UnsupportedEncodingException problem) { throw new IllegalArgumentException(problem); } }
Example 12
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 13
From project AdminCmd, under directory /src/main/java/be/Balor/Tools/Files/.
Source file: FileManager.java

/** * Get a txt-file and return its content in a String * @param fileName - The name of the file to be loaded * @return The content of the file */ public String getTextFile(final String fileName){ final StringBuffer result=new StringBuffer(); try { final File fileDir=getInnerFile(fileName); final BufferedReader in=new BufferedReader(new UnicodeReader(new FileInputStream(fileDir),"UTF-8")); String temp; while ((temp=in.readLine()) != null) { result.append(temp + "\n"); } in.close(); } catch ( final UnsupportedEncodingException e) { ACLogger.Log(Level.SEVERE,e.getMessage(),e); } catch ( final IOException e) { ACLogger.Log(Level.SEVERE,e.getMessage(),e); } catch ( final Exception e) { ACLogger.Log(Level.SEVERE,e.getMessage(),e); } if (result.length() == 0) { return null; } else { return result.toString().trim(); } }
Example 14
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 15
From project agit, under directory /agit/src/main/java/com/madgag/agit/util/.
Source file: DigestUtils.java

private static byte[] utf8Bytes(String data){ try { return data.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 16
From project agraph-java-client, under directory /src/com/franz/agraph/http/.
Source file: AGHttpRepoClient.java

public void uploadJSON(String url,JSONArray rows,Resource... contexts) throws AGHttpException { if (rows == null) return; InputStream in; try { in=new ByteArrayInputStream(rows.toString().getBytes("UTF-8")); RequestEntity entity=new InputStreamRequestEntity(in,-1,"application/json"); upload(url,entity,null,false,null,null,null,contexts); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 17
From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.
Source file: HttpBuilder.java

private <T>HttpResult<T> doPost(Type target){ try { URI path=createPath(address); HttpPost post=new HttpPost(path); HttpEntity entity=prepareMultipart(); post.setEntity(entity); return doRequest(post,target); } catch ( UnsupportedEncodingException e) { Log.e(Constants.TAG,"Couldn't process parameters",e); return error(); } catch ( URISyntaxException e) { Log.e(Constants.TAG,"Couldn't create path",e); return error(); } }
Example 18
From project airlift, under directory /jaxrs/src/main/java/io/airlift/jaxrs/testing/.
Source file: MockUriInfo.java

private static String urlDecode(String value){ try { return URLDecoder.decode(value,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } }
Example 19
From project ajah, under directory /ajah-amazon-s3/src/main/java/com/efsavage/amazon/s3/.
Source file: S3Client.java

/** * Gets an object. * @see S3Client#getDefaultClient() * @param bucket The bucket to put the object into, required. * @param name The name to store the object as, required. * @param gzip Un-Gzip the data? (if it has .gz to the end of it) * @return The file's data * @throws S3Exception If an error occurs storing the object. */ public byte[] get(final Bucket bucket,final String name,final boolean gzip) throws S3Exception { try { log.finest("Fetching " + name + " from bucket "+ bucket.getName()); final S3Object object=this.s3Service.getObject(bucket.toString(),name); if (gzip && name.endsWith(".gz")) { throw new UnsupportedOperationException(); } return StreamUtils.toByteArray(object.getDataInputStream()); } catch ( final UnsupportedEncodingException e) { throw new ConfigException(e); } catch ( IOException|ServiceException e) { throw new S3Exception(e); } }
Example 20
String readString(int length) throws IOException { if (length > end - (bufferOffset + pos)) throw new EOFException(); String result=null; try { if (buffer.length - pos >= length) { result=decodeChars(buffer,pos,length); pos+=length; } else { byte[] b=new byte[length]; readFully(b); result=decodeChars(b,0,length); } } catch ( UnsupportedEncodingException uee) { throw new Error(); } return result; }
Example 21
From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.
Source file: AVService.java

/** * Post the image related to the incident, with httpPost method. The comment has to be encoded in base64 * @param udid The device id * @param img_comment The far image comment * @param incident_id The id of the related incident * @param image_far The file containing far image * @param image_near The file containing close image */ @SuppressWarnings("unchecked") public void postImage(RequestListener listener,String udid,String img_comment,String incident_id,File image_far,File image_near,boolean newIncident){ this.listener=listener; ArrayList<Object> image_1=new ArrayList<Object>(); ArrayList<Object> image_2=new ArrayList<Object>(); if (image_far != null) { image_1.add(AV_URL + "photo/"); image_1.add(udid); try { image_1.add(Base64.encodeToString(img_comment.getBytes("UTF-8"),Base64.NO_WRAP)); } catch ( UnsupportedEncodingException e) { Log.e(Constants.PROJECT_TAG,"UTF-8 not supported",e); image_1.add(Base64.encodeToString(img_comment.getBytes(),Base64.NO_WRAP)); } image_1.add(incident_id); image_1.add(AV_IMG_FAR); image_1.add(image_far); image_1.add(newIncident); } if (image_near != null) { image_2.add(AV_URL + "photo/"); image_2.add(udid); image_2.add(""); image_2.add(incident_id); image_2.add(AV_IMG_CLOSE); image_2.add(image_near); image_2.add(newIncident); } cancelTask(); currentTask=new postImage().execute(image_1.size() > 0 ? image_1 : null,image_2.size() > 0 ? image_2 : null); }
Example 22
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 23
From project AmDroid, under directory /AmenLib/src/main/java/com.jaeckel/amenoid/api/.
Source file: AmenServiceImpl.java

private User authenticate(String authName,String authPassword) throws IOException { User user; String authJSON="{\"password\":\"" + authPassword + "\",\"email\":\""+ authName+ "\"}"; HttpPost httpPost=new HttpPost(serviceUrl + "authentication.json"); httpPost.setHeader("Content-Type","application/json"); try { httpPost.setEntity(new ByteArrayEntity(authJSON.getBytes("UTF8"))); HttpResponse response=httpclient.execute(httpPost); HttpEntity responseEntity=response.getEntity(); final String responseString=EntityUtils.toString(responseEntity,"UTF-8"); if (responseString.startsWith("{\"error\"")) { lastError=gson.fromJson(responseString,ServerError.class); throw new InvalidCredentialsException(lastError.getError()); } user=gson.fromJson(responseString,User.class); authToken=user.getAuthToken(); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Encoding",e); } catch ( ClientProtocolException e) { throw new RuntimeException("Exception while authenticating",e); } return user; }
Example 24
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/mysql/net/packet/.
Source file: EOFPacket.java

public void write2Buffer(AbstractPacketBuffer buffer) throws UnsupportedEncodingException { super.write2Buffer(buffer); MysqlPacketBuffer myBuffer=(MysqlPacketBuffer)buffer; myBuffer.writeInt(warningCount); myBuffer.writeInt(serverStatus); }
Example 25
From project and-bible, under directory /AndBible/src/net/bible/service/format/.
Source file: OSISInputStream.java

/** * load the next verse, or opening or closing <div> into the verse buffer * @throws UnsupportedEncodingException */ private void loadNextVerse() throws UnsupportedEncodingException { try { if (isFirstVerse) { putInVerseBuffer(DOC_START); isFirstVerse=false; return; } if (keyIterator.hasNext()) { Key currentVerse=keyIterator.next(); String verseText=book.getRawText(currentVerse); verseText=osisVerseTidy.tidy(currentVerse,verseText); putInVerseBuffer(verseText); return; } if (!isClosingTagWritten) { putInVerseBuffer(DOC_END); isClosingTagWritten=true; } } catch ( UnsupportedEncodingException usc) { usc.printStackTrace(); } catch ( BookException be) { be.printStackTrace(); } }
Example 26
From project Android, under directory /app/src/main/java/com/github/mobile/util/.
Source file: GravatarUtils.java

private static String digest(final String value){ if (MD5 == null) return null; byte[] bytes; try { bytes=value.getBytes(CHARSET); } catch ( UnsupportedEncodingException e) { return null; } synchronized (MD5) { MD5.reset(); bytes=MD5.digest(bytes); } String hashed=new BigInteger(1,bytes).toString(16); int padding=HASH_LENGTH - hashed.length(); if (padding == 0) return hashed; char[] zeros=new char[padding]; Arrays.fill(zeros,'0'); return new StringBuilder(HASH_LENGTH).append(zeros).append(hashed).toString(); }
Example 27
public static byte[] convert(String s){ try { if (s != null) { return s.getBytes("us-ascii"); } else { return null; } } catch ( UnsupportedEncodingException e) { throw new Error(e); } }
Example 28
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 29
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: RequestParams.java

/** * Returns an HttpEntity containing all request parameters */ public HttpEntity getEntity(){ HttpEntity entity=null; if (!fileParams.isEmpty()) { SimpleMultipartEntity multipartEntity=new SimpleMultipartEntity(); for ( ConcurrentHashMap.Entry<String,String> entry : urlParams.entrySet()) { multipartEntity.addPart(entry.getKey(),entry.getValue()); } int currentIndex=0; int lastIndex=fileParams.entrySet().size() - 1; for ( ConcurrentHashMap.Entry<String,FileWrapper> entry : fileParams.entrySet()) { FileWrapper file=entry.getValue(); if (file.inputStream != null) { boolean isLast=currentIndex == lastIndex; if (file.contentType != null) { multipartEntity.addPart(entry.getKey(),file.getFileName(),file.inputStream,file.contentType,isLast); } else { multipartEntity.addPart(entry.getKey(),file.getFileName(),file.inputStream,isLast); } } currentIndex++; } entity=multipartEntity; } else { try { entity=new UrlEncodedFormEntity(getParamsList(),ENCODING); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } } return entity; }
Example 30
From project android-client, under directory /xwiki-android-core/src/org/xwiki/android/security/.
Source file: Master.java

/** * Encrypt a secret string. * @param plainTextPwd * @return BASE64 encoded password cypher text string. */ public String encryptPassword(String plainTextPwd){ if (masterCipher == null) return plainTextPwd; byte[] input=null; try { input=plainTextPwd.getBytes("UTF8"); masterCipher.init(Cipher.ENCRYPT_MODE,masterKey); byte[] output=new byte[masterCipher.getOutputSize(input.length)]; int outputLen=masterCipher.update(input,0,input.length,output,0); masterCipher.doFinal(output,outputLen); String out=Base64.encodeToString(output,true); return out; } catch ( InvalidKeyException e) { Log.e(TAG,"invalid key. In Master"); } catch ( ShortBufferException e) { e.printStackTrace(); } catch ( IllegalBlockSizeException e) { Log.d(TAG,"",e); } catch ( BadPaddingException e) { e.printStackTrace(); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"UTF8 not supported ?"); } return plainTextPwd; }
Example 31
From project android-client_1, under directory /src/com/googlecode/asmack/connection/impl/.
Source file: XmppInputStream.java

/** * Attach to an underlying input stream, usually done during feature negotiation as some features require stream resets. * @param in InputStream The new underlying input stream. * @throws XmppTransportException In case of a transport error. */ public void attach(InputStream in) throws XmppTransportException { Log.d(TAG,"attach"); this.inputStream=in; try { parser=XMLUtils.getXMLPullParser(); parser.setInput(new InputStreamReader(in,"UTF-8")); } catch ( XmlPullParserException e) { Log.e(TAG,"attach failed",e); throw new XmppTransportException("Can't initialize pull parser",e); } catch ( UnsupportedEncodingException e) { Log.e(TAG,"attach failed",e); throw new XmppTransportException("Can't initialize pull parser",e); } Log.d(TAG,"attached"); }
Example 32
From project Android-MapForgeFragment, under directory /library-common/src/com/jakewharton/android/mapsforge_fragment/.
Source file: MapDatabase.java

/** * Decodes a variable amount of bytes from the read buffer to a string. * @param readString true if the string should be decoded and returned, false otherwise. * @return the UTF-8 decoded string (may be null). * @throws UnsupportedEncodingException if string decoding fails. */ private String readUTF8EncodedString(boolean readString) throws UnsupportedEncodingException { this.stringLength=readVariableByteEncodedUnsignedInt(); if (this.stringLength >= 0 && this.bufferPosition + this.stringLength <= this.readBuffer.length) { this.bufferPosition+=this.stringLength; if (readString) { return new String(this.readBuffer,this.bufferPosition - this.stringLength,this.stringLength,CHARSET_UTF8); } return null; } Logger.debug("invalid string length: " + this.stringLength); return null; }
Example 33
From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/.
Source file: ApacheHCUtils.java

public static void addEntityForContent(HttpEntityEnclosingRequest apacheRequest,Object content,String contentType,long length){ if (content instanceof InputStream) { InputStream inputStream=(InputStream)content; if (length == -1) throw new IllegalArgumentException("you must specify size when content is an InputStream"); InputStreamEntity Entity=new InputStreamEntity(inputStream,length); Entity.setContentType(contentType); apacheRequest.setEntity(Entity); } else if (content instanceof String) { StringEntity nStringEntity=null; try { nStringEntity=new StringEntity((String)content); } catch ( UnsupportedEncodingException e) { throw new UnsupportedOperationException("Encoding not supported",e); } nStringEntity.setContentType(contentType); apacheRequest.setEntity(nStringEntity); } else if (content instanceof File) { apacheRequest.setEntity(new FileEntity((File)content,contentType)); } else if (content instanceof byte[]) { ByteArrayEntity Entity=new ByteArrayEntity((byte[])content); Entity.setContentType(contentType); apacheRequest.setEntity(Entity); } else { throw new UnsupportedOperationException("Content class not supported: " + content.getClass().getName()); } assert(apacheRequest.getEntity() != null); }
Example 34
From project android-share-menu, under directory /src/org/apache/commons/codec_1_4/binary/.
Source file: Hex.java

/** * Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements. * @param array An array of character bytes containing hexadecimal digits * @return A byte array containing binary data decoded from the supplied byte array (representing characters). * @throws DecoderException Thrown if an odd number of characters is supplied to this function * @see #decodeHex(char[]) */ public byte[] decode(byte[] array) throws DecoderException { try { return decodeHex(new String(array,getCharsetName()).toCharArray()); } catch ( UnsupportedEncodingException e) { throw new DecoderException(e.getMessage(),e); } }
Example 35
From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.
Source file: WebClient.java

protected synchronized String postContentToUrl(String url,String content) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } HttpClient client=CreateClient(); java.net.URI uri=URI.create(url); HttpHost host=GetHost(uri); HttpPost request=new HttpPost(uri.getPath()); request.setHeader("User-Agent",sUserAgent); request.setHeader("Content-Type","text/xml"); HttpEntity ent; try { ent=new StringEntity(content,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new ApiException("unsupported encoding set",e); } request.setEntity(ent); try { HttpResponse response=client.execute(host,request); StatusLine status=response.getStatusLine(); Log.i(cTag,"post with response " + status.toString()); if (status.getStatusCode() != HttpStatus.SC_CREATED) { throw new ApiException("Invalid response from server: " + status.toString() + " for content: "+ content); } Header[] header=response.getHeaders("Location"); if (header.length != 0) return header[0].getValue(); else return null; } catch ( IOException e) { throw new ApiException("Problem communicating with API",e); } }
Example 36
From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/oauth/signpost/signature/.
Source file: HmacSha1MessageSigner.java

@Override public String sign(HttpRequest request,HttpParameters requestParams) throws OAuthMessageSignerException { try { String keyString=OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret()); byte[] keyBytes=keyString.getBytes(OAuth.ENCODING); SecretKey key=new SecretKeySpec(keyBytes,MAC_NAME); Mac mac=Mac.getInstance(MAC_NAME); mac.init(key); String sbs=new SignatureBaseString(request,requestParams).generate(); OAuth.debugOut("SBS",sbs); byte[] text=sbs.getBytes(OAuth.ENCODING); return base64Encode(mac.doFinal(text)).trim(); } catch ( GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch ( UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } }
Example 37
From project Android-Terminal-Emulator, under directory /libraries/emulatorview/src/jackpal/androidterm/emulatorview/.
Source file: TerminalEmulator.java

private String nextOSCString(int delimiter){ int start=mOSCArgTokenizerIndex; int end=start; while (mOSCArgTokenizerIndex < mOSCArgLength) { byte b=mOSCArg[mOSCArgTokenizerIndex++]; if ((int)b == delimiter) { break; } end++; } if (start == end) { return ""; } try { return new String(mOSCArg,start,end - start,"UTF-8"); } catch ( UnsupportedEncodingException e) { return new String(mOSCArg,start,end - start); } }
Example 38
From project android-tether, under directory /src/og/android/tether/.
Source file: MainActivity.java

String tagURL(String url,String medium,String content,String campaign){ String p=url.contains("?") ? "&" : "?"; String source="og.android.tether_" + application.getVersionNumber(); try { source=URLEncoder.encode(source,"UTF-8"); medium=URLEncoder.encode(medium,"UTF-8"); content=URLEncoder.encode(content,"UTF-8"); campaign=URLEncoder.encode(campaign,"UTF-8"); } catch ( UnsupportedEncodingException e) { } return url + p + "utm_source="+ source+ "&utm_medium="+ medium+ "&utm_content="+ content+ "&utm_campaign="+ campaign; }
Example 39
From project android-vpn-server, under directory /src/android/security/.
Source file: KeyStore.java

private static byte[] getBytes(String string){ try { return string.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 40
From project android-vpn-settings, under directory /src/android/security/.
Source file: KeyStore.java

private static byte[] getBytes(String string){ try { return string.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Example 41
From project android-xbmcremote, under directory /src/org/xbmc/android/util/.
Source file: Crc32.java

public static int compute(String strValue){ try { return compute(strValue.getBytes("UTF-8"),0xFFFFFFFF); } catch ( UnsupportedEncodingException e) { return compute(strValue.getBytes(),0xFFFFFFFF); } }
Example 42
From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/utils/.
Source file: AESObfuscator.java

public String obfuscate(String original){ if (original == null) { return null; } try { return Base64.encode(mEncryptor.doFinal((header + original).getBytes(UTF8))); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("Invalid environment",e); } catch ( GeneralSecurityException e) { throw new RuntimeException("Invalid environment",e); } }
Example 43
From project androidquery, under directory /demo/src/com/androidquery/test/async/.
Source file: AjaxLoadingActivity.java

public void async_post_entity() throws UnsupportedEncodingException { String url="http://search.twitter.com/search.json"; List<NameValuePair> pairs=new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("q","androidquery")); HttpEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8"); Map<String,Object> params=new HashMap<String,Object>(); params.put(AQuery.POST_ENTITY,entity); aq.progress(R.id.progress).ajax(url,params,JSONObject.class,new AjaxCallback<JSONObject>(){ @Override public void callback( String url, JSONObject json, AjaxStatus status){ showResult(json,status); } } ); }
Example 44
public String crypt(int mode,String encryption_subject) throws Base64DecoderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, UnsupportedEncodingException, IllegalBlockSizeException { final PBEParameterSpec ps=new javax.crypto.spec.PBEParameterSpec(SALT,20); final SecretKeyFactory kf=SecretKeyFactory.getInstance(ALGORITHM); final SecretKey k=kf.generateSecret(new javax.crypto.spec.PBEKeySpec(SECRET_KEY.toCharArray())); final Cipher crypter=Cipher.getInstance(CIPHER_TYPE); String result; switch (mode) { case Cipher.DECRYPT_MODE: crypter.init(Cipher.DECRYPT_MODE,k,ps); result=new String(crypter.doFinal(Base64.decode(encryption_subject)),CHARSET); break; case Cipher.ENCRYPT_MODE: default : crypter.init(Cipher.ENCRYPT_MODE,k,ps); result=Base64.encode(crypter.doFinal(encryption_subject.getBytes(CHARSET))); } return result; }
Example 45
static String utf8(byte[] signature){ try { return new String(signature,"UTF-8"); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); return ""; } }
Example 46
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 47
From project android_packages_apps_CellBroadcastReceiver, under directory /tests/src/com/android/cellbroadcastreceiver/.
Source file: DialogSmsDisplayTests.java

byte[] encodeCellBroadcast(int serialNumber,int messageId,int dcs,String message){ byte[] pdu=new byte[88]; pdu[0]=(byte)((serialNumber >> 8) & 0xff); pdu[1]=(byte)(serialNumber & 0xff); pdu[2]=(byte)((messageId >> 8) & 0xff); pdu[3]=(byte)(messageId & 0xff); pdu[4]=(byte)(dcs & 0xff); pdu[5]=0x11; try { byte[] encodedString; if (dcs == DCS_16BIT_UCS2) { encodedString=message.getBytes("UTF-16"); System.arraycopy(encodedString,0,pdu,6,encodedString.length); } else { encodedString=GsmAlphabet.stringToGsm7BitPacked(message); System.arraycopy(encodedString,1,pdu,6,encodedString.length - 1); } return pdu; } catch ( EncodeException e) { Log.e(TAG,"Encode Exception"); return null; } catch ( UnsupportedEncodingException e) { Log.e(TAG,"Unsupported encoding exception for UTF-16"); return null; } }
Example 48
From project android_packages_apps_Superuser, under directory /src/com/noshufou/android/su/util/.
Source file: Util.java

public static String getHash(String pin){ MessageDigest digest; try { digest=MessageDigest.getInstance("SHA-1"); } catch ( NoSuchAlgorithmException e) { Log.e("Utils","NoSuchAlgorithm, storing in plain text...",e); return pin; } digest.reset(); try { byte[] input=digest.digest(pin.getBytes("UTF-8")); String base64=Base64.encode(input); return base64; } catch ( UnsupportedEncodingException e) { Log.e("Utils","UnsupportedEncoding, storing in plain text...",e); return pin; } }
Example 49
From project android_packages_apps_Tag, under directory /src/com/android/apps/tag/record/.
Source file: TextRecord.java

public static TextRecord parse(NdefRecord record){ Preconditions.checkArgument(record.getTnf() == NdefRecord.TNF_WELL_KNOWN); Preconditions.checkArgument(Arrays.equals(record.getType(),NdefRecord.RTD_TEXT)); try { byte[] payload=record.getPayload(); String textEncoding=((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16"; int languageCodeLength=payload[0] & 0077; String languageCode=new String(payload,1,languageCodeLength,"US-ASCII"); String text=new String(payload,languageCodeLength + 1,payload.length - languageCodeLength - 1,textEncoding); return new TextRecord(languageCode,text); } catch ( UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } }
Example 50
From project Android_Pusher, under directory /src/de/roderick/weberknecht/.
Source file: WebSocketConnection.java

public synchronized void send(String data) throws WebSocketException { if (!connected) { throw new WebSocketException("error while sending text data: not connected"); } try { output.write(0x00); output.write(data.getBytes(("UTF-8"))); output.write(0xff); Log.d("Output","Wrote to Output"); } catch ( UnsupportedEncodingException uee) { uee.printStackTrace(); throw new WebSocketException("error while sending text data: unsupported encoding",uee); } catch ( IOException ioe) { ioe.printStackTrace(); throw new WebSocketException("error while sending text data",ioe); } }
Example 51
From project andstatus, under directory /src/org/andstatus/app/net/.
Source file: ConnectionBasicAuth.java

@Override public JSONObject updateStatus(String message,String inReplyToId) throws ConnectionException { String url=getApiUrl(apiEnum.STATUSES_UPDATE); List<NameValuePair> formParams=new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("status",message)); if (!TextUtils.isEmpty(inReplyToId)) { formParams.add(new BasicNameValuePair("in_reply_to_status_id",inReplyToId)); } JSONObject jObj=null; try { jObj=new JSONObject(postRequest(url,new UrlEncodedFormEntity(formParams,HTTP.UTF_8))); String error=jObj.optString("error"); if ("Could not authenticate you.".equals(error)) { throw new ConnectionException(error); } } catch ( UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } catch ( JSONException e) { throw new ConnectionException(e); } return jObj; }
Example 52
From project andtweet, under directory /src/com/xorcode/andtweet/net/.
Source file: ConnectionBasicAuth.java

@Override public JSONObject updateStatus(String message,long inReplyToId) throws ConnectionException { String url=STATUSES_UPDATE_URL; List<NameValuePair> formParams=new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("status",message)); if (inReplyToId > 0) { formParams.add(new BasicNameValuePair("in_reply_to_status_id",String.valueOf(inReplyToId))); } JSONObject jObj=null; try { jObj=new JSONObject(postRequest(url,new UrlEncodedFormEntity(formParams,HTTP.UTF_8))); String error=jObj.optString("error"); if ("Could not authenticate you.".equals(error)) { throw new ConnectionException(error); } } catch ( UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } catch ( JSONException e) { throw new ConnectionException(e); } return jObj; }
Example 53
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; }