Exemplo n.º 1
0
  protected AegisType createUserType(TypeClassInfo info) {
    try {
      AegisType type = info.getAegisTypeClass().newInstance();

      QName name = info.getTypeName();
      if (name == null) {
        // We do not want to use the java.lang.whatever schema type.
        // If the @ annotation or XML file didn't specify a schema type,
        // but the natural type has a schema type mapping, we use that rather
        // than create nonsense.
        Class<?> typeClass = TypeUtil.getTypeRelatedClass(info.getType());
        if (typeClass.getPackage().getName().startsWith("java")) {
          name = tm.getTypeQName(typeClass);
        }
        // if it's still null, we'll take our lumps, but probably end up with
        // an invalid schema.
        if (name == null) {
          name = createQName(typeClass);
        }
      }

      type.setSchemaType(name);
      type.setTypeClass(info.getType());
      type.setTypeMapping(getTypeMapping());

      return type;
    } catch (InstantiationException e) {
      throw new DatabindingException(
          "Couldn't instantiate type classs " + info.getAegisTypeClass().getName(), e);
    } catch (IllegalAccessException e) {
      throw new DatabindingException(
          "Couldn't access type classs " + info.getAegisTypeClass().getName(), e);
    }
  }
Exemplo n.º 2
0
  protected QName createCollectionQName(TypeClassInfo info, AegisType type) {
    String ns;

    if (type.isComplex()) {
      ns = type.getSchemaType().getNamespaceURI();
    } else {
      ns = tm.getMappingIdentifierURI();
    }
    if (WSDLConstants.NS_SCHEMA_XSD.equals(ns)) {
      ns = HTTP_CXF_APACHE_ORG_ARRAYS;
    }

    String first = type.getSchemaType().getLocalPart().substring(0, 1);
    String last = type.getSchemaType().getLocalPart().substring(1);
    String localName = "ArrayOf" + first.toUpperCase() + last;
    if (info.nonDefaultAttributes()) {
      localName += "-";
      if (info.getMinOccurs() >= 0) {
        localName += info.getMinOccurs();
      }
      localName += "-";
      if (info.getMaxOccurs() >= 0) {
        localName += info.getMaxOccurs();
      }
      if (info.isFlat()) {
        localName += "Flat";
      }
    }

    return new QName(ns, localName);
  }
Exemplo n.º 3
0
  protected QName createMapQName(TypeClassInfo info, AegisType keyType, AegisType valueType) {
    String name =
        keyType.getSchemaType().getLocalPart() + '2' + valueType.getSchemaType().getLocalPart();

    Class<?> cls = TypeUtil.getTypeRelatedClass(info.getType());
    name += cls.getSimpleName();

    // TODO: Get namespace from XML?
    return new QName(tm.getMappingIdentifierURI(), name);
  }
Exemplo n.º 4
0
  protected QName createMapQName(TypeClassInfo info, Type keyType, Type valueType) {
    String name =
        keyType.getSchemaType().getLocalPart()
            + '2'
            + valueType.getSchemaType().getLocalPart()
            + "Map";

    // TODO: Get namespace from XML?
    return new QName(tm.getEncodingStyleURI(), name);
  }
Exemplo n.º 5
0
  private static HashMap<String, String> extractJVar2KVarMapping(Stream<SimpleName> names) {
    // map java var name to k var name
    HashMap<String, String> fromJVarName2KVarName = new HashMap<>();

    names.forEach(
        name -> {
          String varId = name.getIdentifier();
          fromJVarName2KVarName.put(
              varId, TypeMapping.convert2KVar(varId, name.resolveTypeBinding().isPrimitive()));
        });
    return fromJVarName2KVarName;
  }
Exemplo n.º 6
0
  private static HashMap<String, String> extractJVar2KVarMapping(
      ArrayList<SingleVariableDeclaration> formalParams) {
    // map java var name to k var name
    HashMap<String, String> fromJVarName2KVarName = new HashMap<>();

    formalParams.forEach(
        varDecl ->
            fromJVarName2KVarName.put(
                varDecl.getName().toString(),
                TypeMapping.convert2KVar(
                    varDecl.getName().toString(), varDecl.getType().isPrimitiveType())));
    return fromJVarName2KVarName;
  }
