Exemplo n.º 1
0
  /**
   * @param xstreamObject not null
   * @param jarFile not null
   * @param packageFilter a package name to filter.
   */
  private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
      jarStream = new JarInputStream(new FileInputStream(jarFile));
      JarEntry jarEntry = jarStream.getNextJarEntry();
      while (jarEntry != null) {
        if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
          String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
          name = name.replaceAll("/", "\\.");

          if (name.indexOf(packageFilter) != -1) {
            try {
              Class<?> clazz = ClassUtils.getClass(name);
              String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
              xstreamObject.alias(alias, clazz);
              if (!clazz.equals(Model.class)) {
                xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
              }
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }
          }
        }

        jarStream.closeEntry();
        jarEntry = jarStream.getNextJarEntry();
      }
    } catch (IOException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("IOException: " + e.getMessage(), e);
      }
    } finally {
      IOUtil.close(jarStream);
    }
  }
  public boolean runWithEntity(IEntity<?> entity) {
    super.beforeRun();

    boolean result = false;

    /* Verifica se a entidade é compatível */
    /* Verifica se a entidade passada eh um DocumentoCobranca ou pertence eh descendente */
    if (ClassUtils.isAssignable(entity.getInfo().getType(), Contrato.class)) {
      Contrato oContrato = (Contrato) entity.getObject();
      this.cpfCnpj = oContrato.getPessoa().getDocumento();

      /* Alguns dados poderao ser inicializados aqui */
      this.categoriaContratoId = IDAO.ENTITY_UNSAVED;

      /* Define as datas de vencimento e recebimento amplas */
      Calendar dataInicial = CalendarUtils.getCalendar(1900, Calendar.JANUARY, 1);
      Calendar dataAtual = CalendarUtils.getCalendar();

      this.dataVencimentoInicial = (Calendar) dataInicial.clone();
      this.dataVencimentoFinal = (Calendar) dataAtual.clone();

      this.dataRecebimentoInicial = (Calendar) dataInicial.clone();
      this.dataRecebimentoFinal = (Calendar) dataAtual.clone();

      /* Não executa nada, pois o processo gera um PDF e é importante
       * que o operador defina as propriedades do relatório antes de gerar o PDF */
      result = true;
    } else if (ClassUtils.isAssignable(entity.getInfo().getType(), Pessoa.class)) {
      Pessoa oPessoa = (Pessoa) entity.getObject();
      this.cpfCnpj = oPessoa.getDocumento();

      /* Alguns dados poderao ser inicializados aqui */
      this.categoriaContratoId = IDAO.ENTITY_UNSAVED;

      /* Define as datas de vencimento e recebimento amplas */
      Calendar dataInicial = CalendarUtils.getCalendar(1900, Calendar.JANUARY, 1);
      Calendar dataAtual = CalendarUtils.getCalendar();

      this.dataVencimentoInicial = (Calendar) dataInicial.clone();
      this.dataVencimentoFinal = (Calendar) dataAtual.clone();

      this.dataRecebimentoInicial = (Calendar) dataInicial.clone();
      this.dataRecebimentoFinal = (Calendar) dataAtual.clone();

      /* Não executa nada, pois o processo gera um PDF e é importante
       * que o operador defina as propriedades do relatório antes de gerar o PDF */
      result = true;
    } else {
      this.getMessageList()
          .add(
              new BusinessMessage(
                  IRunnableEntityProcess.class,
                  "ENTITY_NOT_COMPATIBLE",
                  PROCESS_NAME,
                  entity.getInfo().getType().getName()));
    }

    return result;
  }
Exemplo n.º 3
0
 private static boolean shouldKeep(
     Class type, Object extension, @Nullable Project project, @Nullable ExtensionMatcher matcher) {
   boolean keep =
       (ClassUtils.isAssignable(extension.getClass(), type)
               || (org.sonar.api.batch.Sensor.class.equals(type)
                   && ClassUtils.isAssignable(extension.getClass(), Sensor.class)))
           && (matcher == null || matcher.accept(extension));
   if (keep
       && project != null
       && ClassUtils.isAssignable(extension.getClass(), CheckProject.class)) {
     keep = ((CheckProject) extension).shouldExecuteOnProject(project);
   }
   return keep;
 }
