List of usage examples for java.lang ClassCastException printStackTrace
public void printStackTrace()
From source file:com.ninetwozero.battlelog.fragments.ForumThreadFragment.java
@Override public boolean onContextItemSelected(MenuItem item) { // Declare... AdapterView.AdapterContextMenuInfo info; // Let's try to get some menu information via a try/catch try {/*w ww. j av a 2 s . c om*/ info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { e.printStackTrace(); return false; } try { // Let's get the item ForumPostData data = (ForumPostData) info.targetView.getTag(); // Divide & conquer if (item.getGroupId() == 0) { // REQUESTS switch (item.getItemId()) { case 0: startActivity( new Intent(context, ProfileActivity.class).putExtra("profile", data.getProfileData())); break; case 1: Toast.makeText(context, R.string.info_forum_quote_warning, Toast.LENGTH_SHORT).show(); textareaContent.setText( textareaContent.getText().insert( textareaContent.getSelectionStart(), Constants.BBCODE_TAG_QUOTE_IN.replace( "{number}", data.getPostId() + "" ).replace( "{username}", data.getProfileData().getUsername() ) ) ); selectedQuotes.put(data.getPostId(), (data.isCensored() ? getString(R.string.general_censored) : data.getContent())); break; case 2: generatePopupWithLinks(data.getContent()); break; case 3: startActivity( new Intent(context, ForumReportActivity.class).putExtra("postId", data.getPostId())); break; default: Toast.makeText(context, R.string.msg_unimplemented, Toast.LENGTH_SHORT).show(); break; } } } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
From source file:com.pastekit.twist.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall// w w w .ja v a 2 s . c o m * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwistException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }
From source file:com.hunchee.twist.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall/*from w w w .j a va2 s. co m*/ * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Blob) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Enum) { String enumValue = fieldValue.toString(); LOG.info("Enum marshalled as \"" + enumValue + "\""); setProperty(e, fieldName, enumValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwistException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(Enum.class)) { throw new RuntimeException("Enum primitive type not yet implemented"); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }
From source file:com.dotweblabs.twirl.gae.GaeMarshaller.java
/** * * Create entity objects that can be persisted into the GAE Datastore, * including its Parent-Child relationships (if necessary). * * @param parent parent of the generated entity or Entities * @param instance to marshall/* ww w .j a v a2 s. com*/ * @return */ @Override public IdentityHashMap marshall(Key parent, Object instance) { if (instance == null) { throw new RuntimeException("Object cannot be null"); } Entity e = null; // Its possible that a Entity to be saved without id and just a parent key if (parent != null && hasNoIdField(instance)) { String kind = getKindOf(instance); e = new Entity(kind, parent); } else { Key key = createKeyFrom(parent, instance); // inspect kind and create key e = new Entity(key); } boolean indexed = !AnnotationUtil.isClassAnnotated(GaeObjectStore.unIndexed(), instance); Map<String, Object> props = new LinkedHashMap<String, Object>(); List<Entity> target = null; // Marshall java.util.Map if (instance instanceof Map) { Map map = (Map) instance; if (String.class.getName().equals(MapHelper.getKeyType(map))) { Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); String entryKey = entry.getKey(); Object entryVal = entry.getValue(); if (!entryKey.equals(GaeObjectStore.KEY_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.KIND_RESERVED_PROPERTY) && !entryKey.equals(GaeObjectStore.NAMESPACE_RESERVED_PROPERTY)) { if (entryVal instanceof Map) { setProperty(e, entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { setProperty(e, entryKey, createEmbeddedEntityFromList((List) entryVal), indexed); } else { setProperty(e, entryKey, entryVal, indexed); } } } } else { throw new RuntimeException( String.class.getName() + " is the only supported " + Map.class.getName() + " key"); } } else { // Marshall all other object types Field[] fields = instance.getClass().getDeclaredFields(); GeoPt geoPt = null; for (Field field : fields) { if (target == null) { target = new LinkedList<Entity>(); } if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) { // do nothing for a final field // usually static UID fields continue; } String fieldName = field.getName(); if (field.isAnnotationPresent(GaeObjectStore.key())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.objectId())) { // skip continue; } else if (field.isAnnotationPresent(GaeObjectStore.kind())) { // skip continue; } else if (field.isAnnotationPresent(Volatile.class)) { // skip continue; } try { boolean isAccessible = field.isAccessible(); field.setAccessible(true); Class<?> fieldType = field.getType(); Object fieldValue = field.get(instance); if (fieldValue == null) { e.setProperty(fieldName, null); } else if (fieldValue instanceof String) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Number || fieldValue instanceof Long || fieldValue instanceof Integer || fieldValue instanceof Short) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Boolean) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Date) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof User) { // GAE support this type setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Blob) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof List) { LOG.debug("Processing List valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromList((List) fieldValue), indexed); } else { boolean supported = true; List list = (List) fieldValue; for (Object item : list) { if (!GAE_SUPPORTED_TYPES.contains(item.getClass())) { supported = false; } } if (supported) { setProperty(e, fieldName, fieldValue, indexed); } else { throw new RuntimeException("List should only include GAE supported types " + GAE_SUPPORTED_TYPES + " otherwise annotate the List with @Embedded"); } } } else if (fieldValue instanceof GeoPt) { setProperty(e, fieldName, fieldValue, indexed); } else if (fieldValue instanceof Enum) { String enumValue = fieldValue.toString(); LOG.info("Enum marshalled as \"" + enumValue + "\""); setProperty(e, fieldName, enumValue, indexed); } else if (fieldValue instanceof Map) { LOG.debug("Processing Map valueType"); if (field.isAnnotationPresent(Embedded.class)) { setProperty(e, fieldName, createEmbeddedEntityFromMap((Map) fieldValue), indexed); } else if (field.isAnnotationPresent(Flat.class)) { Map<String, Object> flat = (Map) fieldValue; Iterator<Map.Entry<String, Object>> it = flat.entrySet().iterator(); if (!it.hasNext()) { LOG.debug("Iterator is empty"); } while (it.hasNext()) { Object entry = it.next(); try { Map.Entry<Object, Object> mapEntry = (Map.Entry<Object, Object>) entry; Object entryKey = mapEntry.getKey(); Object entryVal = mapEntry.getValue(); if (entryVal == null) { setProperty(e, (String) entryKey, null, indexed); } else if (entryVal instanceof Map) { setProperty(e, (String) entryKey, createEmbeddedEntityFromMap((Map) entryVal), indexed); } else if (entryVal instanceof List) { throw new RuntimeException("List values are not yet supported"); } else if (entryVal instanceof String || entryVal instanceof Number || entryVal instanceof Boolean || entryVal instanceof Date || entryVal instanceof User || entryVal instanceof EmbeddedEntity) { setProperty(e, (String) entryKey, entryVal, indexed); } else { throw new RuntimeException( "Unsupported GAE property type: " + entryVal.getClass().getName()); } if (e == null) { throw new RuntimeException("Entity is null"); } } catch (ClassCastException ex) { // Something is wrong here ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } } else { throw new TwirlException("Map type should be annotated with @Embedded or @Flat"); } } else { // For primitives if (fieldType.equals(int.class)) { int i = (Integer) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(boolean.class)) { boolean i = (Boolean) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte i = (Byte) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(short.class)) { short i = (Short) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(long.class)) { long i = (Long) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(float.class)) { float i = (Float) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(double.class)) { double i = (Double) fieldValue; setProperty(e, fieldName, i, indexed); } else if (fieldType.equals(byte.class)) { byte b = (byte) fieldValue; Blob blob = new Blob(new byte[b]); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(byte[].class)) { byte[] bytes = (byte[]) fieldValue; Blob blob = new Blob(bytes); setProperty(e, fieldName, blob, indexed); } else if (fieldType.equals(Enum.class)) { throw new RuntimeException("Enum primitive type not yet implemented"); } else { // POJO if (field.isAnnotationPresent(Embedded.class)) { Map<String, Object> map = createMapFrom(fieldValue); EmbeddedEntity ee = createEmbeddedEntityFromMap(map); setProperty(e, fieldName, ee, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.parent())) { // @Parent first before @Child, don't switch. @Child needs parent Key. if (field.getType().equals(Key.class)) { // skip it continue; } else { if (parent != null) { // Case where a Parent entity is marshalled then during the // iteration process, a @Child entity is found Entity _target = new Entity(createKeyFrom(parent, instance)); _target.setPropertiesFrom(e); e = _target; } else { // Case where a Child entity is first marshalled // at this point this child is not yet in the stack // and the Parent entity is not yet also in the stack // so we will create a Key from the "not yet marshalled" parent instance // or is it not? Let's check. Object parentField = field.get(instance); Entity parentEntity = stack.get(parentField); if (parentEntity != null) { Entity _target = new Entity( createKeyFrom(parentEntity.getKey(), instance)); _target.setPropertiesFrom(e); e = _target; } else { Key generatedParentKey = createKeyFrom(null, parentField); Entity _target = new Entity( createKeyFrom(generatedParentKey, instance)); _target.setPropertiesFrom(e); e = _target; marshall(null, parentField); } } } } else if (field.isAnnotationPresent(GaeObjectStore.child())) { Object childField = field.get(instance); marshall(e.getKey(), childField); Entity childEntity = stack.get(childField); Key childEntityKey = childEntity.getKey(); setProperty(e, fieldName, childEntityKey, indexed); } else if (field.isAnnotationPresent(GaeObjectStore.ancestor())) { // already processed above, skip it } else { throw new RuntimeException( "POJO's must be annotated with @Embedded, @Parent or @Child annotations for field " + fieldName); } } } field.setAccessible(isAccessible); } catch (IllegalAccessException ex) { ex.printStackTrace(); } } } stack.put(instance, e); return stack; }
From source file:no.ntnu.okse.protocol.wsn.WSNotificationServer.java
public InternalMessage sendMessage(InternalMessage message) { // Fetch the requestInformation from the message, and extract the endpoint RequestInformation requestInformation = message.getRequestInformation(); String endpoint = requestInformation.getEndpointReference(); /* If we have nowhere to send the message */ if (endpoint == null) { log.error("Endpoint reference not set"); totalErrors.incrementAndGet();/*from w w w . j a v a2s .com*/ return new InternalMessage(InternalMessage.STATUS_FAULT, null); } /* Create the actual http-request*/ org.eclipse.jetty.client.api.Request request = _client .newRequest(requestInformation.getEndpointReference()); request.timeout(connectionTimeout, TimeUnit.SECONDS); /* Try to send the message */ try { /* Raw request */ if ((message.statusCode & InternalMessage.STATUS_HAS_MESSAGE) == 0) { request.method(HttpMethod.GET); log.debug("Sending message without content to " + requestInformation.getEndpointReference()); ContentResponse response = request.send(); totalRequests.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); /* Request with message */ } else { // Set proper request method request.method(HttpMethod.POST); // If the statusflag has set a message and it is not an input stream if ((message.statusCode & InternalMessage.STATUS_MESSAGE_IS_INPUTSTREAM) == 0) { log.error("sendMessage(): " + "The message contained something else than an inputStream." + "Please convert your message to an InputStream before calling this methbod."); return new InternalMessage( InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } else { // Check if we should have had a message, but there was none if (message.getMessage() == null) { log.error("No content was found to send"); totalErrors.incrementAndGet(); return new InternalMessage( InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } // Send the request to the specified endpoint reference log.info("Sending message with content to " + requestInformation.getEndpointReference()); InputStream msg = (InputStream) message.getMessage(); request.content(new InputStreamContentProvider(msg), "application/soap+xml; charset=utf-8"); ContentResponse response = request.send(); totalMessagesSent.incrementAndGet(); // Check what HTTP status we received, if is not A-OK, flag the internalmessage as fault // and make the response content the message of the InternalMessage returned if (!HttpStatus.isSuccess(response.getStatus())) { totalBadRequests.incrementAndGet(); return new InternalMessage( InternalMessage.STATUS_FAULT | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); } else { return new InternalMessage(InternalMessage.STATUS_OK | InternalMessage.STATUS_HAS_MESSAGE, response.getContentAsString()); } } } } catch (ClassCastException e) { log.error("sendMessage(): The message contained something else than an inputStream." + "Please convert your message to an InputStream before calling this method."); totalErrors.incrementAndGet(); return new InternalMessage(InternalMessage.STATUS_FAULT | InternalMessage.STATUS_FAULT_INVALID_PAYLOAD, null); } catch (Exception e) { totalErrors.incrementAndGet(); e.printStackTrace(); log.error("sendMessage(): Unable to establish connection: " + e.getMessage()); return new InternalMessage(InternalMessage.STATUS_FAULT_INTERNAL_ERROR, null); } }
From source file:org.starnub.starnubserver.pluggable.PluggableManager.java
private PluggableReturn loadPluggable(String unloadedPluggableName, UnloadedPluggable unloadedPluggable, boolean enable) { Pluggable pluggable;/*from w w w .ja va 2s . c o m*/ PluggableType pluggableType = unloadedPluggable.getDetails().getTYPE(); String type = unloadedPluggable.getDetails().getTypeString(); try { if (pluggableType == PluggableType.PLUGIN) { pluggable = unloadedPluggable.instantiatePluggable(PluggableType.PLUGIN); } else { pluggable = unloadedPluggable.instantiatePluggable(PluggableType.COMMAND); } } catch (ClassCastException e) { return classCastFailure(type, e, unloadedPluggable); } catch (IOException e) { return pluggableIOError(type, e, unloadedPluggable); } catch (ClassNotFoundException e) { return classNotFoundError(type, e, unloadedPluggable); } catch (DirectoryCreationFailed e) { return directoryCreationError(type, e, unloadedPluggable); } catch (InstantiationException e) { return instantiateError(type, e, unloadedPluggable); } catch (MissingData e) { return missingDataError(type, e, unloadedPluggable); } catch (IllegalAccessException e) { return illegalAccessError(type, e, unloadedPluggable); } PluggableReturn pluggableReturn; String lowerCaseName = unloadedPluggableName.toLowerCase(); if (enable) { try { pluggable.enable(); } catch (Exception e) { e.printStackTrace(); return pluggableEnableError(type, unloadedPluggable); } } boolean containsKey; if (pluggableType == PluggableType.PLUGIN) { containsKey = PLUGINS.containsKey(lowerCaseName); } else { containsKey = COMMANDS.containsKey(lowerCaseName); } if (!unloadedPluggable.isUpdating() && containsKey) { return failNewerVersion(type, unloadedPluggable); } else if (unloadedPluggable.isUpdating()) { Pluggable remove; if (pluggableType == PluggableType.PLUGIN) { remove = PLUGINS.remove(lowerCaseName); } else { remove = COMMANDS.remove(lowerCaseName); } remove.disable(); pluggableReturn = pluggableUpdated(type, pluggable); } else { pluggableReturn = pluggableLoaded(type, pluggable); } if (pluggableType == PluggableType.PLUGIN) { PLUGINS.put(lowerCaseName, (Plugin) pluggable); } else { COMMANDS.put(lowerCaseName, (Command) pluggable); } return pluggableReturn; }
From source file:structure.Index.java
/** * * @param ontologyPath/*from w ww . j ava 2s .c o m*/ * @param indexPath * @param descriptorPath * @param gFormat * @param basename * @param IDGetterPath * @throws SLIB_Ex_Critic */ public void init(String ontologyPath, String descriptorPath, String indexPath, GFormat gFormat, String basename) throws SLIB_Ex_Critic { if (engineManager == null) { try { engineManager = USI_IO.loadGraph(ontologyPath, descriptorPath, gFormat, basename); if (!indexPath.equals("")) { byte[] encoded = Files.readAllBytes(Paths.get(indexPath)); String indexJson = Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString(); // Root Object obj = JSONValue.parse(indexJson); JSONObject json = (JSONObject) obj; // Index object = array Object indexObj = json.get("index"); JSONArray arrayOfDocuments = (JSONArray) indexObj; // Get all element and index them for (int j = 0; j < arrayOfDocuments.size(); j++) { JSONObject docObj = (JSONObject) arrayOfDocuments.get(j); String href = (String) docObj.get("href"); String title = (String) docObj.get("title"); String id; try { id = "D_" + (Long) docObj.get("id"); } catch (java.lang.ClassCastException e) { id = (String) docObj.get("id"); } JSONArray annotation = (JSONArray) docObj.get("conceptIds"); Set<URI> conceptSet = new HashSet(); for (int k = 0; k < annotation.size(); k++) { String base = engineManager.getEngine().getGraph().getURI().stringValue(); if (!base.endsWith("/") && !base.endsWith(".")) base += "/"; URI toAdd = URIFactoryMemory.getSingleton().getURI(base + (String) annotation.get(k)); if (!toAdd.getLocalName().equals(getEngineManager().getFromURI(toAdd))) conceptSet.add(toAdd); } Entity en = new Entity(); en.setId(id); en.setTitle(title); en.setHref(href); en.setConcepts(conceptSet); addEntity(en); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.zoho.creator.jframework.JSONParser.java
static List<ZCChoice> parseCrmLeadModule(List<ZCChoice> choices, JSONObject rowArrayObj) { try {//from w w w . jav a2 s .c o m String leadID = ""; String frstName = ""; String lastName = ""; String smCreatorId = ""; String modifiedById = ""; List<ZCRecordValue> recordValues = new ArrayList<ZCRecordValue>(); if (rowArrayObj.has("no")) { rowArrayObj.getInt("no");//No I18N } if (rowArrayObj.has("FL")) { try { JSONArray flArray = (JSONArray) rowArrayObj.get("FL"); for (int j = 0; j < flArray.length(); j++) { JSONObject flArrayObj = (JSONObject) flArray.get(j); ZCRecordValue recordValue = null; if (flArrayObj.has("content")) { if (flArrayObj.has("val")) { if (flArrayObj.getString("val").equals("LEADID")) { leadID = flArrayObj.getString("content"); } else if (flArrayObj.getString("val").equals("First Name")) { frstName = flArrayObj.getString("content"); } else if (flArrayObj.getString("val").equals("Last Name")) { lastName = flArrayObj.getString("content"); } else if (!(flArrayObj.getString("val").equals("SMOWNERID")) && (!(flArrayObj.getString("val").equals("SMCREATORID"))) && (!(flArrayObj.getString("val").equals("MODIFIEDBY")))) { recordValue = new ZCRecordValue(new ZCField(flArrayObj.getString("val"), FieldType.SINGLE_LINE, flArrayObj.getString("val")), flArrayObj.getString("content")); } } } if (recordValue != null) { recordValues.add(recordValue); } } } catch (ClassCastException e) { } } if (frstName != null) { choices.add(new ZCChoice(recordValues, Long.valueOf(leadID), leadID, frstName + " " + lastName)); } else { choices.add(new ZCChoice(recordValues, Long.valueOf(leadID), leadID, lastName)); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return choices; }
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 ww 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:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java
private void updateCodeTemplateNode(CodeTemplateTreeTableNode codeTemplateNode) { if (codeTemplateNode != null) { codeTemplateNode.setValueAt(templateTypeComboBox.getSelectedItem(), TEMPLATE_TYPE_COLUMN); codeTemplateNode.getCodeTemplate().setCode(templateCodeTextArea.getText()); CodeTemplateContextSet contextSet = new CodeTemplateContextSet(); for (Enumeration<? extends MutableTreeTableNode> groups = ((MutableTreeTableNode) templateContextTreeTable .getTreeTableModel().getRoot()).children(); groups.hasMoreElements();) { MutableTreeTableNode group = groups.nextElement(); for (Enumeration<? extends MutableTreeTableNode> children = group.children(); children .hasMoreElements();) { Pair<Integer, ContextType> pair = (Pair<Integer, ContextType>) children.nextElement() .getUserObject(); if (pair.getLeft() == MirthTriStateCheckBox.CHECKED) { try { contextSet.add(pair.getRight()); } catch (ClassCastException e) { e.printStackTrace(); }/* w ww .jav a 2 s . c o m*/ } } } codeTemplateNode.getCodeTemplate().setContextSet(contextSet); } }