Exemplo n.º 7
0
  /** add a mapping for this {@link TypeMapping}'s type and alias */
  public void addMapping(final TypeMapping mapping) {
    final String typeAlias = mapping.getTypeAlias();
    if (StringUtils.empty(typeAlias)) {
      throw new IllegalArgumentException("typeAlias must not be empty");
    }

    {
      // put alias if unknown
      final TypeMapping prev = _mappingsByAlias.putIfAbsent(typeAlias, mapping);
      if (prev != null && prev != mapping) {
        throw new IllegalArgumentException("duplicate type alias " + mapping.getTypeAlias());
      }
    }

    {
      // put class if unknown
      final TypeMapping prev = _mappingsByClass.putIfAbsent(mapping.getTypeClass(), mapping);
      if (prev != null && prev != mapping) {
        _mappingsByAlias.remove(typeAlias);
        throw new IllegalArgumentException(
            "duplicate type class " + mapping.getTypeClass().getName());
      }
    }
  }
Exemplo n.º 8
0
  protected QName createCollectionQName(TypeClassInfo info, Type type) {
    String ns;

    if (type.isComplex()) {
      ns = type.getSchemaType().getNamespaceURI();
    } else {
      ns = tm.getEncodingStyleURI();
    }

    String first = type.getSchemaType().getLocalPart().substring(0, 1);
    String last = type.getSchemaType().getLocalPart().substring(1);
    String localName = "ArrayOf" + first.toUpperCase() + last;

    return new QName(ns, localName);
  }
Exemplo n.º 9
0
  public static void updateObjStoreByParsingContent(
      List<String> objStore,
      String objStoreContent,
      Collection<KRewriteObj> kObjs,
      ArrayList<SingleVariableDeclaration> formalParams) {
    if (objStoreContent == null || objStore == null) return;

    final String[] inputs = objStoreContent.split(",");
    for (int i = 0; i < inputs.length; i++) {
      String strI = inputs[i];
      final String[] elements = strI.split("=>");
      final String[] lhs = {elements[0]};
      final String[] rhs = {null};
      if (elements.length > 1) rhs[0] = elements[1];

      kObjs.forEach(
          kRewriteObj -> {
            lhs[0] = kRewriteObj.rewrite2KVarIfPossible(lhs[0], true);
          });

      if (formalParams != null && !formalParams.isEmpty()) {
        formalParams.forEach(
            var -> {
              lhs[0] =
                  lhs[0].replaceAll(
                      name2Regex(var.getName().getIdentifier()),
                      TypeMapping.convert2KVar(
                          var.getName().getIdentifier(), var.getType().isPrimitiveType()));
            });
      }

      if (rhs[0] != null) {
        kObjs.forEach(
            kRewriteObj -> {
              rhs[0] = kRewriteObj.rewrite2KVarIfPossible(rhs[0], false);
            });
      }

      String outputI = lhs[0];
      if (rhs[0] != null) {
        outputI += " => " + rhs[0];
      }

      objStore.add(outputI);
    }
  }