Exemplo n.º 4
0
  public void removeListener(NodeListener listener) {
    if (logger.isDebugEnabled()) {
      logger.debug("## remove listener [{}]", ClassUtils.getShortClassName(listener.getClass()));
    }

    this.listeners.remove(listener);
  }
Exemplo n.º 5
0
 public static Class loadClass(ClassLoader classLoader, String className)
     throws ClassNotFoundException {
   if (classLoader == null) {
     classLoader = Thread.currentThread().getContextClassLoader();
   }
   return org.apache.commons.lang.ClassUtils.getClass(classLoader, className);
 }
Exemplo n.º 6
0
  public void addListener(NodeListener listener) {
    if (logger.isDebugEnabled()) {
      logger.debug(
          "## pipeline[{}] add listener [{}]", ClassUtils.getShortClassName(listener.getClass()));
    }

    this.listeners.add(listener);
  }
Exemplo n.º 7
0
  public static void main(String[] args) throws Exception {
    initLogName("CreateExportDataBat.log");
    configInit(ClassUtils.getShortClassName(CreateExportDataBat.class));

    CreateExportDataBat bat = new CreateExportDataBat();
    bat.dbInit();
    bat.start();
  }
Exemplo n.º 8
0
 private static Class<?>[] getAllInterfaces(Class<?> baseClass) {
   List interfaces = ClassUtils.getAllInterfaces(baseClass);
   Class<?>[] result = new Class<?>[interfaces.size()];
   int i = 0;
   for (Object o : interfaces) {
     result[i++] = (Class<?>) o;
   }
   return result;
 }
  /** {@inheritDoc} */
  @SuppressWarnings({"unchecked", "rawtypes"})
  public ControlAccessor getControlAccessor(Object control) {
    Class<? extends ControlAccessor> accessorClass = null;
    ControlAccessor accessor = null;
    Class<? extends Object> clazz = control.getClass();

    accessorClass = accessors.get(clazz);

    if (accessorClass == null) { // try with superclasses

      List superclasses = ClassUtils.getAllSuperclasses(clazz);
      superclasses.addAll(ClassUtils.getAllInterfaces(clazz));
      Iterator iter = superclasses.iterator();

      while (iter.hasNext() && accessorClass == null) {
        accessorClass = accessors.get(iter.next());
      }
    }

    if (accessorClass != null) {
      try {
        Constructor<? extends ControlAccessor> ctor = accessorClass.getConstructor(Object.class);
        accessor = ctor.newInstance(control);
      } catch (InstantiationException e) {
        log.error(e);
      } catch (IllegalAccessException e) {
        log.error(e);
      } catch (SecurityException e) {
        log.error(e);
      } catch (NoSuchMethodException e) {
        log.error(e);
      } catch (IllegalArgumentException e) {
        log.error(e);
      } catch (InvocationTargetException e) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(baos));
        log.error(baos);
      }
    } else {
      log.warn("Can't find a accessor for class: " + clazz.getName());
    }

    return accessor;
  }
