public static String getInternalServletXmlFilePath(EdoBean bean) {
   String folder =
       bean.getEdoBuilder().getJavaControllerInternalServletFolder()
           + StringUtils.uncapitalize(bean.getName())
           + File.separator;
   String filename = StringUtils.uncapitalize(bean.getName()) + "Front.xml";
   String finalfile = folder + filename;
   return finalfile;
 }
  private void updateEncodingPresets(Resource configResource, S7Config s7Config, String typeHandle)
      throws RepositoryException {

    // Get the presets from S7 and store them on the node
    //
    List<Scene7PropertySet> propertySets = scene7Service.getPropertySets(typeHandle, s7Config);

    String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_ENCODING_PRESETS;
    Node node = prepNode(configResource.getResourceResolver(), path);
    Node presetNode;
    int i = 0;
    for (Scene7PropertySet propertySet : propertySets) {
      String handle = propertySet.getSetHandle();
      String nodeName = getNodeName(handle);
      if (StringUtils.isNotBlank(nodeName)) {
        presetNode = node.addNode(nodeName);
        presetNode.setProperty("handle", handle);
        Map<String, String> properties = propertySet.getProperties();
        for (String key : properties.keySet()) {
          String value = properties.get(key);
          key = StringUtils.uncapitalize(key);
          presetNode.setProperty(key, value);
        }
      }
    }
  }
Example #3
0
  private Object getProperty(Object instance, FieldDto field, MotechDataService service)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String fieldName = StringUtils.uncapitalize(field.getBasic().getName());

    PropertyDescriptor propertyDescriptor = PropertyUtil.getPropertyDescriptor(instance, fieldName);
    Method readMethod = propertyDescriptor.getReadMethod();

    if (readMethod == null) {
      throw new NoSuchMethodException(String.format("No getter for field %s", fieldName));
    }

    if (TypeDto.BLOB.getTypeClass().equals(field.getType().getTypeClass())) {
      return ArrayUtils.EMPTY_BYTE_OBJECT_ARRAY;
    }

    try {
      return readMethod.invoke(instance);
    } catch (InvocationTargetException e) {
      LOGGER.debug(
          "Invocation target exception thrown when retrieving field {}. This may indicate a non loaded field",
          fieldName,
          e);
      // fallback to the service
      return service.getDetachedField(instance, fieldName);
    }
  }
Example #4
0
  @Override
  public void revertInstanceFromTrash(Long entityId, Long instanceId) {
    EntityDto entity = getEntity(entityId);
    validateCredentials(entity);
    validateNonEditableProperty(entity);
    MotechDataService service = getServiceForEntity(entity);

    Object trash = service.findTrashInstanceById(instanceId, entityId);
    List<FieldRecord> fieldRecords = new LinkedList<>();

    try {
      for (FieldDto field : entityService.getEntityFields(entity.getId())) {
        if (ID_FIELD_NAME.equalsIgnoreCase(field.getBasic().getDisplayName())) {
          continue;
        }
        Field f =
            FieldUtils.getField(
                trash.getClass(), StringUtils.uncapitalize(field.getBasic().getName()), true);
        FieldRecord record = new FieldRecord(field);
        record.setValue(f.get(trash));
        fieldRecords.add(record);
      }

      Class<?> entityClass = getEntityClass(entity);

      Object newInstance = entityClass.newInstance();
      updateFields(newInstance, fieldRecords, service, null);

      service.revertFromTrash(newInstance, trash);
    } catch (Exception e) {
      throw new RevertFromTrashException(entity.getName(), instanceId, e);
    }
  }
 public List<T> findWithFinder(Finder finder) {
   Session session = getSessionFactory().getCurrentSession();
   Criteria criteria =
       session.createCriteria(
           persistentClass, StringUtils.uncapitalize(persistentClass.getSimpleName()));
   finder.prepareCriteria(criteria, persistentClass);
   return criteria.list();
 }
 /**
  * db feild name -> pojo field name
  *
  * @param column
  * @return
  */
 private static String column2Prop(String column) {
   String[] strs = column.split("_");
   String conventName = "";
   for (int i = 0; i < strs.length; i++) {
     conventName += StringUtils.capitalize(strs[i]);
   }
   StringUtils.uncapitalize(conventName);
   return conventName;
 }
  public static String getInternalServletJspFilePath(EdoBean bean, String suffix) {
    String folder = bean.getEdoBuilder().getWebinfApsFolder();
    String subfolder =
        "jsp/internalservlet/".replaceAll("/", Matcher.quoteReplacement(File.separator));
    folder = folder + subfolder;
    folder = folder + bean.getName().toLowerCase() + File.separator;

    String filename = "frontend-" + StringUtils.uncapitalize(bean.getName()) + suffix;
    String finalfile = folder + filename;
    return finalfile;
  }