Exemplo n.º 10
0
  /**
   * We can assume that there is neither '&&' nor '||' in the literal, and focus on transforming the
   * literal according to the type of atoms. Currently, only int operations and floating operations
   * are supported.
   *
   * @param literal
   * @param typeId
   * @return
   */
  public static String fromLiteral2KExpr(String literal, int typeId) {
    String kexp = literal;
    // replace each pattern in the array to its corresponding k-form.
    String[] transformCandidates = null;
    if (typeId == TypeMapping.INT_OPERAND) transformCandidates = TypeMapping.infixOP;
    else if (typeId == TypeMapping.FLOAT_OPERAND) transformCandidates = TypeMapping.commonInfixOP;
    else if (typeId == TypeMapping.BOOL_OPERAND) transformCandidates = TypeMapping.boolOP;
    else if (typeId == TypeMapping.STRING_OPERAND) transformCandidates = TypeMapping.commonInfixOP;
    else transformCandidates = null;

    if (transformCandidates == null) return literal.replaceAll("(?<=\\W)==(?=\\W)", "==K");

    for (int i = 0; i < transformCandidates.length; i++) {
      String curOp = transformCandidates[i];
      if (!literal.contains(curOp)) continue;

      kexp = kexp.replaceAll(toRegEx(curOp), TypeMapping.convert2KOP(curOp, typeId));
    }

    return kexp;
  }
 @Override
 public StorageResults visit(Select select) {
   // TMDM-4654: Checks if entity has a composite PK.
   Set<ComplexTypeMetadata> compositeKeyTypes = new HashSet<ComplexTypeMetadata>();
   // TMDM-7496: Search should include references to reused types
   Collection<ComplexTypeMetadata> types =
       new HashSet<ComplexTypeMetadata>(select.accept(new SearchTransitiveClosure()));
   for (ComplexTypeMetadata type : types) {
     if (type.getKeyFields().size() > 1) {
       compositeKeyTypes.add(type);
     }
   }
   if (!compositeKeyTypes.isEmpty()) {
     StringBuilder message = new StringBuilder();
     Iterator it = compositeKeyTypes.iterator();
     while (it.hasNext()) {
       ComplexTypeMetadata compositeKeyType = (ComplexTypeMetadata) it.next();
       message.append(compositeKeyType.getName());
       if (it.hasNext()) {
         message.append(',');
       }
     }
     throw new FullTextQueryCompositeKeyException(message.toString());
   }
   // Removes Joins and joined fields.
   List<Join> joins = select.getJoins();
   if (!joins.isEmpty()) {
     Set<ComplexTypeMetadata> joinedTypes = new HashSet<ComplexTypeMetadata>();
     for (Join join : joins) {
       joinedTypes.add(join.getRightField().getFieldMetadata().getContainingType());
     }
     for (ComplexTypeMetadata joinedType : joinedTypes) {
       types.remove(joinedType);
     }
     List<TypedExpression> filteredFields = new LinkedList<TypedExpression>();
     for (TypedExpression expression : select.getSelectedFields()) {
       if (expression instanceof Field) {
         FieldMetadata fieldMetadata = ((Field) expression).getFieldMetadata();
         if (joinedTypes.contains(fieldMetadata.getContainingType())) {
           TypeMapping mapping =
               mappings.getMappingFromDatabase(fieldMetadata.getContainingType());
           filteredFields.add(
               new Alias(
                   new StringConstant(StringUtils.EMPTY),
                   mapping.getUser(fieldMetadata).getName()));
         } else {
           filteredFields.add(expression);
         }
       } else {
         filteredFields.add(expression);
       }
     }
     selectedFields.clear();
     selectedFields.addAll(filteredFields);
   }
   // Handle condition
   Condition condition = select.getCondition();
   if (condition == null) {
     throw new IllegalArgumentException("Expected a condition in select clause but got 0.");
   }
   // Create Lucene query (concatenates all sub queries together).
   FullTextSession fullTextSession = Search.getFullTextSession(session);
   Query parsedQuery = select.getCondition().accept(new LuceneQueryGenerator(types));
   // Create Hibernate Search query
   Set<Class> classes = new HashSet<Class>();
   for (ComplexTypeMetadata type : types) {
     String className = ClassCreator.getClassName(type.getName());
     try {
       ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
       classes.add(contextClassLoader.loadClass(className));
     } catch (ClassNotFoundException e) {
       throw new RuntimeException("Could not find class '" + className + "'.", e);
     }
   }
   FullTextQuery fullTextQuery =
       fullTextSession.createFullTextQuery(
           parsedQuery, classes.toArray(new Class<?>[classes.size()]));
   // Very important to leave this null (would disable ability to search across different types)
   fullTextQuery.setCriteriaQuery(null);
   fullTextQuery.setSort(Sort.RELEVANCE); // Default sort (if no order by specified).
   query =
       EntityFinder.wrap(
           fullTextQuery,
           (HibernateStorage) storage,
           session); // ensures only MDM entity objects are returned.
   // Order by
   for (OrderBy current : select.getOrderBy()) {
     current.accept(this);
   }
   // Paging
   Paging paging = select.getPaging();
   paging.accept(this);
   pageSize = paging.getLimit();
   boolean hasPaging = pageSize < Integer.MAX_VALUE;
   if (!hasPaging) {
     return createResults(query.scroll(ScrollMode.FORWARD_ONLY));
   } else {
     return createResults(query.list());
   }
 }