Exemplo n.º 10
0
 static {
   try {
     responseSetCharacterEncodingAvailable =
         ClassUtils.getPublicMethod(
                 HttpServletResponse.class, "setCharacterEncoding", new Class[] {String.class})
             != null;
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 11
0
  public static <T> T create(String pClassName, Class<T> pClass)
      throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    final Object o = create(pClassName);

    if (ClassUtils.isAssignable(o.getClass(), pClass)) {
      return (T) o;
    } else {
      throw new InstantiationException("Not of type: " + pClass.getName());
    }
  }
Exemplo n.º 12
0
  /**
   * Contructor to be used by all child classes to create a new instance and get the name right.
   *
   * @param clazz the Grails class
   * @param trailingName the trailing part of the name for this class type
   */
  public AbstractGrailsClass(Class clazz, String trailingName) {
    super();
    setClazz(clazz);

    this.reference = new BeanWrapperImpl(newInstance());
    this.fullName = clazz.getName();
    this.packageName = ClassUtils.getPackageName(clazz);
    this.naturalName = GrailsNameUtils.getNaturalName(clazz.getName());
    this.shortName = getShortClassname(clazz);
    this.name = GrailsNameUtils.getLogicalName(clazz, trailingName);
  }
 public PreparedStatementCallbackReturnId(PreparedStatementSetter setter, Class<?> returnType) {
   this.setter = setter;
   if (returnType.isPrimitive()) {
     returnType = ClassUtils.primitiveToWrapper(returnType);
   }
   this.returnType = returnType;
   Class<?> idType = returnType;
   if (returnType.isArray()) {
     idType = returnType.getComponentType();
   }
   this.idType = idType;
   if (idType.isPrimitive()) {
     idType = ClassUtils.primitiveToWrapper(idType);
   }
   this.wrappedIdType = idType;
   this.mapper = new SingleColumnRowMapper(idType);
   if (wrappedIdType != Integer.class && wrappedIdType != Long.class) {
     throw new IllegalArgumentException(
         "wrong return type(int/long type or its array type only): " + returnType);
   }
 }
Exemplo n.º 14
0
 /**
  * Gets the criteria.
  *
  * @param values the values
  * @param bean the bean
  * @return the criteria
  * @throws ManagerBeanException the manager bean exception
  * @throws ExpressionException the expression exception
  */
 private Criteria getCriteria(IManagerBean bean, Object[] values)
     throws ManagerBeanException, ExpressionException {
   Criteria criteria = null;
   if (values != null) {
     criteria = new Criteria();
     String prefix = ClassUtils.getShortClassName(bean.getPOJOClass()) + "_";
     for (int i = 0; i < values.length; i++) {
       String fieldName = bean.getFieldName(prefix + getForeignJoinProperties().get(i));
       if (values[i] != null) {
         criteria.addExpression(fieldName, values[i].toString());
       } else {
         criteria.addNullExpression(fieldName);
       }
     }
   }
   return criteria;
 }
 @Override
 public String getOptions() {
   AssertUtil.parameterEmpty(getField().getRelationClass(), "getField().getRelationClass()");
   try {
     List<? extends BaseEnum> items =
         EnumUtils.getEnumList(ClassUtils.getClass(getField().getRelationClass()));
     StringBuffer buffer = new StringBuffer();
     for (BaseEnum item : items) {
       buffer.append(
           "<option value='" + ((Enum) item).name() + "'>" + item.getTitle() + "</option>");
     }
     return buffer.toString();
   } catch (ClassNotFoundException e) {
     log.error("枚举类型[" + getField().getRelationClass() + "]创建失败,错误信息:" + e.getMessage());
   }
   return "";
 }
Exemplo n.º 16
0
 /*  17:    */
 /*  18:    */ public static Field getField(Class cls, String fieldName, boolean forceAccess)
       /*  19:    */ {
   /*  20: 78 */ if (cls == null) {
     /*  21: 79 */ throw new IllegalArgumentException("The class must not be null");
     /*  22:    */ }
   /*  23: 81 */ if (fieldName == null) {
     /*  24: 82 */ throw new IllegalArgumentException("The field name must not be null");
     /*  25:    */ }
   /*  26: 98 */ for (Class acls = cls; acls != null; acls = acls.getSuperclass()) {
     /*  27:    */ try
     /*  28:    */ {
       /*  29:100 */ Field field = acls.getDeclaredField(fieldName);
       /*  30:103 */ if (!Modifier.isPublic(field.getModifiers())) {
         /*  31:104 */ if (forceAccess) {
           /*  32:105 */ field.setAccessible(true);
           /*  33:    */ } else {
           /*  34:    */ continue;
           /*  35:    */ }
         /*  36:    */ }
       /*  37:110 */ return field;
       /*  38:    */ }
     /*  39:    */ catch (NoSuchFieldException ex) {
     }
     /*  40:    */ }
   /*  41:118 */ Field match = null;
   /*  42:119 */ Iterator intf = ClassUtils.getAllInterfaces(cls).iterator();
   /*  43:120 */ while (intf.hasNext()) {
     /*  44:    */ try
     /*  45:    */ {
       /*  46:122 */ Field test = ((Class) intf.next()).getField(fieldName);
       /*  47:123 */ if (match != null) {
         /*  48:124 */ throw new IllegalArgumentException(
             "Reference to field "
                 + fieldName
                 + " is ambiguous relative to "
                 + cls
                 + "; a matching field exists on two or more implemented interfaces.");
         /*  49:    */ }
       /*  50:131 */ match = test;
       /*  51:    */ }
     /*  52:    */ catch (NoSuchFieldException ex) {
     }
     /*  53:    */ }
   /*  54:136 */ return match;
   /*  55:    */ }
Exemplo n.º 17
0
  @SuppressWarnings("unchecked")
  public static Map<String, Field> getAllFieldMap(Class<?> resultClass) {
    List<Class<?>> allSuperclasses = ClassUtils.getAllSuperclasses(resultClass);

    Map<String, Field> m = new HashMap<String, Field>();
    for (Class<?> one : allSuperclasses) {
      Field[] fields = one.getDeclaredFields();
      for (Field o : fields) {
        m.put(o.getName(), o);
      }
    }
    Field[] fields = resultClass.getDeclaredFields();
    for (Field o : fields) {
      m.put(o.getName(), o);
    }

    return m;
  }
  /**
   * 从{@link #handleres handleres}的<code>key</code>的迭代器中找出参数<code>clazz</code> 最近的父类
   *
   * @param clazz 异常类型
   * @return 参数<code>clazz</code>最近的父类, 如果参数没有直接的父类返回<code>null</code>
   */
  private Class findSuperClass(Iterator iterator, Class clazz) {
    Class ret = null;
    List classes = ClassUtils.getAllSuperclasses(clazz);
    int minIndex = -1;
    while (iterator.hasNext()) {
      Class candidate = (Class) iterator.next();
      int candidateIndex = classes.indexOf(candidate);
      if (minIndex == -1 || (candidateIndex != -1 && candidateIndex < minIndex)) {
        minIndex = candidateIndex;
      }
    }

    if (minIndex > -1) {
      ret = (Class) classes.get(minIndex);
    }

    return ret;
  }
Exemplo n.º 19
0
  private static StringParser getParserFor(Class<?> fieldType) {
    String typeName;
    if (fieldType.isPrimitive()) {
      typeName = ClassUtils.primitiveToWrapper(fieldType).getSimpleName();
    } else {
      typeName = fieldType.getSimpleName();
    }
    try {
      Class<?> parserClass =
          Class.forName("com.martiansoftware.jsap.stringparsers." + typeName + "StringParser");

      Method getParser = parserClass.getMethod("getParser", new Class<?>[] {});

      return (StringParser) getParser.invoke(null, new Object[] {});

    } catch (ClassNotFoundException e) {
      throw new NoJSAPParserForThisTypeException(
          "JSAP parameters can not be made out of type " + typeName);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 20
0
  /**
   * @param expression the user expression.
   * @param obj a not null.
   * @return the XML for the given object.
   */
  private String toXML(String expression, Object obj) {
    XStream currentXStream = getXStream();

    // beautify list
    if (obj instanceof List) {
      List<?> list = (List<?>) obj;
      if (list.size() > 0) {
        Object elt = list.iterator().next();

        String name =
            StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(elt.getClass()));
        currentXStream.alias(pluralize(name), List.class);
      } else {
        // try to detect the alias from question
        if (expression.indexOf(".") != -1) {
          String name = expression.substring(expression.indexOf(".") + 1, expression.indexOf("}"));
          currentXStream.alias(name, List.class);
        }
      }
    }

    return currentXStream.toXML(obj);
  }
Exemplo n.º 21
0
 /**
  * Find an accessible method that matches the given name and has compatible parameters. Compatible
  * parameters mean that every method parameter is assignable from the given parameters. In other
  * words, it finds a method with the given name that will take the parameters given.
  *
  * <p>
  *
  * <p>This method is used by {@link #invokeMethod(Object object, String methodName, Object[] args,
  * Class[] parameterTypes)}.
  *
  * <p>This method can match primitive parameter by passing in wrapper classes. For example, a
  * <code>Boolean</code> will match a primitive <code>boolean</code> parameter.
  *
  * @param cls find method in this class
  * @param methodName find method with this name
  * @param parameterTypes find method with most compatible parameters
  * @return The accessible method
  */
 public static Method getMatchingAccessibleMethod(
     Class cls, String methodName, Class[] parameterTypes) {
   try {
     Method method = cls.getMethod(methodName, parameterTypes);
     MemberUtils.setAccessibleWorkaround(method);
     return method;
   } catch (NoSuchMethodException e) {
     /* SWALLOW */
   }
   // search through all methods
   Method bestMatch = null;
   Method[] methods = cls.getMethods();
   for (int i = 0, size = methods.length; i < size; i++) {
     if (methods[i].getName().equals(methodName)) {
       // compare parameters
       if (ClassUtils.isAssignable(parameterTypes, methods[i].getParameterTypes(), true)) {
         // get accessible version of method
         Method accessibleMethod = getAccessibleMethod(methods[i]);
         if (accessibleMethod != null) {
           if (bestMatch == null
               || MemberUtils.compareParameterTypes(
                       accessibleMethod.getParameterTypes(),
                       bestMatch.getParameterTypes(),
                       parameterTypes)
                   < 0) {
             bestMatch = accessibleMethod;
           }
         }
       }
     }
   }
   if (bestMatch != null) {
     MemberUtils.setAccessibleWorkaround(bestMatch);
   }
   return bestMatch;
 }
Exemplo n.º 22
0
 /** Just for debug purposes. {@inheritDoc} */
 @Override
 public String toString() {
   return ClassUtils.getShortClassName(getClass()) + "[<" + getTagName() + " ...>]";
 }
 final Class<?> type(String name) throws Exception {
   return ClassUtils.getClass(name);
 }
Exemplo n.º 24
0
 public static <T> FromBytes<T> getPrimitiveFromBytes(Class<T> clazz) {
   if (clazz.isPrimitive()) {
     return convertMap.get(ClassUtils.primitiveToWrapper(clazz));
   }
   return convertMap.get(clazz);
 }
Exemplo n.º 25
0
  /**
   * gets the annotation but also adds an import in the process if a Convert annotation is required.
   */
  @Override
  protected NodeData getAnnotationNodes(
      String enclosingClass, String fieldName, String mappedClass) {
    final ObjectReferenceDescriptor ord =
        OjbUtil.findObjectReferenceDescriptor(mappedClass, fieldName, descriptorRepositories);
    if (ord != null) {
      final List<MemberValuePair> pairs = new ArrayList<MemberValuePair>();
      final Collection<ImportDeclaration> additionalImports = new ArrayList<ImportDeclaration>();

      final Collection<String> fks = ord.getForeignKeyFields();
      if (fks == null || fks.isEmpty()) {
        LOG.error(
            ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                + " field has a reference descriptor for "
                + fieldName
                + " but does not have any foreign keys configured");
        return null;
      }

      final Collection<String> pks =
          OjbUtil.getPrimaryKeyNames(mappedClass, descriptorRepositories);

      if (!(pks.size() == fks.size() && pks.containsAll(fks))) {
        final String className = ord.getItemClassName();
        if (StringUtils.isBlank(className)) {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has a reference descriptor for "
                  + fieldName
                  + " but does not class name attribute");
        } else {
          final String shortClassName = ClassUtils.getShortClassName(className);
          final String packageName = ClassUtils.getPackageName(className);
          pairs.add(new MemberValuePair("targetEntity", new NameExpr(shortClassName + ".class")));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(packageName), shortClassName), false, false));
        }

        final boolean proxy = ord.isLazy();
        if (proxy) {
          pairs.add(new MemberValuePair("fetch", new NameExpr("FetchType.LAZY")));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(PACKAGE), "FetchType"), false, false));
        }

        final boolean refresh = ord.isRefresh();
        if (refresh) {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has refresh set to "
                  + refresh
                  + ", unsupported conversion to @OneToOne attributes");
        }

        final List<Expression> cascadeTypes = new ArrayList<Expression>();
        final boolean autoRetrieve = ord.getCascadeRetrieve();
        if (autoRetrieve) {
          cascadeTypes.add(new NameExpr("CascadeType.REFRESH"));
        } else {
          // updated default logging - false would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-retrieve set to "
                    + autoRetrieve
                    + ", unsupported conversion to CascadeType");
          }
        }

        final int autoDelete = ord.getCascadingDelete();
        if (autoDelete == ObjectReferenceDescriptor.CASCADE_NONE) {
          // updated default logging - none would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-delete set to none, unsupported conversion to CascadeType");
          }
        } else if (autoDelete == ObjectReferenceDescriptor.CASCADE_LINK) {
          LOG.warn(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-delete set to link, unsupported conversion to CascadeType");
        } else if (autoDelete == ObjectReferenceDescriptor.CASCADE_OBJECT) {
          cascadeTypes.add(new NameExpr("CascadeType.REMOVE"));
        } else {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-delete set to an invalid value");
        }

        final int autoUpdate = ord.getCascadingStore();
        if (autoUpdate == ObjectReferenceDescriptor.CASCADE_NONE) {
          // updated default logging - none would result no additional annotations
          if (LOG.isDebugEnabled()) {
            LOG.debug(
                ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                    + " field has auto-update set to none, unsupported conversion to CascadeType");
          }
        } else if (autoUpdate == ObjectReferenceDescriptor.CASCADE_LINK) {
          LOG.warn(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-update set to link, unsupported conversion to CascadeType");
        } else if (autoUpdate == ObjectReferenceDescriptor.CASCADE_OBJECT) {
          cascadeTypes.add(new NameExpr("CascadeType.PERSIST"));
        } else {
          LOG.error(
              ResolverUtil.logMsgForField(enclosingClass, fieldName, mappedClass)
                  + " field has auto-update set to an invalid value");
        }

        if (!cascadeTypes.isEmpty()) {
          pairs.add(new MemberValuePair("cascade", new ArrayInitializerExpr(cascadeTypes)));
          additionalImports.add(
              new ImportDeclaration(
                  new QualifiedNameExpr(new NameExpr(PACKAGE), "CascadeType"), false, false));
        }

        return new NodeData(
            new NormalAnnotationExpr(new NameExpr(SIMPLE_NAME), pairs),
            new ImportDeclaration(
                new QualifiedNameExpr(new NameExpr(PACKAGE), SIMPLE_NAME), false, false),
            additionalImports);
      }
    }
    return null;
  }
 private Class<?> findClass(String name) throws ClassNotFoundException {
   return ClassUtils.getClass(getClass().getClassLoader(), name, false);
 }
