List of usage examples for java.io UnsupportedEncodingException toString
public String toString()
From source file:org.kiji.schema.FormattedEntityId.java
/** * Decode a byte array containing an hbase row key into an ordered list corresponding to * the key format in the layout file.//from w ww. java 2 s . com * * @param format The row key format as specified in the layout file. * @param hbaseRowKey A byte array containing the hbase row key. * @return An ordered list of component values in the key. */ private static List<Object> makeKijiRowKey(RowKeyFormat2 format, byte[] hbaseRowKey) { if (hbaseRowKey.length == 0) { throw new EntityIdException("Invalid hbase row key"); } List<Object> kijiRowKey = new ArrayList<Object>(); // skip over the hash int pos = format.getSalt().getHashSize(); // we are suppressing materialization, so the components cannot be retrieved. int kijiRowElem = 0; if (format.getSalt().getSuppressKeyMaterialization()) { if (pos < hbaseRowKey.length) { throw new EntityIdException("Extra bytes in key after hash when materialization is" + "suppressed"); } return null; } ByteBuffer buf; while (kijiRowElem < format.getComponents().size() && pos < hbaseRowKey.length) { switch (format.getComponents().get(kijiRowElem).getType()) { case STRING: // Read the row key until we encounter a Null (0) byte or end. int endpos = pos; while (endpos < hbaseRowKey.length && (hbaseRowKey[endpos] != (byte) 0)) { endpos += 1; } String str = null; try { str = new String(hbaseRowKey, pos, endpos - pos, "UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error(e.toString()); throw new EntityIdException(String.format("UnsupportedEncoding for component %d", kijiRowElem)); } kijiRowKey.add(str); pos = endpos + 1; break; case INTEGER: // Toggle highest order bit to return to original 2's complement. hbaseRowKey[pos] = (byte) ((int) hbaseRowKey[pos] ^ (int) Byte.MIN_VALUE); try { buf = ByteBuffer.wrap(hbaseRowKey, pos, Integer.SIZE / Byte.SIZE); } catch (IndexOutOfBoundsException e) { throw new EntityIdException("Malformed hbase Row Key"); } kijiRowKey.add(Integer.valueOf(buf.getInt())); pos = pos + Integer.SIZE / Byte.SIZE; break; case LONG: // Toggle highest order bit to return to original 2's complement. hbaseRowKey[pos] = (byte) ((int) hbaseRowKey[pos] ^ (int) Byte.MIN_VALUE); try { buf = ByteBuffer.wrap(hbaseRowKey, pos, Long.SIZE / Byte.SIZE); } catch (IndexOutOfBoundsException e) { throw new EntityIdException("Malformed hbase Row Key"); } kijiRowKey.add(Long.valueOf(buf.getLong())); pos = pos + Long.SIZE / Byte.SIZE; break; default: throw new RuntimeException("Invalid code path"); } kijiRowElem += 1; } // Fail if there are extra bytes in hbase row key. if (pos < hbaseRowKey.length) { throw new EntityIdException("Extra bytes in hbase row key cannot be mapped to any " + "component"); } // Fail if we encounter nulls before it is legal to do so. if (kijiRowElem < format.getNullableStartIndex()) { throw new EntityIdException("Too few components decoded from hbase row key. Component " + "number " + kijiRowElem + " cannot be null"); } // finish up with nulls for everything that wasn't in the key for (; kijiRowElem < format.getComponents().size(); kijiRowElem++) { kijiRowKey.add(null); } return kijiRowKey; }
From source file:com.alibaba.akita.io.HttpInvoker.java
public static String post(String url, ArrayList<NameValuePair> params, Header[] headers) throws AkInvokeException, AkServerStatusException { //==log start // TEMP//from w w w . j a va2 s . c o m //url = url.replace("gw.api.alibaba.com", "205.204.112.73"); // usa ocean //url = url.replace("gw.api.alibaba.com", "172.20.128.127"); //url = url.replace("mobi.aliexpress.com", "172.20.226.142"); Log.v(TAG, "post:" + url); if (params != null) { Log.v(TAG, "params:====================="); for (NameValuePair nvp : params) { Log.v(TAG, nvp.getName() + "=" + nvp.getValue()); } Log.v(TAG, "params end:====================="); } //==log end String retString = null; try { HttpPost request = new HttpPost(url); if (headers != null) { for (Header header : headers) { request.addHeader(header); } } if (params == null) { Log.e(TAG, "Post Parameters Null Error"); throw new AkInvokeException(AkInvokeException.CODE_POST_PARAM_NULL_ERROR, "Post Parameters Null Error"); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET); request.setEntity(entity); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { HttpEntity resEntity = response.getEntity(); retString = (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET); } else { HttpEntity resEntity = response.getEntity(); throw new AkServerStatusException(response.getStatusLine().getStatusCode(), EntityUtils.toString(resEntity, CHARSET)); } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, e.toString(), e); } catch (ClientProtocolException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, e.toString(), e); } catch (IOException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, e.toString(), e); } catch (ParseException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_PARSE_EXCEPTION, e.toString(), e); } Log.v(TAG, "response:" + retString); return retString; }
From source file:org.akita.io.HttpInvoker.java
public static String post(String url, ArrayList<NameValuePair> params, Header[] headers) throws AkInvokeException, AkServerStatusException { //==log start Log.v(TAG, "post:" + url); if (params != null) { Log.v(TAG, "params:====================="); for (NameValuePair nvp : params) { Log.v(TAG, nvp.getName() + "=" + nvp.getValue()); }/* ww w.j av a 2 s. com*/ Log.v(TAG, "params end:====================="); } //==log end String retString = null; try { HttpPost request = new HttpPost(url); if (headers != null) { for (Header header : headers) { request.addHeader(header); } } if (params == null) { Log.e(TAG, "Post Parameters Null Error"); throw new AkInvokeException(AkInvokeException.CODE_POST_PARAM_NULL_ERROR, "Post Parameters Null Error"); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, CHARSET); request.setEntity(entity); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { HttpEntity resEntity = response.getEntity(); retString = (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET); } else { HttpEntity resEntity = response.getEntity(); throw new AkServerStatusException(response.getStatusLine().getStatusCode(), EntityUtils.toString(resEntity, CHARSET)); } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, e.toString(), e); } catch (ClientProtocolException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_HTTP_PROTOCOL_ERROR, e.toString(), e); } catch (IOException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_CONNECTION_ERROR, e.toString(), e); } catch (ParseException e) { Log.e(TAG, e.toString(), e); throw new AkInvokeException(AkInvokeException.CODE_PARSE_EXCEPTION, e.toString(), e); } Log.v(TAG, "response:" + retString); return retString; }
From source file:org.opendatakit.common.utils.WebUtils.java
/** * Safely encode a string for use as a query parameter. * /*w w w .j av a2 s . co m*/ * @param rawString * @return encoded string */ public static String safeEncode(String rawString) { if (rawString == null || rawString.length() == 0) { return null; } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(rawString.getBytes(CharEncoding.UTF_8)); gzip.finish(); gzip.close(); String candidate = Base64.encodeBase64URLSafeString(out.toByteArray()); return candidate; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalArgumentException("Unexpected failure: " + e.toString()); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unexpected failure: " + e.toString()); } }
From source file:org.opendatakit.common.utils.WebUtils.java
/** * Decode a safeEncode() string.//w w w . j av a 2 s . c o m * * @param encodedWebsafeString * @return rawString */ public static String safeDecode(String encodedWebsafeString) { if (encodedWebsafeString == null || encodedWebsafeString.length() == 0) { return encodedWebsafeString; } try { ByteArrayInputStream in = new ByteArrayInputStream( Base64.decodeBase64(encodedWebsafeString.getBytes(CharEncoding.UTF_8))); GZIPInputStream gzip = new GZIPInputStream(in); ByteArrayOutputStream out = new ByteArrayOutputStream(); int ch = gzip.read(); while (ch >= 0) { out.write(ch); ch = gzip.read(); } gzip.close(); out.flush(); out.close(); return new String(out.toByteArray(), CharEncoding.UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalArgumentException("Unexpected failure: " + e.toString()); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unexpected failure: " + e.toString()); } }
From source file:com.granule.json.utils.XML.java
/** * Method to take an input stream to an XML document and return a String of the JSON format. Note that the xmlStream is not closed when read is complete. This is left up to the caller, who may wish to do more with it. * @param xmlStream The InputStream to an XML document to transform to JSON. * @param verbose Boolean flag denoting whther or not to write the JSON in verbose (formatted), or compact form (no whitespace) * @return A string of the JSON representation of the XML file * /*from w w w . j a v a2 s . c om*/ * @throws SAXException Thrown if an error occurs during parse. * @throws IOException Thrown if an IOError occurs. */ public static String toJson(InputStream xmlStream, boolean verbose) throws SAXException, IOException { if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toJson(InputStream, boolean)"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); String result = null; try { toJson(xmlStream, baos, verbose); result = baos.toString("UTF-8"); baos.close(); } catch (UnsupportedEncodingException uec) { IOException iox = new IOException(uec.toString()); iox.initCause(uec); throw iox; } if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toJson(InputStream, boolean)"); } return result; }
From source file:com.granule.json.utils.XML.java
/** * Method to take an input stream to an JSON document and return a String of the XML format. Note that the JSONStream is not closed when read is complete. This is left up to the caller, who may wish to do more with it. * @param xmlStream The InputStream to an JSON document to transform to XML. * @param verbose Boolean flag denoting whther or not to write the XML in verbose (formatted), or compact form (no whitespace) * @return A string of the JSON representation of the XML file * //from w w w . j a va 2s .c o m * @throws IOException Thrown if an IOError occurs. */ public static String toXml(InputStream JSONStream, boolean verbose) throws IOException { if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toXml(InputStream, boolean)"); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); String result = null; try { toXml(JSONStream, baos, verbose); result = baos.toString("UTF-8"); baos.close(); } catch (UnsupportedEncodingException uec) { IOException iox = new IOException(uec.toString()); iox.initCause(uec); throw iox; } if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toXml(InputStream, boolean)"); } return result; }
From source file:org.notfunnynerd.opencoinmap.utils.JSONParser.java
public static JSONObject getJSONfromUrl(String url) { InputStream is = null;//from www . j av a 2s.c o m JSONObject jObj = null; String json = ""; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString().trim(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // Log.i("JSONParser", json); try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSONParser", "Error parsing data " + e.toString()); } return jObj; }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Common part for sending message process : * <ul>//from w w w . j a va 2 s .co m * <li>initializes a mail session with the SMTP server</li> * <li>activates debugging</li> * <li>instantiates and initializes a mime message</li> * <li>sets the sent date, the from field, the subject field</li> * <li>sets the recipients</li> * </ul> * * * @return the message object initialized with the common settings * @param strRecipientsTo The list of the main recipients email.Every * recipient must be separated by the mail separator defined in * config.properties * @param strRecipientsCc The recipients list of the carbon copies . * @param strRecipientsBcc The recipients list of the blind carbon copies . * @param strSenderName The sender name. * @param strSenderEmail The sender email address. * @param strSubject The message subject. * @param session The SMTP session object * @throws AddressException If invalid address * @throws MessagingException If a messaging error occurred */ protected static Message prepareMessage(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, Session session) throws MessagingException, AddressException { // Instantiate and initialize a mime message Message msg = new MimeMessage(session); msg.setSentDate(new Date()); try { msg.setFrom(new InternetAddress(strSenderEmail, strSenderName, AppPropertiesService.getProperty(PROPERTY_CHARSET))); msg.setSubject(MimeUtility.encodeText(strSubject, AppPropertiesService.getProperty(PROPERTY_CHARSET), ENCODING)); } catch (UnsupportedEncodingException e) { throw new AppException(e.toString()); } // Instantiation of the list of address if (strRecipientsTo != null) { msg.setRecipients(Message.RecipientType.TO, getAllAdressOfRecipients(strRecipientsTo)); } if (strRecipientsCc != null) { msg.setRecipients(Message.RecipientType.CC, getAllAdressOfRecipients(strRecipientsCc)); } if (strRecipientsBcc != null) { msg.setRecipients(Message.RecipientType.BCC, getAllAdressOfRecipients(strRecipientsBcc)); } return msg; }
From source file:com.provision.alarmemi.paper.fragments.SetAlarmFragment.java
public static void deleteCloudAlarm(final Context c, final Alarm tempAlarm) { FragmentChangeActivity.progressDialog.show(); new Thread() { @Override// w w w .j av a 2 s. com public void run() { if (prefs == null) prefs = c.getSharedPreferences("forest", Context.MODE_PRIVATE); String url = null; try { url = "http://alarmemi.appspot.com/alarmemi/alarm/remove?owner_name=" + URLEncoder.encode(tempAlarm.cloudName, "UTF-8") + "&owner_password=" + prefs.getString(tempAlarm.cloudName + "_password", "") + "&key=" + tempAlarm.cloudKey + "&my_uuid=" + myUUID; } catch (UnsupportedEncodingException e) { showToast(e.toString(), false); } String result = ServerUtilities.connect(url, c); if (result == null) { showToast(c.getString(R.string.cloud_failed), false); } else if (result.equals("CONNECTION_FAILED")) { showToast(c.getString(R.string.connection_chk), false); } else if (result.equals("FAILED")) { showToast(c.getString(R.string.cloud_failed), false); } else { Alarms.deleteAlarm(c, tempAlarm.id); } ProgressDismiss.sendEmptyMessage(0); } }.start(); }