private void readSoapEnvelopeEnd(XmlInputStream xin) throws IOException, ConnectionException { xin.nextTag(); typeMapper.verifyTag(Constants.SOAP_ENVELOPE_NS, "Body", xin.getNamespace(), xin.getName()); xin.nextTag(); typeMapper.verifyTag(Constants.SOAP_ENVELOPE_NS, "Envelope", xin.getNamespace(), xin.getName()); }
private XMLizable bind(XmlInputStream xin, QName responseElement, Class responseType) throws IOException, ConnectionException { readSoapEnvelopeStart(xin); xin.peekTag(); typeMapper.verifyTag( responseElement.getNamespaceURI(), responseElement.getLocalPart(), xin.getNamespace(), xin.getName()); // todo: change responseElement to typeInfo. TypeInfo info = new TypeInfo( responseElement.getNamespaceURI(), responseElement.getLocalPart(), null, null, 1, 1, true); XMLizable result = (XMLizable) typeMapper.readObject(xin, info, responseType); readSoapEnvelopeEnd(xin); return result; }
void createSchema(SQLiteDatabase db) { StringBuilder b = new StringBuilder(); b.append("CREATE TABLE IF NOT EXISTS " + mTableName + " ("); int len = mFields.size(); for (int i = 0; i < len; i++) { String colName = mColumnNames.get(i); // Without this we'll add overriden fields twice... b.append(colName); b.append(" "); b.append(TypeMapper.sqlType(mFields.get(i).getType())); if (colName.equals(mPrimaryKeyColumnName)) { b.append(" PRIMARY KEY AUTOINCREMENT"); } if (i < len - 1) { b.append(","); } } b.append(");"); String sql = b.toString(); Log.v(TAG, sql); db.execSQL(sql); mSchemaCreated = true; }
@Override public List<ProductType> map(TypeListResult typeListResult) { List<ProductType> productTypes = new ArrayList<>(); for (TypePo typePo : typeListResult.getData()) { productTypes.add(mapper.toModel(typePo)); } return productTypes; }
private ConnectionException createException(XmlInputStream xin) throws IOException, ConnectionException { readSoapEnvelopeStart(xin); xin.nextTag(); typeMapper.verifyTag(Constants.SOAP_ENVELOPE_NS, "Fault", xin.getNamespace(), xin.getName()); xin.nextTag(); if (!"faultcode".equals(xin.getName())) { throw new ConnectionException("Unable to find 'faultcode' in SOAP:Fault"); } String faultCodeStr = xin.nextText(); String prefix = TypeMapper.getPrefix(faultCodeStr); String name = TypeMapper.getType(faultCodeStr); String namespace = xin.getNamespace(prefix); QName faultCode = new QName(namespace, name); xin.nextTag(); if (!"faultstring".equals(xin.getName())) { throw new ConnectionException("Unable to find 'faultstring' in SOAP:Fault"); } String faultstring = xin.nextText(); ConnectionException e; xin.peekTag(); if ("detail".equals(xin.getName())) { e = parseDetail(xin, faultCode, faultstring); } else { e = new SoapFaultException(faultCode, faultstring); } xin.nextTag(); typeMapper.verifyTag(Constants.SOAP_ENVELOPE_NS, "Fault", xin.getNamespace(), xin.getName()); readSoapEnvelopeEnd(xin); return e; }
private void readSoapHeader(XmlInputStream xin) throws IOException, ConnectionException { while (!headerEndTag(xin)) { xin.peekTag(); if (xin.getEventType() == XmlInputStream.START_TAG) { QName tag = new QName(xin.getNamespace(), xin.getName()); Class headerType = (knownHeaders != null) ? knownHeaders.get(tag) : null; if (headerType != null) { TypeInfo info = new TypeInfo(xin.getNamespace(), xin.getName(), null, null, 1, 1, true); XMLizable result = (XMLizable) typeMapper.readObject(xin, info, headerType); if (connection != null) { setHeader(tag, headerType, result); } } else { throw new ConnectionException("Unrecognized header: " + tag.toString()); } } } xin.next(); }
/* * Doesn't move the cursor - expects it to be positioned appropriately. */ <T extends Entity> T load(SQLiteDatabase db, Cursor c) { try { // TODO we should be checking here that we've got data before // instantiating... @SuppressWarnings("unchecked") T model = (T) mMappedClass.newInstance(); model.mTransient = false; ArrayList<String> colNames = mColumnNames; ArrayList<Field> fields = mFields; int len = colNames.size(); for (int i = 0; i < len; i++) { Field f = fields.get(i); Class<?> ftype = f.getType(); int colIndex = c.getColumnIndex(colNames.get(i)); if (colIndex == -1) { Log.e( "Internal<ModelMapping>", "Got -1 column index for `" + colNames.get(i) + "' - Database schema may not match entity"); throw new ORMDroidException( "Got -1 column index for `" + colNames.get(i) + "' - Database schema may not match entity"); } else { Object o = TypeMapper.getMapping(f.getType()).decodeValue(db, ftype, c, colIndex); f.set(model, o); } } return model; } catch (Exception e) { throw new ORMDroidException( "Failed to instantiate model class - does it have a public null constructor?", e); } }
/** * Configure the output ports to expose all of the variables at the top level of the (potentially * constrained) DDS. * * @param dds The DDS * @throws IllegalActionException When bad things happen. */ private void configureOutputPorts(DDS dds) throws IllegalActionException { Vector<Type> types = new Vector<Type>(); Vector<String> names = new Vector<String>(); Enumeration e = dds.getVariables(); while (e.hasMoreElements()) { opendap.dap.BaseType bt = (opendap.dap.BaseType) e.nextElement(); types.add(TypeMapper.mapDapObjectToType(bt, false)); names.add(bt.getLongName()); } removeOtherOutputPorts(names); Iterator ti = types.iterator(); Iterator ni = names.iterator(); while (ti.hasNext() && ni.hasNext()) { Type type = (Type) ti.next(); String name = (String) ni.next(); initializePort(name, type); } }
private ConnectionException parseDetail(XmlInputStream xin, QName faultCode, String faultstring) throws IOException, ConnectionException { ConnectionException e; xin.nextTag(); // consume <detail> xin.peekTag(); // move to the body of <detail> if (xin.getEventType() == XmlInputStream.END_TAG) { // check for empty detail element throw new SoapFaultException(faultCode, faultstring); } TypeInfo info = new TypeInfo(null, null, null, null, 1, 1, true); try { e = (ConnectionException) typeMapper.readObject(xin, info, ConnectionException.class); if (e instanceof SoapFaultException) { ((SoapFaultException) e).setFaultCode(faultCode); if (faultstring != null && (faultstring.contains("Session timed out") || faultstring.contains("Session not found") || faultstring.contains("Illegal Session")) && "INVALID_SESSION_ID".equals(faultCode.getLocalPart())) { e = new SessionTimedOutException(faultstring, e); } } } catch (ConnectionException ce) { throw new ConnectionException( "Failed to parse detail: " + xin + " due to: " + ce, ce.getCause()); } xin.nextTag(); // consume </detail> if (!"detail".equals(xin.getName())) { throw new ConnectionException("Failed to find </detail>"); } return e; }
private Object convertArgument( Object[] args, int index, Method invokingMethod, TypeMapper mapper, boolean allowObjects, Class expectedType) { Object arg = args[index]; if (arg != null) { Class type = arg.getClass(); ToNativeConverter converter = null; if (NativeMapped.class.isAssignableFrom(type)) { converter = NativeMappedConverter.getInstance(type); } else if (mapper != null) { converter = mapper.getToNativeConverter(type); } if (converter != null) { ToNativeContext context; if (invokingMethod != null) { context = new MethodParameterContext(this, args, index, invokingMethod); } else { context = new FunctionParameterContext(this, args, index); } arg = converter.toNative(arg, context); } } if (arg == null || isPrimitiveArray(arg.getClass())) { return arg; } Class argClass = arg.getClass(); // Convert Structures to native pointers if (arg instanceof Structure) { Structure struct = (Structure) arg; struct.autoWrite(); if (struct instanceof Structure.ByValue) { // Double-check against the method signature, if available Class ptype = struct.getClass(); if (invokingMethod != null) { Class[] ptypes = invokingMethod.getParameterTypes(); if (isVarArgs(invokingMethod)) { if (index < ptypes.length - 1) { ptype = ptypes[index]; } else { Class etype = ptypes[ptypes.length - 1].getComponentType(); if (etype != Object.class) { ptype = etype; } } } else { ptype = ptypes[index]; } } if (Structure.ByValue.class.isAssignableFrom(ptype)) { return struct; } } return struct.getPointer(); } // Convert Callback to Pointer else if (arg instanceof Callback) { return CallbackReference.getFunctionPointer((Callback) arg); } // String arguments are converted to native pointers here rather // than in native code so that the values will be valid until // this method returns. // Convert String to native pointer (const) else if (arg instanceof String) { return new NativeString((String) arg, false).getPointer(); } // Convert WString to native pointer (const) else if (arg instanceof WString) { return new NativeString(arg.toString(), true).getPointer(); } // Default conversion of boolean to int; if you want something // different, use a ToNativeConverter else if (arg instanceof Boolean) { return Boolean.TRUE.equals(arg) ? INTEGER_TRUE : INTEGER_FALSE; } else if (String[].class == argClass) { return new StringArray((String[]) arg, encoding); } else if (WString[].class == argClass) { return new StringArray((WString[]) arg); } else if (Pointer[].class == argClass) { return new PointerArray((Pointer[]) arg); } else if (NativeMapped[].class.isAssignableFrom(argClass)) { return new NativeMappedArray((NativeMapped[]) arg); } else if (Structure[].class.isAssignableFrom(argClass)) { // If the signature is Structure[], disallow // Structure.ByReference[] and Structure.ByReference elements Structure[] ss = (Structure[]) arg; Class type = argClass.getComponentType(); boolean byRef = Structure.ByReference.class.isAssignableFrom(type); if (expectedType != null) { if (!Structure.ByReference[].class.isAssignableFrom(expectedType)) { if (byRef) { throw new IllegalArgumentException( "Function " + getName() + " declared Structure[] at parameter " + index + " but array of " + type + " was passed"); } for (int i = 0; i < ss.length; i++) { if (ss[i] instanceof Structure.ByReference) { throw new IllegalArgumentException( "Function " + getName() + " declared Structure[] at parameter " + index + " but element " + i + " is of Structure.ByReference type"); } } } } if (byRef) { Structure.autoWrite(ss); Pointer[] pointers = new Pointer[ss.length + 1]; for (int i = 0; i < ss.length; i++) { pointers[i] = ss[i] != null ? ss[i].getPointer() : null; } return new PointerArray(pointers); } else if (ss.length == 0) { throw new IllegalArgumentException("Structure array must have non-zero length"); } else if (ss[0] == null) { Structure.newInstance(type).toArray(ss); return ss[0].getPointer(); } else { Structure.autoWrite(ss); return ss[0].getPointer(); } } else if (argClass.isArray()) { throw new IllegalArgumentException( "Unsupported array argument type: " + argClass.getComponentType()); } else if (allowObjects) { return arg; } else if (!Native.isSupportedNativeType(arg.getClass())) { throw new IllegalArgumentException( "Unsupported argument type " + arg.getClass().getName() + " at parameter " + index + " of function " + getName()); } return arg; }
/** * Invoke the native function with the given arguments, returning the native result as an Object. */ public Object invoke(Class returnType, Object[] inArgs, Map options) { // Clone the argument array to obtain a scratch space for modified // types/values Object[] args = {}; if (inArgs != null) { if (inArgs.length > MAX_NARGS) { throw new UnsupportedOperationException("Maximum argument count is " + MAX_NARGS); } args = new Object[inArgs.length]; System.arraycopy(inArgs, 0, args, 0, args.length); } TypeMapper mapper = (TypeMapper) options.get(Library.OPTION_TYPE_MAPPER); Method invokingMethod = (Method) options.get(OPTION_INVOKING_METHOD); Class[] paramTypes = invokingMethod != null ? invokingMethod.getParameterTypes() : null; boolean allowObjects = Boolean.TRUE.equals(options.get(Library.OPTION_ALLOW_OBJECTS)); boolean isVarArgs = args.length > 0 && invokingMethod != null ? isVarArgs(invokingMethod) : false; for (int i = 0; i < args.length; i++) { Class paramType = invokingMethod != null ? (isVarArgs && i >= paramTypes.length - 1 ? paramTypes[paramTypes.length - 1].getComponentType() : paramTypes[i]) : null; args[i] = convertArgument(args, i, invokingMethod, mapper, allowObjects, paramType); } Class nativeReturnType = returnType; FromNativeConverter resultConverter = null; if (NativeMapped.class.isAssignableFrom(returnType)) { NativeMappedConverter tc = NativeMappedConverter.getInstance(returnType); resultConverter = tc; nativeReturnType = tc.nativeType(); } else if (mapper != null) { resultConverter = mapper.getFromNativeConverter(returnType); if (resultConverter != null) { nativeReturnType = resultConverter.nativeType(); } } Object result = invoke(args, nativeReturnType, allowObjects); // Convert the result to a custom value/type if appropriate if (resultConverter != null) { FromNativeContext context; if (invokingMethod != null) { context = new MethodResultContext(returnType, this, inArgs, invokingMethod); } else { context = new FunctionResultContext(returnType, this, inArgs); } result = resultConverter.fromNative(result, context); } // Sync all memory which might have been modified by the native call if (inArgs != null) { for (int i = 0; i < inArgs.length; i++) { Object inArg = inArgs[i]; if (inArg == null) continue; if (inArg instanceof Structure) { if (!(inArg instanceof Structure.ByValue)) { ((Structure) inArg).autoRead(); } } else if (args[i] instanceof PostCallRead) { ((PostCallRead) args[i]).read(); if (args[i] instanceof PointerArray) { PointerArray array = (PointerArray) args[i]; if (Structure.ByReference[].class.isAssignableFrom(inArg.getClass())) { Class type = inArg.getClass().getComponentType(); Structure[] ss = (Structure[]) inArg; for (int si = 0; si < ss.length; si++) { Pointer p = array.getPointer(Pointer.SIZE * si); ss[si] = Structure.updateStructureByReference(type, ss[si], p); } } } } else if (Structure[].class.isAssignableFrom(inArg.getClass())) { Structure.autoRead((Structure[]) inArg); } } } return result; }
@SuppressWarnings({"unchecked", "rawtypes"}) public Object jsonToObject(final JSonNode json, Type type) throws MapperException { final ClassCache cc; try { Class<?> clazz = null; if (type instanceof ParameterizedType) { Type typ = ((ParameterizedType) type).getRawType(); if (typ instanceof Class) { clazz = (Class<?>) typ; } } else if (type instanceof Class) { clazz = (Class) type; } else if (type instanceof GenericArrayType) { // this is for 1.6 // for 1.7 we do not get GenericArrayTypeImpl here but the // actual array class type = clazz = Array.newInstance((Class<?>) ((GenericArrayType) type).getGenericComponentType(), 0) .getClass(); } if (clazz == null || clazz == Object.class) { if (json instanceof JSonArray) { type = clazz = LinkedList.class; } else if (json instanceof JSonObject) { type = clazz = HashMap.class; } else if (json instanceof JSonValue) { switch (((JSonValue) json).getType()) { case BOOLEAN: type = clazz = boolean.class; break; case DOUBLE: type = clazz = double.class; break; case LONG: type = clazz = long.class; break; case NULL: case STRING: type = clazz = String.class; } } } final TypeMapper<?> tm = typeMapper.get(clazz); if (tm != null) { return tm.reverseMap(json); } if (json instanceof JSonValue) { if (!Clazz.isPrimitive(type) && !Clazz.isString(type) && type != Object.class && ((JSonValue) json).getValue() != null && !Clazz.isEnum(type)) { // throw new MapperException(json + " cannot be mapped to " + type); } switch (((JSonValue) json).getType()) { case BOOLEAN: case DOUBLE: case LONG: if (type instanceof Class) { return JSonMapper.cast(((JSonValue) json).getValue(), (Class) type); } else { return ((JSonValue) json).getValue(); } case STRING: if (type instanceof Class && ((Class<?>) type).isEnum()) { try { return Enum.valueOf((Class<Enum>) type, ((JSonValue) json).getValue() + ""); } catch (final IllegalArgumentException e) { if (isIgnoreIllegalArgumentMappings() || isIgnoreIllegalEnumMappings()) { return null; } throw e; } } else { return ((JSonValue) json).getValue(); } case NULL: return null; } } if (type instanceof ParameterizedType) { final ParameterizedType pType = (ParameterizedType) type; Type raw = pType.getRawType(); if (raw instanceof Class && Collection.class.isAssignableFrom((Class) raw)) { final Collection<Object> inst = (Collection<Object>) mapClasses((Class) raw).newInstance(); final JSonArray obj = (JSonArray) json; for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, pType.getActualTypeArguments()[0])); } return inst; } else if (raw instanceof Class && Map.class.isAssignableFrom((Class) raw)) { final Map<String, Object> inst = (Map<String, Object>) mapClasses((Class) raw).newInstance(); final JSonObject obj = (JSonObject) json; Entry<String, JSonNode> next; for (final Iterator<Entry<String, JSonNode>> it = obj.entrySet().iterator(); it.hasNext(); ) { next = it.next(); inst.put( next.getKey(), this.jsonToObject(next.getValue(), pType.getActualTypeArguments()[1])); } return inst; } } if (clazz != null) { if (clazz == Object.class) { // guess type if (json instanceof JSonArray) { type = LinkedList.class; } else if (json instanceof JSonObject) { type = HashMap.class; } } if (Collection.class.isAssignableFrom(clazz)) { final Collection<Object> inst = (Collection<Object>) mapClasses(clazz).newInstance(); final JSonArray obj = (JSonArray) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[0]; } else { gType = void.class; } for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, gType)); } return inst; } else if (Map.class.isAssignableFrom(clazz)) { final Map<String, Object> inst = (Map<String, Object>) mapClasses(clazz).newInstance(); final JSonObject obj = (JSonObject) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[1]; } else { gType = void.class; } Entry<String, JSonNode> next; for (final Iterator<Entry<String, JSonNode>> it = obj.entrySet().iterator(); it.hasNext(); ) { next = it.next(); inst.put(next.getKey(), this.jsonToObject(next.getValue(), gType)); } return inst; } else if (clazz.isArray()) { final JSonArray obj = (JSonArray) json; final Object arr = Array.newInstance(mapClasses(clazz.getComponentType()), obj.size()); for (int i = 0; i < obj.size(); i++) { final Object v = this.jsonToObject(obj.get(i), clazz.getComponentType()); Array.set(arr, i, v); } return arr; } else { if (json instanceof JSonArray) { final java.util.List<Object> inst = new ArrayList<Object>(); final JSonArray obj = (JSonArray) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[0]; } else { gType = Object.class; } for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, gType)); } return inst; } else { final JSonObject obj = (JSonObject) json; if (Clazz.isPrimitive(clazz)) { // if (isIgnoreIllegalArgumentMappings()) { return null; } else { throw new IllegalArgumentException("Cannot Map " + obj + " to " + clazz); } } cc = ClassCache.getClassCache(clazz); final Object inst = cc.getInstance(); JSonNode value; Object v; for (final Setter s : cc.getSetter()) { value = obj.get(s.getKey()); if (value == null) { continue; } // Type fieldType = s.getType(); // special handling for generic fields if (fieldType instanceof TypeVariable) { final Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments(); final TypeVariable<?>[] genericTypes = clazz.getTypeParameters(); for (int i = 0; i < genericTypes.length; i++) { if (StringUtils.equals( ((TypeVariable) fieldType).getName(), genericTypes[i].getName())) { fieldType = actualTypes[i]; break; } } } v = this.jsonToObject(value, fieldType); try { s.setValue(inst, v); } catch (final IllegalArgumentException e) { if (isIgnoreIllegalArgumentMappings()) { continue; } else if (v == null && isIgnorePrimitiveNullMapping()) { continue; } throw e; } } return inst; } } } else { System.err.println("TYPE?!"); } } catch (final SecurityException e) { e.printStackTrace(); } catch (final NoSuchMethodException e) { e.printStackTrace(); } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final InstantiationException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final InvocationTargetException e) { e.printStackTrace(); } return null; }
/** * @param obj * @return * @throws MapperException */ @SuppressWarnings("unchecked") public JSonNode create(final Object obj) throws MapperException { try { if (obj == null) { return new JSonValue(null); } final Class<? extends Object> clazz = obj.getClass(); TypeMapper<?> mapper; if (clazz.isPrimitive()) { if (clazz == boolean.class) { return new JSonValue((Boolean) obj); } else if (clazz == char.class) { return new JSonValue(0 + ((Character) obj).charValue()); } else if (clazz == byte.class) { return new JSonValue(((Byte) obj).longValue()); } else if (clazz == short.class) { return new JSonValue(((Short) obj).longValue()); } else if (clazz == int.class) { return new JSonValue(((Integer) obj).longValue()); } else if (clazz == long.class) { return new JSonValue(((Long) obj).longValue()); } else if (clazz == float.class) { return new JSonValue(((Float) obj).doubleValue()); } else if (clazz == double.class) { return new JSonValue(((Double) obj).doubleValue()); } } else if (clazz.isEnum()) { return new JSonValue(obj + ""); } else if (obj instanceof Boolean) { return new JSonValue(((Boolean) obj).booleanValue()); } else if (obj instanceof Character) { return new JSonValue(0 + ((Character) obj).charValue()); } else if (obj instanceof Byte) { return new JSonValue(((Byte) obj).longValue()); } else if (obj instanceof Short) { return new JSonValue(((Short) obj).longValue()); } else if (obj instanceof Integer) { return new JSonValue(((Integer) obj).longValue()); } else if (obj instanceof Long) { return new JSonValue(((Long) obj).longValue()); } else if (obj instanceof Float) { return new JSonValue(((Float) obj).doubleValue()); } else if (obj instanceof Double) { return new JSonValue(((Double) obj).doubleValue()); } else if (obj instanceof String) { return new JSonValue((String) obj); } else if (obj instanceof Map) { final JSonObject ret = new JSonObject(); Entry<Object, Object> next; for (final Iterator<Entry<Object, Object>> it = ((Map<Object, Object>) obj).entrySet().iterator(); it.hasNext(); ) { next = it.next(); if (!(next.getKey() instanceof String)) { throw new MapperException( "Map keys have to be Strings: " + clazz + " Keyclass:" + (next.getKey() == null ? "<null>" : next.getKey().getClass())); } ret.put(next.getKey().toString(), create(next.getValue())); } return ret; } else if (obj instanceof Collection) { final JSonArray ret = new JSonArray(); for (final Object o : (Collection<?>) obj) { ret.add(create(o)); } return ret; } else if (clazz.isArray()) { final JSonArray ret = new JSonArray(); for (int i = 0; i < Array.getLength(obj); i++) { ret.add(create(Array.get(obj, i))); } return ret; } else if (obj instanceof Class) { return new JSonValue(((Class<?>) obj).getName()); } else if ((mapper = typeMapper.get(clazz)) != null) { return mapper.map(obj); } else /* if (obj instanceof Storable) */ { final ClassCache cc = ClassCache.getClassCache(clazz); final JSonObject ret = new JSonObject(); for (final Getter g : cc.getGetter()) { ret.put(g.getKey(), create(g.getValue(obj))); } return ret; } } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final InvocationTargetException e) { e.printStackTrace(); } catch (final SecurityException e) { e.printStackTrace(); } catch (final NoSuchMethodException e) { e.printStackTrace(); } return null; }
private String processValue(SQLiteDatabase db, Object value) { return TypeMapper.encodeValue(db, value); }