Exemplo n.º 27
0
  /**
   * http form multipart form post
   *
   * @param connection
   * @param activationContent
   * @throws ExchangeException
   */
  public static void transport(URLConnection connection, ActivationContent activationContent)
      throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setUseCaches(false);
      connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
      connection.setRequestProperty("Cache-Control", "no-cache");

      outStream = new DataOutputStream(connection.getOutputStream());
      outStream.writeBytes("--" + BOUNDARY + "\r\n");

      // set all resources from activationContent
      Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
      while (fileNameIterator.hasNext()) {
        String fileName = (String) fileNameIterator.next();
        fis = new FileInputStream(activationContent.getFile(fileName));
        outStream.writeBytes(
            "content-disposition: form-data; name=\""
                + fileName
                + "\"; filename=\""
                + fileName
                + "\"\r\n");
        outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
        while (true) {
          synchronized (buffer) {
            int amountRead = fis.read(buffer);
            if (amountRead == -1) {
              break;
            }
            outStream.write(buffer, 0, amountRead);
          }
        }
        fis.close();
        outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
      }
      outStream.flush();
      outStream.close();

      log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
      throw new ExchangeException(
          "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          log.error("Exception caught", e);
        }
      }
      if (outStream != null) {
        try {
          outStream.close();
        } catch (IOException e) {
          log.error("Exception caught", e);
        }
      }
    }
  }
