List of usage examples for java.lang ClassCastException toString
public String toString()
From source file:com.orange.datavenue.ValueFragment.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add_value: /**//from w ww.j ava 2s . co m * Add value */ mDialog = new android.app.Dialog(getActivity()); mDialog.setContentView(R.layout.create_value_dialog); mDialog.setTitle(R.string.add_value); final EditText at = (EditText) mDialog.findViewById(R.id.at); final EditText metadata = (EditText) mDialog.findViewById(R.id.metadata); final EditText latitude = (EditText) mDialog.findViewById(R.id.latitude); final EditText longitude = (EditText) mDialog.findViewById(R.id.longitude); final EditText value = (EditText) mDialog.findViewById(R.id.value); SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); Date now = new Date(); at.setText(ISO8601DATEFORMAT.format(now)); Button addButton = (Button) mDialog.findViewById(R.id.add_button); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG_NAME, "at : " + at.getText().toString()); Log.d(TAG_NAME, "metadata : " + metadata.getText().toString()); Log.d(TAG_NAME, "value : " + value.getText().toString()); Value newValue = new Value(); newValue.setAt(at.getText().toString()); Double[] location = null; String strLatitude = latitude.getText().toString(); String strLongitude = longitude.getText().toString(); try { if ((!"".equals(strLatitude)) && (!"".equals(strLongitude))) { location = new Double[2]; location[0] = Double.parseDouble(strLatitude); location[1] = Double.parseDouble(strLongitude); } } catch (NumberFormatException e) { Log.e(TAG_NAME, e.toString()); location = null; } newValue.setLocation(location); if (!"".equals(value.getText().toString())) { try { JSONObject valueJson = (JSONObject) new JSONParser().parse(value.getText().toString()); newValue.setValue(valueJson); } catch (ParseException e) { Log.e(TAG_NAME, e.toString()); newValue.setValue(value.getText().toString()); } catch (ClassCastException ce) { Log.e(TAG_NAME, ce.toString()); newValue.setValue(value.getText().toString()); } } else { newValue.setValue(null); } if (!"".equals(metadata.getText().toString())) { try { JSONObject metadataJson = (JSONObject) new JSONParser() .parse(metadata.getText().toString()); newValue.setMetadata(metadataJson); } catch (ParseException e) { Log.e(TAG_NAME, e.toString()); newValue.setMetadata(metadata.getText().toString()); } catch (ClassCastException ce) { Log.e(TAG_NAME, ce.toString()); newValue.setMetadata(metadata.getText().toString()); } } else { newValue.setMetadata(null); } CreateValueOperation createValueOperation = new CreateValueOperation(Model.instance.oapiKey, Model.instance.key, Model.instance.currentDatasource, Model.instance.currentStream, newValue, new OperationCallback() { @Override public void process(Object object, Exception exception) { if (exception == null) { mPageNumber = 1; getValues(mPageNumber, true); } else { Errors.displayError(getActivity(), exception); } } }); createValueOperation.execute(""); mDialog.dismiss(); } }); Button cancelButton = (Button) mDialog.findViewById(R.id.cancel_button); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mDialog.dismiss(); } }); mDialog.setCancelable(false); mDialog.show(); return true; case R.id.action_add_sensor_sensor: /** * Geolocation */ mDialog = new android.app.Dialog(getActivity()); mDialog.setContentView(R.layout.add_sensor_value_dialog); mDialog.setTitle(R.string.geolocation); llInfo = (LinearLayout) mDialog.findViewById(R.id.info); llValue = (LinearLayout) mDialog.findViewById(R.id.value); llValue.setVisibility(View.GONE); tvLatitude = (TextView) mDialog.findViewById(R.id.latitude); tvLongitude = (TextView) mDialog.findViewById(R.id.longitude); if (mLocationService != null) { mLocationService.setServiceParameters(Model.instance.oapiKey, Model.instance.key, Model.instance.currentDatasource, Model.instance.currentStream); mLocationService.register(this); mLocationService.start(); } Button cButton = (Button) mDialog.findViewById(R.id.cancel_button); cButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mLocationService != null) { mLocationService.stop(); } tvLatitude = null; tvLongitude = null; mDialog.dismiss(); } }); mDialog.setCancelable(false); mDialog.show(); return true; default: break; } return false; }
From source file:com.nubits.nubot.trading.wrappers.ExcoinWrapper.java
private ApiResponse getQuery(String url) { ApiResponse apiResponse = new ApiResponse(); HashMap<String, String> query_args = new HashMap<>(); boolean isGet = true; String queryResult = query(url, "", query_args, true, isGet); if (queryResult == null) { apiResponse.setError(errors.nullReturnError); return apiResponse; }/* www. jav a 2 s .com*/ if (queryResult.equals(TOKEN_BAD_RETURN)) { apiResponse.setError(errors.noConnectionError); return apiResponse; } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) parser.parse(queryResult); if (httpAnswerJson.containsKey(TOKEN_ERR)) { String errorMessage = httpAnswerJson.get(TOKEN_ERR).toString(); ApiError apiErr = errors.apiReturnError; apiErr.setDescription(errorMessage); LOG.error("Exco.in API returned an error: " + errorMessage); apiResponse.setError(apiErr); } else { //LOG.info("httpAnswerJSON = \n" + httpAnswerJson.toJSONString()); apiResponse.setResponseObject(httpAnswerJson); } } catch (ClassCastException cce) { //if casting to a JSON object failed, try a JSON Array try { JSONArray httpAnswerJson = (JSONArray) (parser.parse(queryResult)); apiResponse.setResponseObject(httpAnswerJson); } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } catch (ClassCastException ccex) { LOG.error("httpResponse: " + queryResult + " \n" + ccex.toString()); apiResponse.setError(errors.genericError); } } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } return apiResponse; }
From source file:com.nubits.nubot.trading.wrappers.PeatioWrapper.java
private ApiResponse getQuery(String url, String method, TreeMap<String, String> query_args, boolean needAuth, boolean isGet) { //LOG.warn("\nurl: " + url + "\nmethod: " + method + "\nquery_args: " + query_args.toStringSep() + "\nisGet: " + isGet); ApiResponse apiResponse = new ApiResponse(); String queryResult = query(url, method, query_args, needAuth, isGet); //LOG.warn("\n\n" + queryResult + "\n\n"); if (queryResult == null) { apiResponse.setError(errors.nullReturnError); return apiResponse; }//from ww w . j a va 2 s . c o m if (queryResult.equals(TOKEN_BAD_RETURN)) { apiResponse.setError(errors.noConnectionError); return apiResponse; } JSONParser parser = new JSONParser(); try { //assume that a standard JSON Object is returned JSONObject httpAnswerJson = (JSONObject) (parser.parse(queryResult)); if (httpAnswerJson.containsKey("error")) { JSONObject error = (JSONObject) httpAnswerJson.get("error"); int code = Integer.parseInt(error.get("code").toString()); String msg = error.get("message").toString(); ApiError errorObj = errors.apiReturnError; errorObj.setDescription(msg); apiResponse.setError(errorObj); return apiResponse; } else { apiResponse.setResponseObject(httpAnswerJson); } } catch (ClassCastException cce) { //if casting to a JSON object failed, try a JSON Array try { JSONArray httpAnswerJson = (JSONArray) (parser.parse(queryResult)); apiResponse.setResponseObject(httpAnswerJson); } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } catch (ClassCastException ex) { LOG.error("httpResponse: " + queryResult + " \n" + ex.toString()); apiResponse.setError(errors.parseError); } } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); return apiResponse; } return apiResponse; }
From source file:at.gv.egovernment.moa.id.protocols.saml1.GetAuthenticationDataService.java
/** * Takes a <code>lt;samlp:Request></code> containing a * <code>SAML artifact</code> and returns the corresponding * authentication data <code>lt;saml:Assertion></code> * (obtained from the <code>AuthenticationServer</code>), * enclosed in a <code>lt;samlp:Response></code>. * <br/>Bad requests are mapped into various <code>lt;samlp:StatusCode></code>s, * possibly containing enclosed sub-<code>lt;samlp:StatusCode></code>s. * The status codes are defined in the SAML specification. * /*w w w .j av a 2 s.c om*/ * @param requests request elements of type <code>lt;samlp:Request></code>; * only 1 request element is allowed * @return response element of type <code>lt;samlp:Response></code>, * packed into an <code>Element[]</code> * @throws AxisFault thrown when an error occurs in assembling the * <code>lt;samlp:Response></code> */ public Element[] Request(Element[] requests) throws AxisFault { Element request = requests[0]; Element[] responses = new Element[1]; String requestID = ""; String statusCode = ""; String subStatusCode = null; String statusMessageCode = null; String statusMessage = null; String samlAssertion = ""; if (requests.length > 1) { // more than 1 request given as parameter statusCode = "samlp:Requester"; subStatusCode = "samlp:TooManyResponses"; statusMessageCode = "1201"; } else { try { DOMUtils.validateElement(request, ALL_SCHEMA_LOCATIONS, null); NodeList samlArtifactList = XPathUtils.selectNodeList(request, "samlp:AssertionArtifact"); if (samlArtifactList.getLength() == 0) { // no SAML artifact given in request statusCode = "samlp:Requester"; statusMessageCode = "1202"; } else if (samlArtifactList.getLength() > 1) { // too many SAML artifacts given in request statusCode = "samlp:Requester"; subStatusCode = "samlp:TooManyResponses"; statusMessageCode = "1203"; } else { Element samlArtifactElem = (Element) samlArtifactList.item(0); requestID = request.getAttribute("RequestID"); String samlArtifact = DOMUtils.getText(samlArtifactElem); SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace(); try { samlAssertion = saml1server.getSaml1AuthenticationData(samlArtifact); // success statusCode = "samlp:Success"; statusMessageCode = "1200"; } catch (ClassCastException ex) { try { Throwable error = saml1server.getErrorResponse(samlArtifact); statusCode = "samlp:Responder"; ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance(); if (error instanceof MOAIDException) { statusMessageCode = ((MOAIDException) error).getMessageId(); statusMessage = StringEscapeUtils.escapeXml(((MOAIDException) error).getMessage()); } else { statusMessage = StringEscapeUtils.escapeXml(error.getMessage()); } subStatusCode = errorUtils.getResponseErrorCode(error); } catch (Exception e) { //no authentication data for given SAML artifact statusCode = "samlp:Requester"; subStatusCode = "samlp:ResourceNotRecognized"; statusMessage = ex.toString(); } } catch (AuthenticationException ex) { //no authentication data for given SAML artifact statusCode = "samlp:Requester"; subStatusCode = "samlp:ResourceNotRecognized"; statusMessage = ex.toString(); } } } catch (Throwable t) { // invalid request format statusCode = "samlp:Requester"; statusMessageCode = "1204"; } } try { String responseID = Random.nextRandom(); String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar.getInstance()); if (statusMessage == null) statusMessage = MOAIDMessageProvider.getInstance().getMessage(statusMessageCode, null); responses[0] = new SAMLResponseBuilder().build(responseID, requestID, issueInstant, statusCode, subStatusCode, statusMessage, samlAssertion); } catch (MOAIDException e) { AxisFault fault = AxisFault.makeFault(e); fault.setFaultDetail(new Element[] { e.toErrorResponse() }); throw fault; } catch (Throwable t) { MOAIDException e = new MOAIDException("1299", null, t); AxisFault fault = AxisFault.makeFault(e); fault.setFaultDetail(new Element[] { e.toErrorResponse() }); throw fault; } return responses; }
From source file:com.xorcode.andtweet.TweetListActivity.java
@Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info; try {//from w ww .j ava 2 s. c o m info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } mCurrentId = info.id; Uri uri; Cursor c; switch (item.getItemId()) { case CONTEXT_MENU_ITEM_REPLY: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID }, null, null, null); try { c.moveToFirst(); String reply = "@" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; long replyId = c.getLong(c.getColumnIndex(Tweets._ID)); mTweetEditor.startEditing(reply, replyId); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_RETWEET: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder message = new StringBuilder(); String reply = "RT @" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + " "; message.append(reply); CharSequence text = c.getString(c.getColumnIndex(Tweets.MESSAGE)); int len = 140 - reply.length() - 3; if (text.length() < len) { len = text.length(); } message.append(text, 0, len); if (message.length() == 137) { message.append("..."); } mTweetEditor.startEditing(message.toString(), 0); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_DESTROY_STATUS: sendCommand(new CommandData(CommandEnum.DESTROY_STATUS, mCurrentId)); return true; case CONTEXT_MENU_ITEM_FAVORITE: sendCommand(new CommandData(CommandEnum.CREATE_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_DESTROY_FAVORITE: sendCommand(new CommandData(CommandEnum.DESTROY_FAVORITE, mCurrentId)); return true; case CONTEXT_MENU_ITEM_SHARE: uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.AUTHOR_ID, Tweets.MESSAGE }, null, null, null); try { c.moveToFirst(); StringBuilder subject = new StringBuilder(); StringBuilder text = new StringBuilder(); String message = c.getString(c.getColumnIndex(Tweets.MESSAGE)); subject.append(getText(R.string.button_create_tweet)); subject.append(" - " + message); int maxlength = 80; if (subject.length() > maxlength) { subject.setLength(maxlength); // Truncate at the last space subject.setLength(subject.lastIndexOf(" ")); subject.append("..."); } text.append(message); text.append("\n-- \n" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID))); text.append("\n URL: " + "http://twitter.com/" + c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)) + "/status/" + c.getString(c.getColumnIndex(Tweets._ID))); Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); share.putExtra(Intent.EXTRA_TEXT, text.toString()); startActivity(Intent.createChooser(share, getText(R.string.menu_item_share))); } catch (Exception e) { Log.e(TAG, "onContextItemSelected: " + e.toString()); return false; } finally { if (c != null && !c.isClosed()) c.close(); } return true; case CONTEXT_MENU_ITEM_UNFOLLOW: case CONTEXT_MENU_ITEM_BLOCK: case CONTEXT_MENU_ITEM_DIRECT_MESSAGE: case CONTEXT_MENU_ITEM_PROFILE: Toast.makeText(this, R.string.unimplemented, Toast.LENGTH_SHORT).show(); return true; } return false; }
From source file:com.nubits.nubot.trading.wrappers.BterWrapper.java
private ApiResponse getQuery(String url, HashMap<String, String> query_args, boolean needAuth, boolean isGet) { ApiResponse apiResponse = new ApiResponse(); String queryResult = query(url, "", query_args, needAuth, isGet); if (queryResult == null) { apiResponse.setError(errors.nullReturnError); return apiResponse; }// www . j a v a2 s . c o m if (queryResult.equals(TOKEN_BAD_RETURN)) { apiResponse.setError(errors.noConnectionError); return apiResponse; } if (queryResult.contains(TOKEN_ERROR_HTML_405)) { ApiError error = errors.apiReturnError; error.setDescription("BTER returned http error 405 - method not allowed"); apiResponse.setError(error); return apiResponse; } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(queryResult)); boolean valid; try { valid = Boolean.parseBoolean((String) httpAnswerJson.get("result")); } catch (ClassCastException e) { valid = true; //hack due to bter returning "false" and false at times, depending on the err try { valid = (boolean) httpAnswerJson.get("result"); } catch (ClassCastException ex) { valid = true; } } if (!valid) { String errorMessage = ""; if (httpAnswerJson.containsKey("message")) { errorMessage = (String) httpAnswerJson.get("message"); } else if (httpAnswerJson.containsKey("msg")) { errorMessage = (String) httpAnswerJson.get("msg"); } ApiError apiErr = errors.apiReturnError; apiErr.setDescription(errorMessage); apiResponse.setError(apiErr); } else { apiResponse.setResponseObject(httpAnswerJson); } } catch (ClassCastException cce) { //if casting to a JSON object failed, try a JSON Array try { JSONArray httpAnswerJson = (JSONArray) (parser.parse(queryResult)); apiResponse.setResponseObject(httpAnswerJson); } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } } catch (ParseException ex) { LOG.error("httpresponse: " + queryResult + " \n" + ex.toString()); apiResponse.setError(errors.parseError); return apiResponse; } return apiResponse; }
From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java
/** * Return the data stored in the cursor at the given index and given position * (ie the given row which the cursor is currently on) as null OR whatever * data type it is./*from w w w . j a v a 2 s .c o m*/ * <p> * This does not actually convert data types from one type to the other. * Instead, it safely preserves null values and returns boxed data values. If * you specify ArrayList or HashMap, it JSON deserializes the value into one * of those. * * @param c * @param clazz * @param i * @return */ @SuppressLint("NewApi") public final <T> T getIndexAsType(Cursor c, Class<T> clazz, int i) { // If you add additional return types here be sure to modify the javadoc. try { if (i == -1) return null; if (c.isNull(i)) { return null; } if (clazz == Long.class) { Long l = c.getLong(i); return (T) l; } else if (clazz == Integer.class) { Integer l = c.getInt(i); return (T) l; } else if (clazz == Double.class) { Double d = c.getDouble(i); return (T) d; } else if (clazz == String.class) { String str = c.getString(i); return (T) str; } else if (clazz == Boolean.class) { // stored as integers Integer l = c.getInt(i); return (T) Boolean.valueOf(l != 0); } else if (clazz == ArrayList.class) { // json deserialization of an array String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, ArrayList.class); } else if (clazz == HashMap.class) { // json deserialization of an object String str = c.getString(i); return (T) ODKFileUtils.mapper.readValue(str, HashMap.class); } else { throw new IllegalStateException("Unexpected data type in SQLite table"); } } catch (ClassCastException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " in SQLite table "); } catch (JsonParseException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (JsonMappingException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException( "Unexpected data type conversion failure " + e.toString() + " on SQLite table"); } }
From source file:edu.harvard.i2b2.fhir.server.ws.I2b2FhirWS.java
@POST @Path("{resourceName:" + FhirUtil.RESOURCE_LIST_REGEX + "}/$validate") @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, "application/xml+fhir", "application/json+fhir" }) public Response validate(@PathParam("resourceName") String resourceName, @HeaderParam("accept") String acceptHeader, @Context HttpServletRequest request, String inTxt, String profile) throws IOException, URISyntaxException, ParserConfigurationException, SAXException, FhirServerException, JAXBException { HttpSession session = request.getSession(); String mediaType;//from w w w. j a va 2s . c o m Parameters ps = null; String resourceTxt = null; Resource r = null; String outTxt = "-"; logger.trace("will run validator"); try { Class resourceClass = FhirUtil.getResourceClass(resourceName); try { ps = JAXBUtil.fromXml(inTxt, Parameters.class); if (ps != null) { for (ParametersParameter p : ps.getParameter()) { logger.trace("pname:" + p.getName().getValue()); } } else { logger.trace("ps is null"); } } catch (ClassCastException e) { } if (ps == null) { resourceTxt = inTxt; try { r = JAXBUtil.fromXml(resourceTxt, resourceClass); } catch (JAXBException e) { Throwable e2 = e.getLinkedException(); throw new FhirServerException(e2.getMessage(), e2); } logger.trace( "could transform to" + resourceClass.getSimpleName() + "\n" + r.getClass().getSimpleName()); } else { for (ParametersParameter p : ps.getParameter()) { logger.trace("getting pname:" + p.getName().getValue()); if (p.getName().getValue().equals("resource")) { r = FhirUtil.getResourceFromContainer(p.getResource()); resourceTxt = JAXBUtil.toXml(r); } } if (r == null) { String msg = "Resource was not specified correctly in the Parameters"; logger.warn(msg); throw new FhirServerException(msg); } } if (!r.getClass().getSimpleName().equals(resourceClass.getSimpleName())) { String msg = "The input is not an instance of class:" + resourceClass; logger.warn(msg); throw new FhirServerException(msg); } outTxt = Validate.runValidate(resourceTxt, profile); } catch (Exception e) { logger.error(e.getLocalizedMessage(), e); return generateResponse(acceptHeader, request, FhirHelper.generateOperationOutcome(e.toString(), IssueTypeList.EXCEPTION, IssueSeverityList.FATAL)); } Resource rOut = JAXBUtil.fromXml(outTxt, OperationOutcome.class); return generateResponse(acceptHeader, request, rOut); }
From source file:com.xorcode.andtweet.TweetListActivity.java
@Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, view, menuInfo); // Get the adapter context menu information AdapterView.AdapterContextMenuInfo info; try {//from ww w . j a va 2 s. co m info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } int m = 0; // Add menu items menu.add(0, CONTEXT_MENU_ITEM_REPLY, m++, R.string.menu_item_reply); menu.add(0, CONTEXT_MENU_ITEM_RETWEET, m++, R.string.menu_item_retweet); menu.add(0, CONTEXT_MENU_ITEM_SHARE, m++, R.string.menu_item_share); // menu.add(0, CONTEXT_MENU_ITEM_DIRECT_MESSAGE, m++, // R.string.menu_item_direct_message); // menu.add(0, CONTEXT_MENU_ITEM_UNFOLLOW, m++, // R.string.menu_item_unfollow); // menu.add(0, CONTEXT_MENU_ITEM_BLOCK, m++, R.string.menu_item_block); // menu.add(0, CONTEXT_MENU_ITEM_PROFILE, m++, // R.string.menu_item_view_profile); // Get the record for the currently selected item Uri uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id); Cursor c = getContentResolver().query(uri, new String[] { Tweets._ID, Tweets.MESSAGE, Tweets.AUTHOR_ID, Tweets.FAVORITED }, null, null, null); try { c.moveToFirst(); menu.setHeaderTitle(c.getString(c.getColumnIndex(Tweets.MESSAGE))); if (c.getInt(c.getColumnIndex(Tweets.FAVORITED)) == 1) { menu.add(0, CONTEXT_MENU_ITEM_DESTROY_FAVORITE, m++, R.string.menu_item_destroy_favorite); } else { menu.add(0, CONTEXT_MENU_ITEM_FAVORITE, m++, R.string.menu_item_favorite); } if (MyPreferences.getDefaultSharedPreferences().getString(MyPreferences.KEY_TWITTER_USERNAME, null) .equals(c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)))) { menu.add(0, CONTEXT_MENU_ITEM_DESTROY_STATUS, m++, R.string.menu_item_destroy_status); } } catch (Exception e) { Log.e(TAG, "onCreateContextMenu: " + e.toString()); } finally { if (c != null && !c.isClosed()) c.close(); } }
From source file:org.metacsp.utility.UI.FiniteStateAutomatonFrame.java
public FiniteStateAutomatonFrame(ObservableGraph<String[], Interval> graph) { super("Constraint Network"); g = graph;/* w w w . j a va 2 s . c o m*/ g.addGraphEventListener(new GraphEventListener<String[], Interval>() { public void handleGraphEvent(GraphEvent<String[], Interval> evt) { System.err.println("got " + evt); /****/ vv.getRenderContext().getPickedVertexState().clear(); vv.getRenderContext().getPickedEdgeState().clear(); try { layout.initialize(); try { Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); } catch (java.lang.ClassCastException e) { } StaticLayout<String[], Interval> staticLayout = new StaticLayout<String[], Interval>(g, layout); LayoutTransition<String[], Interval> lt = new LayoutTransition<String[], Interval>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } catch (Exception e) { System.out.println(e); } /****/ } }); //create a graphdraw //layout = new FRLayout<State,Interval>(g); //layout = new SpringLayout<State,Interval>(g); //layout = new StaticLayout<State,Interval>(g,new STNTransformer()); layout = new FRLayout2<String[], Interval>(g); //layout = new CircleLayout<State,Interval>(g); //layout = new ISOMLayout<State,Interval>(g); //layout = new KKLayout<State,Interval>(g); layout.setSize(new Dimension(600, 600)); try { Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); } catch (java.lang.ClassCastException e) { } Layout<String[], Interval> staticLayout = new StaticLayout<String[], Interval>(g, layout); vv = new VisualizationViewer<String[], Interval>(staticLayout, new Dimension(600, 600)); JRootPane rp = this.getRootPane(); rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE); getContentPane().setLayout(new BorderLayout()); getContentPane().setBackground(java.awt.Color.lightGray); getContentPane().setFont(new Font("Serif", Font.PLAIN, 12)); vv.setGraphMouse(new DefaultModalGraphMouse<String[], Interval>()); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.S); vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String[]>()); vv.setForeground(Color.black); //draw edge labels Transformer<Interval, String> stringer = new Transformer<Interval, String>() { public String transform(Interval e) { return e.toString(); } }; vv.getRenderContext().setEdgeLabelTransformer(stringer); vv.getRenderContext().setEdgeDrawPaintTransformer( new PickableEdgePaintTransformer<Interval>(vv.getPickedEdgeState(), Color.black, Color.cyan)); vv.addComponentListener(new ComponentAdapter() { /** * @see java.awt.event.ComponentAdapter#componentResized(java.awt.event.ComponentEvent) */ @Override public void componentResized(ComponentEvent arg0) { super.componentResized(arg0); System.err.println("resized"); layout.setSize(arg0.getComponent().getSize()); } }); getContentPane().add(vv); switchLayout = new JButton("Switch to SpringLayout"); switchLayout.addActionListener(new ActionListener() { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent ae) { Dimension d = vv.getSize();//new Dimension(600,600); if (switchLayout.getText().indexOf("Spring") > 0) { switchLayout.setText("Switch to FRLayout"); //layout = new SpringLayout<State,Interval>(g, new ConstantTransformer(EDGE_LENGTH)); layout = new SpringLayout<String[], Interval>(g); layout.setSize(d); try { Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); } catch (java.lang.ClassCastException e) { } StaticLayout<String[], Interval> staticLayout = new StaticLayout<String[], Interval>(g, layout); LayoutTransition<String[], Interval> lt = new LayoutTransition<String[], Interval>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } else { switchLayout.setText("Switch to SpringLayout"); layout = new FRLayout<String[], Interval>(g, d); layout.setSize(d); try { Relaxer relaxer = new VisRunner((IterativeContext) layout); relaxer.stop(); relaxer.prerelax(); } catch (java.lang.ClassCastException e) { } StaticLayout<String[], Interval> staticLayout = new StaticLayout<String[], Interval>(g, layout); LayoutTransition<String[], Interval> lt = new LayoutTransition<String[], Interval>(vv, vv.getGraphLayout(), staticLayout); Animator animator = new Animator(lt); animator.start(); // vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.repaint(); } } }); getContentPane().add(switchLayout, BorderLayout.SOUTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.pack(); this.setVisible(true); }