Example #8
0
  private void validateNonEditableField(
      FieldRecord fieldRecord, Object instance, Object parsedValue) throws IllegalAccessException {

    Object fieldOldValue =
        FieldUtils.readField(instance, StringUtils.uncapitalize(fieldRecord.getName()), true);

    // We need to check if read only field value isn't changed
    // in some unexpected way. If so then throw exception
    if (fieldRecord.isNonEditable()
        // There is need to use Objects.equals as values - one or both - can be null
        // which would cause NullPointerException when just .equals() on null value
        && !Objects.equals(fieldOldValue, parsedValue)) {
      throw new FieldReadOnlyException(instance.getClass().getName(), fieldRecord.getName());
    }
  }
  /**
   * Converts the folderName to comply with java naming convention
   *
   * @param importFolderName
   * @return String
   */
  private String convertToJavaCompliantName(String importFolderName) {
    // do not use upper case
    importFolderName = importFolderName.toLowerCase();

    // remove blank space
    importFolderName = importFolderName.replaceAll("\\s", "");
    importFolderName = importFolderName.replaceAll("-", "_");
    importFolderName = importFolderName.replaceAll("^\\d", "");

    // remove special chars
    Set<Character> barredChars = new HashSet<Character>();
    for (int i = 0; i < importFolderName.length(); i++) {
      char c = importFolderName.charAt(i);
      if (!(Character.isJavaIdentifierPart(c))) {
        barredChars.add(c);
      }
    }
    for (char c : barredChars) {
      importFolderName = StringUtils.remove(importFolderName, c);
    }
    return StringUtils.uncapitalize(importFolderName);
  }
  public static void buildManyAdder(
      OJAnnotatedClass owner,
      PropertyWrapper propertyWrapper,
      boolean indexed,
      boolean ignoreInverse) {
    OJAnnotatedOperation adder = new OJAnnotatedOperation(propertyWrapper.adder());
    if (!propertyWrapper.isMemberOfAssociationClass()) {
      if (indexed) {
        adder.addParam("index", "int");
      }
      adder.addParam(propertyWrapper.fieldname(), propertyWrapper.javaTypePath());
    } else {
      if (indexed) {
        adder.addParam("index", "int");
      }
      adder.addParam(
          propertyWrapper.getAssociationClassFakePropertyName(),
          propertyWrapper.javaTypePathWithAssociationClass());
    }

    if (!(owner instanceof OJAnnotatedInterface)) {
      if (!propertyWrapper.hasQualifiers()) {
        if (!propertyWrapper.isMemberOfAssociationClass()) {
          OJIfStatement ifNotNull =
              new OJIfStatement("!" + propertyWrapper.fieldname() + ".isEmpty()");
          ifNotNull.addToThenPart(
              "this."
                  + propertyWrapper.fieldname()
                  + ".addAll("
                  + propertyWrapper.fieldname()
                  + ")");
          adder.getBody().addToStatements(ifNotNull);
        } else {
          // iterate the association class set as it contains a Pair
          OJForStatement associationClassPairs =
              new OJForStatement(
                  "pair",
                  propertyWrapper.getAssociationClassPair(),
                  propertyWrapper.getAssociationClassFakePropertyName());
          associationClassPairs
              .getBody()
              .addToStatements(propertyWrapper.adder() + "(pair.getFirst(), pair.getSecond())");
          adder.getBody().addToStatements(associationClassPairs);
        }
      } else {
        String elementName = "_" + propertyWrapper.fieldname().substring(0, 1);
        OJForStatement forAll =
            new OJForStatement(
                elementName, propertyWrapper.javaBaseTypePath(), propertyWrapper.fieldname());
        forAll
            .getBody()
            .addToStatements("this." + propertyWrapper.adder() + "(" + elementName + ")");
        adder.getBody().addToStatements(forAll);
      }
    }
    owner.addToOperations(adder);

    OJAnnotatedOperation singleAdder =
        new OJAnnotatedOperation(
            !ignoreInverse ? propertyWrapper.adder() : propertyWrapper.adderIgnoreInverse());
    if (indexed) {
      singleAdder.addParam("index", "int");
    }
    singleAdder.addParam(propertyWrapper.fieldname(), propertyWrapper.javaBaseTypePath());
    if (propertyWrapper.isMemberOfAssociationClass()) {
      singleAdder.addParam(
          StringUtils.uncapitalize(propertyWrapper.getAssociationClass().getName()),
          UmlgClassOperations.getPathName(propertyWrapper.getAssociationClass()));
    }
    if (!(owner instanceof OJAnnotatedInterface)) {

      PropertyWrapper otherEnd = new PropertyWrapper(propertyWrapper.getOtherEnd());
      if (
      /*For bags the one side can have many edges to the same element*/ propertyWrapper.isUnique()
          && propertyWrapper.hasOtherEnd()
          && !propertyWrapper.isEnumeration()
          && otherEnd.isOne()) {
        OJIfStatement ifNotNull2 = new OJIfStatement(propertyWrapper.fieldname() + " != null");
        ifNotNull2.addToThenPart(propertyWrapper.fieldname() + "." + otherEnd.clearer() + "()");
        ifNotNull2.addToThenPart(
            propertyWrapper.fieldname()
                + ".initialiseProperty("
                + UmlgClassOperations.propertyEnumName(otherEnd.getOwningType())
                + "."
                + otherEnd.fieldname()
                + ", false)");
        ifNotNull2.addToThenPart(
            propertyWrapper.remover() + "(" + propertyWrapper.fieldname() + ")");
        owner.addToImports(
            UmlgClassOperations.getPathName(otherEnd.getOwningType())
                .append(UmlgClassOperations.propertyEnumName(otherEnd.getOwningType())));
        singleAdder.getBody().addToStatements(ifNotNull2);
      }
      OJIfStatement ifNotNull = new OJIfStatement(propertyWrapper.fieldname() + " != null");

      // Add in validations

      OJBlock block;
      if (propertyWrapper.isDataType()) {
        OJField failedConstraints =
            new OJField(
                "violations",
                new OJPathName("java.util.List")
                    .addToGenerics(UmlgGenerationUtil.UmlgConstraintViolation));
        failedConstraints.setInitExp(
            propertyWrapper.validator() + "(" + propertyWrapper.fieldname() + ")");
        ifNotNull.getThenPart().addToLocals(failedConstraints);
        OJIfStatement ifValidated = new OJIfStatement("violations.isEmpty()");
        ifValidated.addToElsePart(
            "throw new "
                + UmlgGenerationUtil.UmlgConstraintViolationException.getLast()
                + "(violations)");
        owner.addToImports(UmlgGenerationUtil.UmlgConstraintViolationException);
        ifNotNull.addToThenPart(ifValidated);
        block = ifValidated.getThenPart();
      } else {
        block = ifNotNull.getThenPart();
      }

      if (!propertyWrapper.isMemberOfAssociationClass()) {
        if (!indexed) {
          if (!ignoreInverse) {
            block.addToStatements(
                "this."
                    + propertyWrapper.fieldname()
                    + ".add("
                    + propertyWrapper.fieldname()
                    + ")");
          } else {
            block.addToStatements(
                "this."
                    + propertyWrapper.fieldname()
                    + ".addIgnoreInverse("
                    + propertyWrapper.fieldname()
                    + ")");
          }
        } else {
          block.addToStatements(
              "this."
                  + propertyWrapper.fieldname()
                  + ".add(index, "
                  + propertyWrapper.fieldname()
                  + ")");
        }
      } else {
        if (!indexed) {
          block.addToStatements(
              "this."
                  + propertyWrapper.fieldname()
                  + ".add("
                  + propertyWrapper.fieldname()
                  + ", "
                  + StringUtils.uncapitalize(propertyWrapper.getAssociationClass().getName())
                  + ")");
        } else {
          block.addToStatements(
              "this."
                  + propertyWrapper.fieldname()
                  + ".add(index, "
                  + propertyWrapper.fieldname()
                  + ", "
                  + StringUtils.uncapitalize(propertyWrapper.getAssociationClass().getName())
                  + ")");
        }
      }
      singleAdder.getBody().addToStatements(ifNotNull);
    }
    owner.addToOperations(singleAdder);

    //        //Add change listener
    //        if (propertyWrapper.isChangedListener()) {
    //            PropertyChangeNotificationBuilder.buildChangeNotification(owner, singleAdder,
    // propertyWrapper, PropertyChangeNotificationBuilder.CHANGE_TYPE.ADD);
    //        }

  }
 /** 获取所管理的对象列表名. 首字母小写,如"users". */
 protected String getEntityListName() {
   return StringUtils.uncapitalize(ClassUtils.getShortName(getEntityClass())) + "s";
 }
 private String createMethodNameFromAnnotation(Class<? extends Annotation> annotation) {
   return StringUtils.uncapitalize(annotation.getSimpleName());
 }
  @Override
  protected String generate(TreeLogger logger, GeneratorContext context) {
    final ClassStructureBuilder<?> classBuilder =
        Implementations.extend(NavigationGraph.class, GENERATED_CLASS_NAME);

    // accumulation of (name, pageclass) mappings for dupe detection and dot file generation
    BiMap<String, MetaClass> pageNames = HashBiMap.create();

    // accumulation UniquePageRoles for ensuring there is exactly one.
    Multimap<Class<?>, MetaClass> pageRoles = ArrayListMultimap.create();

    ConstructorBlockBuilder<?> ctor = classBuilder.publicConstructor();
    final Collection<MetaClass> pages = ClassScanner.getTypesAnnotatedWith(Page.class, context);
    for (MetaClass pageClass : pages) {
      if (!pageClass.isAssignableTo(IsWidget.class)) {
        throw new GenerationException(
            "Class "
                + pageClass.getFullyQualifiedName()
                + " is annotated with @Page, so it must implement IsWidget");
      }
      Page annotation = pageClass.getAnnotation(Page.class);
      String pageName = getPageName(pageClass);
      List<Class<? extends PageRole>> annotatedPageRoles = Arrays.asList(annotation.role());

      MetaClass prevPageWithThisName = pageNames.put(pageName, pageClass);
      if (prevPageWithThisName != null) {
        throw new GenerationException(
            "Page names must be unique, but "
                + prevPageWithThisName
                + " and "
                + pageClass
                + " are both named ["
                + pageName
                + "]");
      }
      Statement pageImplStmt = generateNewInstanceOfPageImpl(pageClass, pageName);
      if (annotatedPageRoles.contains(DefaultPage.class)) {
        // need to assign the page impl to a variable and add it to the map twice
        ctor.append(Stmt.declareFinalVariable("defaultPage", PageNode.class, pageImplStmt));
        pageImplStmt = Variable.get("defaultPage");
        ctor.append(Stmt.nestedCall(Refs.get("pagesByName")).invoke("put", "", pageImplStmt));
        ctor.append(
            Stmt.nestedCall(Refs.get("pagesByRole"))
                .invoke("put", DefaultPage.class, pageImplStmt));
      } else if (pageName.equals("")) {
        throw new GenerationException(
            "Page "
                + pageClass.getFullyQualifiedName()
                + " has an empty path. Only the"
                + " page with startingPage=true is permitted to have an empty path.");
      }

      final String fieldName = StringUtils.uncapitalize(pageClass.getName());
      ctor.append(Stmt.declareFinalVariable(fieldName, PageNode.class, pageImplStmt));
      ctor.append(
          Stmt.nestedCall(Refs.get("pagesByName")).invoke("put", pageName, Refs.get(fieldName)));

      for (Class<? extends PageRole> annotatedPageRole : annotatedPageRoles) {
        pageRoles.put(annotatedPageRole, pageClass);
        // DefaultPage is already added above.
        if (!annotatedPageRole.equals(DefaultPage.class))
          ctor.append(
              Stmt.nestedCall(Refs.get("pagesByRole"))
                  .invoke("put", annotatedPageRole, Refs.get(fieldName)));
      }
    }
    ctor.finish();

    renderNavigationToDotFile(pageNames);

    validateDefaultPagePresent(pages, pageRoles);
    validateUnique(pageRoles);

    return classBuilder.toJavaString();
  }