Exemplo n.º 28
0
  public static void copyModeltoModel(Object src, Object des) {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(des); // 得到to对象的字段属性集合
    for (int i = 0; i < pds.length; i++) {
      try {
        // 得到to对象的属性的类型
        String toClassName = ClassUtils.getShortClassName(pds[i].getPropertyType());
        // 根据此字段名去from对象查找 如果找不到则跳过 继续下一个to字段的赋值
        PropertyDescriptor descriptor = null;
        try {
          descriptor = PropertyUtils.getPropertyDescriptor(src, pds[i].getDisplayName());
          if (descriptor == null) {
            continue; // Skip this property setter
          }
        } catch (NoSuchMethodException e) {
          continue; // Skip this property setter
        }
        // 得到form对象该字段的类型
        String fromClassName = ClassUtils.getShortClassName(descriptor.getPropertyType());

        if ("Class".equals(toClassName)) {
          continue;
        } else {
          // 得到form字段该字段的值 如果有值则赋值 否则继续下一个
          // System.out.println("\n\n\n pds[i].getDisplayName()=" +
          // pds[i].getDisplayName() + "\n\n\n");
          Object o = PropertyUtils.getProperty(src, pds[i].getDisplayName());
          if (o != null) {
            if (toClassName.equals("Date") && fromClassName.equals("String")) { // 如果form该字段是字符串
              // o = Helper.switchDate((String) o);
              // BeanUtils.setProperty(des,
              // pds[i].getDisplayName(), o);
              ConvertUtilsBean convertUtils = new ConvertUtilsBean();
              convertUtils.register(new DateConverter(), Date.class);
              BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils, new PropertyUtilsBean());
              o = Helper.switchDate((String) o);
              beanUtils.setProperty(des, pds[i].getDisplayName(), o);
            } else if (toClassName.equals("String") && fromClassName.equals("Date")) {
              o = DateUtil.toStringByFormat((Date) o, "yyyy-MM-dd HH:mm:ss");
              if (org.apache.commons.lang.StringUtils.contains((String) o, "00:00:00")) {
                o =
                    org.apache.commons.lang.StringUtils.substringBeforeLast((String) o, "00:00:00")
                        .trim();
              }
              org.apache.commons.beanutils.BeanUtils.setProperty(des, pds[i].getDisplayName(), o);
            } else if (toClassName.equals("Date") && fromClassName.equals("Date")) {
              ConvertUtilsBean convertUtils = new ConvertUtilsBean();
              convertUtils.register(new DateConverter(), Date.class);
              BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils, new PropertyUtilsBean());
              beanUtils.setProperty(des, pds[i].getDisplayName(), o);
              // BeanUtils.setProperty(des,
              // pds[i].getDisplayName(), o);
            } else {
              org.apache.commons.beanutils.BeanUtils.setProperty(des, pds[i].getDisplayName(), o);
            }
            // org.apache.commons.beanutils.BeanUtils.setProperty(des,pds[i].getDisplayName(),o);
          }
        }
      } catch (Exception ex) {
        // System.out.println("赋值失败:" + ex);
      }
    }
  }
