List of usage examples for java.lang Exception getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:com.swingtech.commons.util.ClassUtil.java
/** * Utility method that uses bean introspection to set a value for a property * for any given Bean. This allows you to dynamically set bean values by * specifying the the name of the property and a value * * For example: <blockquote>/*w w w . j a va 2s . c om*/ * * <pre> * Person person = . . . <font color="#339933">//(get a populated Person object from somewhere)</font> * String age = setBeanProperty(person, "age", "23"); * </pre> * * </blockquote> Is the same as: <blockquote> * * <pre> * String age = person.setAge("23"); * </pre> * * </blockquote> * * @param pBean * - the bean which contains the data for which you want to get. * @param pPropertyName * - the bean property you want to set the data for. This should * follow all the JavaBean convention...i.e. if the property name * is "age", there should be a method "getAge()" on the bean. * @param pValue * - The value you want to set for the bean. * @throws RuntimeException * - If the propertyName is not found on the bean or if the * value passed in is not the expected data type or object type * expected. * @return Object - The value for the property on the bean. */ public static void setBeanProperty(final Object pBean, final String pPropertyName, final Object pValue) { try { BeanUtils.setProperty(pBean, pPropertyName, pValue); } catch (final Exception e) { throw new RuntimeException("Error occured trying to set property " + "name, '" + pPropertyName + "', in object of class, '" + pBean.getClass().getName() + "'. Error: " + e.getClass().getName() + ": " + e.getMessage(), e); } return; }
From source file:com.swingtech.commons.util.ClassUtil.java
/** * Utility method that uses bean introspection to get a String value for a * property for any given Bean. This allows you to dynamically get bean * values by specifying the the name of the property. This method will * return a String.// w ww . j av a2s .c o m * * For example: <blockquote> * * <pre> * Person person = . . . <font color="#339933">//(get a populated Person object from somewhere)</font> * String age = getBeanProperty(person, "age"); * </pre> * * </blockquote> Is the same as: <blockquote> * * <pre> * String age = person.getAge(); * </pre> * * </blockquote> * * @Deprecated This method returns a String, instead of an object. Might * have some wierd unexpected behavior. Use getBeanProperty() * instead. It returns an object. * * @param pBean * - the bean which contains the data for which you want to get. * @param pPropertyName * - the bean property you want to get the data for. This should * follow all the JavaBean convention...i.e. if the property name * is "age", there should be a method "getAge()" on the bean. * @return Object - The value for the property on the bean. * */ public static Object getBeanPropertyString(final Object pBean, final String pPropertyName) { Object vReturnObject = null; try { vReturnObject = BeanUtils.getProperty(pBean, pPropertyName); } catch (final Exception e) { throw new RuntimeException("Error occured trying to get property " + "name, '" + pPropertyName + "', from object of class, '" + pBean.getClass().getName() + "'. Error: " + e.getClass().getName() + ": " + e.getMessage(), e); } return vReturnObject; }
From source file:com.swingtech.commons.util.ClassUtil.java
/** * Utility method that uses bean introspection to get a value for a property * for any given Bean. This allows you to dynamically get bean values by * specifying the the name of the property. This method will return an * object./*from w ww .ja v a 2 s .c o m*/ * * For example: <blockquote> * * <pre> * Person person = . . . <font color="#339933">//(get a populated Person object from somewhere)</font> * String age = getBeanProperty(person, "age"); * </pre> * * </blockquote> Is the same as: <blockquote> * * <pre> * String age = person.getAge(); * </pre> * * </blockquote> * * @param pBean * - the bean which contains the data for which you want to get. * @param pPropertyName * - the bean property you want to get the data for. This should * follow all the JavaBean convention...i.e. if the property name * is "age", there should be a method "getAge()" on the bean. * @return Object - The value for the property on the bean. */ public static Object getBeanProperty(final Object pBean, final String pPropertyName) { Object vReturnObject = null; try { vReturnObject = PropertyUtils.getProperty(pBean, pPropertyName); } catch (final RuntimeException re) { // if it's a runtime exception, throw the original exception. This // way, it gets bubbled to the top. throw re; } catch (final Exception e) { throw new RuntimeException("Error occured trying to get property " + "name, '" + pPropertyName + "', from object of class, '" + pBean.getClass().getName() + "'. Error: " + e.getClass().getName() + ": " + e.getMessage(), e); } return vReturnObject; }
From source file:com.revorg.goat.IndexManager.java
/** * Creates documents inside of the Lucene Index * * @param writer Index Writer Class * @param rs Result Set for the row of data * @param columnNamesArray The array of column names to be added to the document * @param indexTypeArray The array of column types to be added to the document * @param tempHTMLDir The temporary HTML directory for HTML publishing * @throws Exception//from www . j a va 2 s . c om * @return ActionResult */ private static String createDocument(IndexWriter writer, ResultSet rs, String columnNamesArray[], String indexTypeArray[], String tempHTMLDir) { try { final Document doc = new Document(); int columns = columnNamesArray.length; /* public Field(String name, String value, Field.Store store, Field.Index index) Store: COMPRESS - Store the original field value in the index in a compressed form. This is useful for long documents and for binary valued fields. YES -Store the original field value in the index. This is useful for short texts like a document's title which should be displayed with the results. The value is stored in its original form, i.e. no analyzer is used before it is stored. NO - Do not store the field value in the index. Index: ANALYZED - Index the tokens produced by running the field's value through an Analyzer. This is useful for common text NOT_ANALYZED - Index the field's value without using an Analyzer, so it can be searched. As no analyzer is used the value will be stored as a single term. This is useful for unique Ids like product numbers. NO - Do not index the field value. This field can thus not be searched, but one can still access its contents provided it is stored. */ for (int i = 0; i < columns; i++) { String columnName = columnNamesArray[i].trim().toLowerCase(); String columnIndexType = indexTypeArray[i]; //Map Column Type To Array String columnValue = rs.getString(columnName); //Get Value But Result Sets are at 1 Not 0 if (columnValue == null) { //Lucene Does Not Like Nulls columnValue = ""; } //System.out.println(" Values: " + columnName + " " + columnIndexType + " " + columnValue + " " + columnValue.length()); //Can't Add Triggers if (columnIndexType.equalsIgnoreCase("TriggerUpdate") == false || columnIndexType.equalsIgnoreCase("TriggerDelete") == false) { if (columnIndexType.equalsIgnoreCase("PrimaryKey") || columnIndexType.equalsIgnoreCase("Keyword") || columnIndexType.equalsIgnoreCase("Date")) { //Format Dates to Correct for Sorting if (columnIndexType.equalsIgnoreCase("Date")) { columnValue = columnValue.replace("/", ""); } doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.NOT_ANALYZED)); } //UnIndexed of UnIndexed else if (columnIndexType.equalsIgnoreCase("UnIndexed")) { doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.NO)); } else if (columnIndexType.equalsIgnoreCase("Text")) { doc.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED)); } else if (columnIndexType.equalsIgnoreCase("UnStored") || columnIndexType.equalsIgnoreCase("HTML")) { if (columnIndexType.equalsIgnoreCase("HTML") && columnValue.length() != 0) { String htmlString = tempHTMLDir + Utilities.CreateUUID() + ".html"; File htmlFile = new File(htmlString); BufferedWriter out = new BufferedWriter(new FileWriter(htmlString)); out.write(columnValue); out.close(); //Parse Document FileInputStream fis = new FileInputStream(htmlFile); HTMLParser parser = new HTMLParser(fis); // Add the tag-stripped contents as a Reader-valued Text field so it will // get tokenized and indexed. doc.add(new Field(columnName, parser.getReader())); //Parse HTML } //UnStored Field else { doc.add(new Field(columnName, columnValue, Field.Store.NO, Field.Index.ANALYZED)); } } else if (columnIndexType.equalsIgnoreCase("Binary")) { doc.add(new Field(columnName, columnValue, Field.Store.COMPRESS, Field.Index.NO)); } } } //Add Document Here //System.out.println(doc); writer.addDocument(doc); ActionResult = "Success"; return ActionResult; } catch (Exception e) { ActionResultError = " caught a " + e.getClass() + " with message: " + e.getMessage(); //System.out.println("Failure of DbSchema File: " + xmlFile); } ActionResult = "Failure"; return ActionResult + ActionResultError; }
From source file:com.linkedin.sample.test.java
public static void main1(String[] args) { /*/* w w w . j a v a2 s . c om*/ we need a OAuthService to handle authentication and the subsequent calls. Since we are going to use the REST APIs we need to generate a request token as the first step in the call. Once we get an access toke we can continue to use that until the API key changes or auth is revoked. Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to disk and then reuse it. When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own credentials and if there is a service.dat file in the code please delete it. */ //The Access Token is used in all Data calls to the APIs - it basically says our application has been given access //to the approved information in LinkedIn Token accessToken = null; //Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls. OAuthService service = new ServiceBuilder().provider(LinkedInApi.class).apiKey(API_KEY) .apiSecret(API_SECRET).build(); /************************************* * This first piece of code handles all the pieces needed to be granted access to make a data call */ try { File file = new File("service.dat"); if (file.exists()) { //if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file)); AuthHandler authHandler = (AuthHandler) inputStream.readObject(); accessToken = authHandler.getAccessToken(); } else { System.out.println("There is no stored Access token we need to make one"); //In the constructor the AuthHandler goes through the chain of calls to create an Access Token AuthHandler authHandler = new AuthHandler(service); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.dat")); outputStream.writeObject(authHandler); outputStream.close(); accessToken = authHandler.getAccessToken(); } } catch (Exception e) { System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage()); } /* * We are all done getting access - time to get busy getting data *************************************/ /************************** * * Querying the LinkedIn API * **************************/ System.out.println(); System.out.println("********A basic user profile call********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/profile-api String url = "http://api.linkedin.com/v1/people/~"; OAuthRequest request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); Response response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON********"); //This basic call profile in JSON format //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addHeader("x-li-format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get the profile in JSON using query parameter********"); //This basic call profile in JSON format. Please note the call above is the preferred method. //You can read more about JSON here http://json.org url = "http://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("format", "json"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get my connections - going into a resource********"); //This basic call gets all your connections each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********Get only 10 connections - using parameters********"); //This basic call gets only 10 connections - each one will be in a person tag with some profile information //https://developer.linkedin.com/documents/connections-api //more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string url = "http://api.linkedin.com/v1/people/~/connections"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("count", "10"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********GET network updates that are CONN and SHAR********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/get-network-updates-and-statistics-api //specifics on updates https://developer.linkedin.com/documents/network-update-types url = "http://api.linkedin.com/v1/people/~/network/updates"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("type", "SHAR"); request.addQuerystringParameter("type", "CONN"); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********"); //This basic call get connection updates from your connections //https://developer.linkedin.com/documents/people-search-api#Facets //Why doesn't this look like //people-search?title=developer&location=fr&industry=4 //url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0"; url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))"; request = new OAuthRequest(Verb.GET, url); request.addQuerystringParameter("title", "Dveloppeur"); request.addQuerystringParameter("facet", "industry,4"); request.addQuerystringParameter("facets", "location,industry"); System.out.println(request.getUrl()); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getBody()); System.out.println(); System.out.println(); /////////////////field selectors System.out.println("********A basic user profile call with field selectors********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out .println("********A basic user profile call with field selectors going into a subresource********"); //The ~ means yourself - so this should return the basic default information for your profile in XML format //https://developer.linkedin.com/documents/field-selectors url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A basic user profile call into a subresource return data in JSON********"); //The ~ means yourself - so this should return the basic default information for your profile //https://developer.linkedin.com/documents/field-selectors url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); System.out.println("********A more complicated example using postings into groups********"); //https://developer.linkedin.com/documents/field-selectors //https://developer.linkedin.com/documents/groups-api url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); System.out.println(response.getHeaders().toString()); System.out.println(response.getBody()); System.out.println(); System.out.println(); /************************** * * Wrting to the LinkedIn API * **************************/ /* * Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out * some code. Uncomment if you'd like to see writes in action. * * System.out.println("********Write to the share - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addHeader("Content-Type", "text/xml"); //Make an XML document Document doc = DocumentHelper.createDocument(); Element share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs"); Element content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to Twitter - using XML********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); request.addQuerystringParameter("twitter-post","true"); request.addHeader("Content-Type", "text/xml"); //Make an XML document doc = DocumentHelper.createDocument(); share = doc.addElement("share"); share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter"); content = share.addElement("content"); content.addElement("title").addText("A title for your share"); content.addElement("submitted-url").addText("http://developer.linkedin.com"); share.addElement("visibility").addElement("code").addText("anyone"); request.addPayload(doc.asXML()); service.signRequest(accessToken, request); response = request.send(); //there is no body just a header System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); System.out.println("********Write to the share and to twitter - using JSON ********"); //This basic shares some basic information on the users activity stream //https://developer.linkedin.com/documents/share-api //NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org url = "http://api.linkedin.com/v1/people/~/shares"; request = new OAuthRequest(Verb.POST, url); //set the headers to the server knows what we are sending request.addHeader("Content-Type", "application/json"); request.addHeader("x-li-format", "json"); //make the json payload using json-simple Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("comment", "Posting from the API using JSON"); JSONObject contentObject = new JSONObject(); contentObject.put("title", "This is a another test post"); contentObject.put("submitted-url","http://www.linkedin.com"); contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg"); jsonMap.put("content", contentObject); JSONObject visibilityObject = new JSONObject(); visibilityObject.put("code", "anyone"); jsonMap.put("visibility", visibilityObject); request.addPayload(JSONValue.toJSONString(jsonMap)); service.signRequest(accessToken, request); response = request.send(); //again no body - just headers System.out.println(response.getBody()); System.out.println(response.getHeaders().toString()); System.out.println();System.out.println(); */ /************************** * * Understanding the response, creating logging, request and response headers * **************************/ System.out.println(); System.out.println("********A basic user profile call and response dissected********"); //This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle //https://developer.linkedin.com/documents/debugging-api-calls url = "https://api.linkedin.com/v1/people/~"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); //get all the headers System.out.println("Request headers: " + request.getHeaders().toString()); System.out.println("Response headers: " + response.getHeaders().toString()); //url requested System.out.println("Original location is: " + request.getHeaders().get("content-location")); //Date of response System.out.println("The datetime of the response is: " + response.getHeader("Date")); //the format of the response System.out.println("Format is: " + response.getHeader("x-li-format")); //Content-type of the response System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n"); //get the HTTP response code - such as 200 or 404 int responseNumber = response.getCode(); if (responseNumber >= 199 && responseNumber < 300) { System.out.println("HOORAY IT WORKED!!"); System.out.println(response.getBody()); } else if (responseNumber >= 500 && responseNumber < 600) { //you could actually raise an exception here in your own code System.out.println("Ruh Roh application error of type 500: " + responseNumber); System.out.println(response.getBody()); } else if (responseNumber == 403) { System.out.println("A 403 was returned which usually means you have reached a throttle limit"); } else if (responseNumber == 401) { System.out.println("A 401 was returned which is a Oauth signature error"); System.out.println(response.getBody()); } else if (responseNumber == 405) { System.out.println( "A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc)."); } else { System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums"); System.out.println(response.getBody()); } System.out.println(); System.out.println(); System.out.println("********A basic error logging function********"); // Now demonstrate how to make a logging function which provides us the info we need to // properly help debug issues. Please use the logged block from here when requesting // help in the forums. url = "https://api.linkedin.com/v1/people/FOOBARBAZ"; request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); response = request.send(); responseNumber = response.getCode(); if (responseNumber < 200 || responseNumber >= 300) { logDiagnostics(request, response); } else { System.out.println("You were supposed to submit a bad request"); } System.out.println("******Finished******"); }
From source file:com.tc.stats.DSO.java
private static Exception newPlainException(Exception e) { String type = e.getClass().getName(); if (type.startsWith("java.") || type.startsWith("javax.")) { return e; } else {/*from w w w. j a va2 s . c o m*/ RuntimeException result = new RuntimeException(e.getMessage()); result.setStackTrace(e.getStackTrace()); return result; } }
From source file:com.oncore.calorders.core.utils.FormatHelper.java
/** * This method returns the stack trace of an exception * * @param ex The exception// w ww. jav a 2s .com * @return The stack trace in string */ public static String getStackTrace(Exception ex) { StringBuilder trace = new StringBuilder(); trace.append(ex.getClass().getCanonicalName()); trace.append("\n\t"); trace.append(ex.getMessage()); trace.append("\n"); for (StackTraceElement stackTrace : ex.getStackTrace()) { trace.append(stackTrace.toString()); trace.append("\n\t"); } return trace.toString(); }
From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java
@Deprecated protected static void saveUpdateResult(Context context, PublicScript script, long date, Exception exception) { if (PublicScript.Profil2.equals(script)) { SharedPreferences preferences = context.getSharedPreferences(ProfileProxyV1.PREFS_NAME, 0); boolean success = false; String result;/*from w w w . ja va 2s.c o m*/ if (exception == null) { result = "SUCCESS"; success = true; } else { result = exception.getClass().getName(); if (exception instanceof NetworkUnavailableException || (exception instanceof PublicScriptException && exception.getCause() != null)) { result = "NETWORK ERROR: " + result; } } SharedPreferences.Editor editor = preferences.edit(); editor.putLong("LAST_UPDATE_ATTEMPT", date); editor.putString("LAST_UPDATE_RESULT", result); if (success) { editor.putLong("LAST_UPDATE_SUCCESS", date); } editor.commit(); } }
From source file:com.wifi.brainbreaker.mydemo.spydroid.api.RequestHandler.java
/** * The implementation of all the possible requests is here * -> "sounds": returns a list of available sounds on the phone * -> "screen": returns the screen state (whether the app. is on the foreground or not) * -> "play": plays a sound on the phone * -> "set": update Spydroid's configuration * -> "get": returns Spydroid's configuration (framerate, bitrate...) * -> "state": returns a JSON containing information about the state of the application * -> "battery": returns an approximation of the battery level on the phone * -> "buzz": makes the phone buuz /*from ww w .jav a 2 s. c om*/ * -> "volume": sets or gets the volume * @throws JSONException * @throws IllegalAccessException * @throws IllegalArgumentException **/ static private void exec(JSONObject object, StringBuilder response) throws JSONException, IllegalArgumentException, IllegalAccessException { SpydroidApplication application = SpydroidApplication.getInstance(); Context context = application.getApplicationContext(); String action = object.getString("action"); // Returns a list of available sounds on the phone if (action.equals("sounds")) { Field[] raws = R.raw.class.getFields(); response.append("["); for (int i = 0; i < raws.length - 1; i++) { response.append("\"" + raws[i].getName() + "\","); } response.append("\"" + raws[raws.length - 1].getName() + "\"]"); } // Returns the screen state (whether the app. is on the foreground or not) else if (action.equals("screen")) { response.append(application.applicationForeground ? "\"1\"" : "\"0\""); } // Plays a sound on the phone else if (action.equals("play")) { Field[] raws = R.raw.class.getFields(); for (int i = 0; i < raws.length; i++) { if (raws[i].getName().equals(object.getString("name"))) { mSoundPool.load(application, raws[i].getInt(null), 0); } } response.append("[]"); } // Returns Spydroid's configuration (framerate, bitrate...) else if (action.equals("get")) { final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); response.append("{\"streamAudio\":" + settings.getBoolean("stream_audio", false) + ","); response.append("\"audioEncoder\":\"" + (application.audioEncoder == SessionBuilder.AUDIO_AMRNB ? "AMR-NB" : "AAC") + "\","); response.append("\"streamVideo\":" + settings.getBoolean("stream_video", true) + ","); response.append("\"videoEncoder\":\"" + (application.videoEncoder == SessionBuilder.VIDEO_H263 ? "H.263" : "H.264") + "\","); response.append("\"videoResolution\":\"" + application.videoQuality.resX + "x" + application.videoQuality.resY + "\","); response.append("\"videoFramerate\":\"" + application.videoQuality.framerate + " fps\","); response.append("\"videoBitrate\":\"" + application.videoQuality.bitrate / 1000 + " kbps\"}"); } // Update Spydroid's configuration else if (action.equals("set")) { final JSONObject settings = object.getJSONObject("settings"); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final Editor editor = prefs.edit(); editor.putBoolean("stream_video", settings.getBoolean("stream_video")); application.videoQuality = VideoQuality.parseQuality(settings.getString("video_quality")); editor.putInt("video_resX", application.videoQuality.resX); editor.putInt("video_resY", application.videoQuality.resY); editor.putString("video_framerate", String.valueOf(application.videoQuality.framerate)); editor.putString("video_bitrate", String.valueOf(application.videoQuality.bitrate / 1000)); editor.putString("video_encoder", settings.getString("video_encoder").equals("H.263") ? "2" : "1"); editor.putBoolean("stream_audio", settings.getBoolean("stream_audio")); editor.putString("audio_encoder", settings.getString("audio_encoder").equals("AMR-NB") ? "3" : "5"); editor.commit(); response.append("[]"); } // Returns a JSON containing information about the state of the application else if (action.equals("state")) { Exception exception = application.lastCaughtException; response.append("{"); if (exception != null) { // Used to display the message on the user interface String lastError = exception.getMessage(); // Useful to display additional information to the user depending on the error StackTraceElement[] stack = exception.getStackTrace(); StringBuilder builder = new StringBuilder( exception.getClass().getName() + " : " + lastError + "||"); for (int i = 0; i < stack.length; i++) builder.append("at " + stack[i].getClassName() + "." + stack[i].getMethodName() + " (" + stack[i].getFileName() + ":" + stack[i].getLineNumber() + ")||"); response.append("\"lastError\":\"" + (lastError != null ? lastError : "unknown error") + "\","); response.append("\"lastStackTrace\":\"" + builder.toString() + "\","); } response.append("\"activityPaused\":\"" + (application.applicationForeground ? "1" : "0") + "\""); response.append("}"); } else if (action.equals("clear")) { application.lastCaughtException = null; response.append("[]"); } // Returns an approximation of the battery level else if (action.equals("battery")) { response.append("\"" + application.batteryLevel + "\""); } // Makes the phone vibrates for 300ms else if (action.equals("buzz")) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(300); response.append("[]"); } // Sets or gets the system's volume else if (action.equals("volume")) { AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); if (object.has("set")) { audio.setStreamVolume(AudioManager.STREAM_MUSIC, object.getInt("set"), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE); response.append("[]"); } else { int max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int current = audio.getStreamVolume(AudioManager.STREAM_MUSIC); response.append("{\"max\":" + max + ",\"current\":" + current + "}"); } } }
From source file:davmail.exchange.ExchangeSessionFactory.java
private static void handleNetworkDown(Exception exc) throws DavMailException { if (!checkNetwork() || configChecked) { ExchangeSession.LOGGER.warn(BundleMessage.formatLog("EXCEPTION_NETWORK_DOWN")); // log full stack trace for unknown errors if (!((exc instanceof UnknownHostException) || (exc instanceof NetworkDownException))) { ExchangeSession.LOGGER.debug(exc, exc); }//w w w. j a v a 2 s.c o m throw new NetworkDownException("EXCEPTION_NETWORK_DOWN"); } else { BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(), exc.getMessage()); if (errorSent) { ExchangeSession.LOGGER.warn(message); throw new NetworkDownException("EXCEPTION_DAVMAIL_CONFIGURATION", message); } else { // Mark that an error has been sent so you only get one // error in a row (not a repeating string of errors). errorSent = true; ExchangeSession.LOGGER.error(message); throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message); } } }