Exemplo n.º 29
0
 private static String getShortClassname(Class clazz) {
   return ClassUtils.getShortClassName(clazz);
 }
Exemplo n.º 30
0
  // ======================== help method ===================
  // 保存对应的dbBatch
  private HttpPipeKey saveDbBatch(DbBatch dbBatch) {
    RowBatch rowBatch = dbBatch.getRowBatch();
    // 转化为proto对象
    BatchProto.RowBatch.Builder rowBatchBuilder = BatchProto.RowBatch.newBuilder();
    rowBatchBuilder.setIdentity(build(rowBatch.getIdentity()));
    // 处理具体的字段rowData
    for (EventData eventData : rowBatch.getDatas()) {
      BatchProto.RowData.Builder rowDataBuilder = BatchProto.RowData.newBuilder();
      rowDataBuilder.setPairId(eventData.getPairId());
      rowDataBuilder.setTableId(eventData.getTableId());
      if (eventData.getSchemaName() != null) {
        rowDataBuilder.setSchemaName(eventData.getSchemaName());
      }
      rowDataBuilder.setTableName(eventData.getTableName());
      rowDataBuilder.setEventType(eventData.getEventType().getValue());
      rowDataBuilder.setExecuteTime(eventData.getExecuteTime());
      // add by ljh at 2012-10-31
      if (eventData.getSyncMode() != null) {
        rowDataBuilder.setSyncMode(eventData.getSyncMode().getValue());
      }
      if (eventData.getSyncConsistency() != null) {
        rowDataBuilder.setSyncConsistency(eventData.getSyncConsistency().getValue());
      }

      // 构造key column
      for (EventColumn keyColumn : eventData.getKeys()) {
        rowDataBuilder.addKeys(buildColumn(keyColumn));
      }
      // 构造old key column
      if (CollectionUtils.isEmpty(eventData.getOldKeys()) == false) {
        for (EventColumn keyColumn : eventData.getOldKeys()) {
          rowDataBuilder.addOldKeys(buildColumn(keyColumn));
        }
      }

      // 构造其他 column
      for (EventColumn column : eventData.getColumns()) {
        rowDataBuilder.addColumns(buildColumn(column));
      }

      rowDataBuilder.setRemedy(eventData.isRemedy());
      rowDataBuilder.setSize(eventData.getSize());
      rowBatchBuilder.addRows(rowDataBuilder.build()); // 添加一条rowData记录
    }

    // 处理下FileBatch
    FileBatch fileBatch = dbBatch.getFileBatch();
    BatchProto.FileBatch.Builder fileBatchBuilder = null;
    fileBatchBuilder = BatchProto.FileBatch.newBuilder();
    fileBatchBuilder.setIdentity(build(fileBatch.getIdentity()));
    // 构造对应的proto对象
    for (FileData fileData : fileBatch.getFiles()) {
      BatchProto.FileData.Builder fileDataBuilder = BatchProto.FileData.newBuilder();
      fileDataBuilder.setPairId(fileData.getPairId());
      fileDataBuilder.setTableId(fileData.getTableId());
      if (fileData.getNameSpace() != null) {
        fileDataBuilder.setNamespace(fileData.getNameSpace());
      }
      if (fileData.getPath() != null) {
        fileDataBuilder.setPath(fileData.getPath());
      }
      fileDataBuilder.setEventType(fileData.getEventType().getValue());
      fileDataBuilder.setSize(fileData.getSize());
      fileDataBuilder.setLastModifiedTime(fileData.getLastModifiedTime());

      fileBatchBuilder.addFiles(fileDataBuilder.build()); // 添加一条fileData记录
    }
    // 处理构造对应的文件url
    String filename =
        buildFileName(rowBatch.getIdentity(), ClassUtils.getShortClassName(dbBatch.getClass()));
    // 写入数据
    File file = new File(htdocsDir, filename);
    OutputStream output = null;
    try {
      output = new BufferedOutputStream(new FileOutputStream(file));
      com.alibaba.otter.node.etl.model.protobuf.BatchProto.RowBatch rowBatchProto =
          rowBatchBuilder.build();
      output.write(ByteUtils.int2bytes(rowBatchProto.getSerializedSize())); // 输出大小
      rowBatchProto.writeTo(output); // 输出row batch

      com.alibaba.otter.node.etl.model.protobuf.BatchProto.FileBatch fileBatchProto =
          fileBatchBuilder.build();
      output.write(ByteUtils.int2bytes(fileBatchProto.getSerializedSize())); // 输出大小
      fileBatchProto.writeTo(output); // 输出file batch
      output.flush();
    } catch (IOException e) {
      throw new PipeException("write_byte_error", e);
    } finally {
      IOUtils.closeQuietly(output);
    }

    HttpPipeKey key = new HttpPipeKey();
    key.setUrl(remoteUrlBuilder.getUrl(rowBatch.getIdentity().getPipelineId(), filename));
    key.setDataType(PipeDataType.DB_BATCH);
    key.setIdentity(rowBatch.getIdentity());
    Pipeline pipeline = configClientService.findPipeline(rowBatch.getIdentity().getPipelineId());
    if (pipeline.getParameters().getUseFileEncrypt()) {
      // 加密处理
      EncryptedData encryptedData = encryptFile(file);
      key.setKey(encryptedData.getKey());
      key.setCrc(encryptedData.getCrc());
    }

    return key;
  }