/**
  * utility method that generically returns a criterion using methods in Restrictions
  *
  * @param constraintName - the criteria
  */
 protected Criterion callRestrictionsMethod(
     String constraintName, Class<?>[] paramTypes, Object[] params) {
   final Method restrictionsMethod =
       ReflectionUtils.findMethod(Restrictions.class, constraintName, paramTypes);
   Assert.notNull(
       restrictionsMethod,
       "Could not find method: "
           + constraintName
           + " in class Restrictions for parameters: "
           + ArrayUtils.toString(params)
           + " with types: "
           + ArrayUtils.toString(paramTypes));
   return (Criterion) ReflectionUtils.invokeMethod(restrictionsMethod, null, params);
 }
Пример #2
0
 @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW)
 public void readBatch() throws Exception {
   List<User> users1 = userMapper.findByAge("10");
   System.out.println(
       String.format(
           "当前readBatch线程%s,读取用户信息,用户%s,时间戳%tc",
           Thread.currentThread(), ArrayUtils.toString(users1.toArray()), new Date()));
   try {
     TimeUnit.SECONDS.sleep(5);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
   List<User> users2 = userMapper.findByAge("10");
   System.out.println(
       String.format(
           "当前readBatch线程%s,读取用户信息完成,用户%s,时间戳%tc",
           Thread.currentThread(), ArrayUtils.toString(users2.toArray()), new Date()));
 }
Пример #3
0
 /**
  * Provide a String representation of the provided list of array of String
  *
  * @return
  */
 public static String toString(List<String[]> values) {
   StringBuffer sb = new StringBuffer();
   if (values != null) {
     sb.append('[');
     for (String[] array : values) {
       sb.append(ArrayUtils.toString(array));
       sb.append(',');
     }
     sb.deleteCharAt(sb.length() - 1);
     sb.append(']');
   } else {
     return null;
   }
   return sb.toString();
 }
Пример #4
0
  public void cancelar(String uuid) throws Exception {
    String[] uuidList = new String[] {uuid};
    System.out.println("Mandando canclera CFDIS: " + ArrayUtils.toString(uuidList));

    String dirPath = "Z:\\CFDI\\cancelaciones";
    File dir = new File(dirPath);
    Assert.isTrue(dir.exists(), "No existe el directorio para cancelaciones: " + dirPath);
    Assert.isTrue(
        dir.isDirectory(), "La ruta para las cancelaciones no es un directorio " + dirPath);

    CancelaResponse res =
        client.cancelCfdi(
            "PAP830101CR3",
            "yqjvqfofb",
            empresa.getRfc(),
            uuidList,
            empresa.getCertificadoDigitalPfx(),
            pfxPassword);
    String msg = res.getText();
    String aka = res.getAck();
    // String[] uuids=res.getUuids();
    CFDI cfdi = ServiceLocator2.getCFDIManager().buscarPorUUID(uuid);
    Assert.notNull(cfdi, "No eixste el CFDI con UUID:" + uuid);

    try {
      // byte[] d1=Base64.decode(msg.getBytes());
      String xmlFile = StringUtils.remove(cfdi.getXmlFilePath(), "xml");
      byte[] d1 = msg.getBytes();
      File msgFile = new File(dir, xmlFile + "_MSG.xml");
      FileOutputStream out1 = new FileOutputStream(msgFile);
      out1.write(d1);
      out1.close();

      // byte[] d2=Base64.decode(aka.getBytes());
      byte[] d2 = aka.getBytes();
      File akaFile = new File(dir, xmlFile + "_AKA.xml");
      FileOutputStream out2 = new FileOutputStream(akaFile);
      out2.write(d2);
      out2.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(
          "Error salvando archivos de cancelacion: " + ExceptionUtils.getRootCauseMessage(e));
    }
    cfdi.setCancelacion(new Date());
    ServiceLocator2.getHibernateTemplate().merge(cfdi);
  }
Пример #5
0
 /**
  * @param packages List of packages identified by their ID, name or local filename.
  * @since 5.7
  */
 public boolean pkgShow(List<String> packages) {
   boolean cmdOk = true;
   if (packages == null || packages.isEmpty()) {
     return cmdOk;
   }
   StringBuilder sb = new StringBuilder();
   sb.append("****************************************");
   for (String pkg : packages) {
     CommandInfo cmdInfo = cset.newCommandInfo(CommandInfo.CMD_SHOW);
     cmdInfo.param = pkg;
     try {
       PackageInfo packageInfo = newPackageInfo(cmdInfo, findPackage(pkg));
       sb.append("\nPackage: " + packageInfo.id);
       sb.append("\nState: " + packageInfo.state);
       sb.append("\nVersion: " + packageInfo.version);
       sb.append("\nName: " + packageInfo.name);
       sb.append("\nType: " + packageInfo.type);
       sb.append("\nVisibility: " + packageInfo.visibility);
       if (packageInfo.state == PackageState.REMOTE
           && packageInfo.type != PackageType.STUDIO
           && packageInfo.visibility != PackageVisibility.PUBLIC
           && !LogicalInstanceIdentifier.isRegistered()) {
         sb.append(" (registration required)");
       }
       sb.append("\nTarget platforms: " + ArrayUtils.toString(packageInfo.targetPlatforms));
       appendIfNotEmpty(sb, "\nVendor: ", packageInfo.vendor);
       sb.append("\nSupports hot-reload: " + packageInfo.supportsHotReload);
       sb.append("\nSupported: " + packageInfo.supported);
       sb.append("\nProduction state: " + packageInfo.productionState);
       sb.append("\nValidation state: " + packageInfo.validationState);
       appendIfNotEmpty(sb, "\nProvides: ", packageInfo.provides);
       appendIfNotEmpty(sb, "\nDepends: ", packageInfo.dependencies);
       appendIfNotEmpty(sb, "\nConflicts: ", packageInfo.conflicts);
       appendIfNotEmpty(sb, "\nTitle: ", packageInfo.title);
       appendIfNotEmpty(sb, "\nDescription: ", packageInfo.description);
       appendIfNotEmpty(sb, "\nHomepage: ", packageInfo.homePage);
       appendIfNotEmpty(sb, "\nLicense: ", packageInfo.licenseType);
       appendIfNotEmpty(sb, "\nLicense URL: ", packageInfo.licenseUrl);
       sb.append("\n****************************************");
     } catch (PackageException e) {
       cmdOk = false;
       cmdInfo.exitCode = 1;
       cmdInfo.newMessage(e);
     }
   }
   log.info(sb.toString());
   return cmdOk;
 }
Пример #6
0
 // ini MCG20140804
 public List<PerfilRol> getRolesByPerfilesIDM(String codigoUsuario) {
   List<PerfilRol> listRoles = new ArrayList<PerfilRol>();
   List<Perfil> listPerfiles = new ArrayList<Perfil>();
   try {
     if (SI.equalsIgnoreCase(Utilities.VALIDAR_PERFILADO)) {
       WsLdapClient ldapServicio = new WsLdapClientImpl(Utilities.WSLDAP_ENDPOINT);
       listPerfiles =
           ldapServicio.obtenerPerfilesPorUsuarioyAplicacion(
               codigoUsuario, Utilities.COD_APLICACION_LDAP);
     } else {
       Perfil perfil = new Perfil();
       perfil.setNombre(Utilities.COD_PERFIL_DEFECTO);
       perfil.setDescripcion(Utilities.DES_PERFIL_DEFECTO);
       listPerfiles.add(perfil);
     }
     if (logger.isDebugEnabled())
       logger.debug("Listado Perfiles LDAP: " + ArrayUtils.toString(listPerfiles));
   } catch (Exception e) {
     logger.error(GenericObject.formatException(e));
   }
   String cadenaCodPerfiles = "";
   boolean primero = true;
   if (listPerfiles != null && listPerfiles.size() > 0) {
     for (Perfil perfil : listPerfiles) {
       if (logger.isDebugEnabled())
         logger.debug(
             "Perfil LDAP: "
                 + ToStringBuilder.reflectionToString(perfil, ToStringStyle.MULTI_LINE_STYLE));
       String codigoperfil = perfil.getNombre();
       if (primero) {
         cadenaCodPerfiles = "'" + codigoperfil + "'";
         primero = false;
       } else {
         cadenaCodPerfiles = cadenaCodPerfiles + "," + "'" + codigoperfil + "'";
       }
     }
     listRoles = loginDao.getListRolesByPerfiles(cadenaCodPerfiles);
   }
   if (logger.isDebugEnabled()) {
     for (PerfilRol perfilRol : listRoles) {
       logger.debug(
           "Listado Roles: "
               + ToStringBuilder.reflectionToString(perfilRol, ToStringStyle.MULTI_LINE_STYLE));
     }
   }
   return listRoles;
 }
Пример #7
0
  /**
   * Creates a new {@code NameLoader}.
   *
   * @param dir the source directory
   * @param shortNames the document archetype(s) that may be loaded to. May be {@code null}, or
   *     contain wildcards
   * @param service the archetype service
   * @param factory the document factory
   */
  public NameLoader(
      File dir, String[] shortNames, IArchetypeService service, DocumentFactory factory) {
    super(service, factory);
    this.dir = dir;
    String[] expanded = getDocumentActShortNames(shortNames);
    if (expanded.length == 0) {
      throw new IllegalArgumentException(
          "Argument 'shortNames' doesn't refer to any valid archetype for loading "
              + "documents to: "
              + ArrayUtils.toString(shortNames));
    }
    if (log.isInfoEnabled()) {
      log.info("Loading documents for archetypes=" + StringUtils.join(expanded, ", "));
    }

    List<IMObjectReference> refs = getDocumentActs(expanded);
    log.info("Found " + refs.size() + " documents");
    iterator = refs.iterator();
  }
Пример #8
0
 /**
  * Motivo: Sobreescritura del método toString(), útil para visualizar el contenido de un Bean
  * (Objeto). <br>
  * Realizado por: <a href="mailto:[email protected]">Richard De los Reyes</a> <br>
  * Fecha: 29/08/2007
  *
  * @return String con el contenido de los atributos y valores formateados para un determinado
  *     objeto.
  */
 public String toString() {
   StringBuffer result = new StringBuffer();
   result.append(this.getClass().getName());
   result.append(" Object {");
   result.append(newLine);
   Field[] fields = this.getClass().getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
     Field field = fields[i];
     try {
       // if((field.getName().substring(0, 2).equals("sw") || field.getName().substring(0,
       // 2).equals("np"))) {
       result.append("    ");
       result.append(field.getName());
       result.append(": ");
       // }
       // Requiere acceso a los atributos privados de las Clases Hijas.
       boolean flag = field.isAccessible();
       if (!flag) {
         field.setAccessible(!flag);
       }
       if (field.getType().isArray()) {
         result.append(ArrayUtils.toString(field.get(this)));
       } else {
         // if((field.getName().substring(0, 2).equals("sw") || field.getName().substring(0,
         // 2).equals("np"))) {
         result.append(field.get(this));
         result.append(newLine);
         // }
       }
       field.setAccessible(flag);
     } catch (IllegalAccessException iae) {
       logger.error(formatException(iae));
     }
   }
   result.append("}");
   return result.toString();
 }
Пример #9
0
  @SuppressWarnings("unchecked")
  private void evaluateOnChangeListener() {
    if (pluginBean.isReadableProperty(ON_SHUTDOWN)) {
      onShutdownListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_SHUTDOWN);
    }
    if (pluginBean.isReadableProperty(ON_CONFIG_CHANGE)) {
      onConfigChangeListener =
          (Closure)
              GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CONFIG_CHANGE);
    }
    if (pluginBean.isReadableProperty(ON_CHANGE)) {
      onChangeListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CHANGE);
    }

    final boolean warDeployed = Metadata.getCurrent().isWarDeployed();
    final boolean reloadEnabled = Environment.getCurrent().isReloadEnabled();

    if (!((reloadEnabled || !warDeployed) && onChangeListener != null)) {
      return;
    }

    Object referencedResources =
        GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, WATCHED_RESOURCES);

    try {
      List resourceList = null;
      if (referencedResources instanceof String) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Configuring plugin "
                  + this
                  + " to watch resources with pattern: "
                  + referencedResources);
        }
        resourceList = new ArrayList();
        resourceList.add(referencedResources.toString());
      } else if (referencedResources instanceof List) {
        resourceList = (List) referencedResources;
      }

      if (resourceList != null) {
        List<String> resourceListTmp = new ArrayList<String>();
        PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();

        if (pluginBuildSettings != null) {

          final Resource[] pluginDirs = pluginBuildSettings.getPluginDirectories();
          final Environment env = Environment.getCurrent();
          final String baseLocation = env.getReloadLocation();

          for (Object ref : resourceList) {
            String stringRef = ref.toString();
            if (!warDeployed) {
              for (Resource pluginDir : pluginDirs) {
                if (pluginDir != null) {
                  String pluginResources =
                      getResourcePatternForBaseLocation(
                          pluginDir.getFile().getCanonicalPath(), stringRef);
                  resourceListTmp.add(pluginResources);
                }
              }
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            } else {
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            }
          }

          watchedResourcePatternReferences = new String[resourceListTmp.size()];
          for (int i = 0; i < watchedResourcePatternReferences.length; i++) {
            String resRef = resourceListTmp.get(i);
            watchedResourcePatternReferences[i] = resRef;
          }

          watchedResourcePatterns =
              new WatchPatternParser()
                  .getWatchPatterns(Arrays.asList(watchedResourcePatternReferences));
        }
      }
    } catch (IllegalArgumentException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    } catch (IOException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    }
  }
Пример #10
0
 private static void obtenerPerfilHOST() {
   CtConOhcQF3BRs rs = InvokeWS.consumirQF3B("P016653", "P016653");
   System.out.println(
       ArrayUtils.toString(Utilities.splitByPosition(rs.getData().getAplfacu(), 2)));
 }
Пример #11
0
  @Override
  protected void doInit() {
    initAddresses();

    if (LOGGER.isInfoEnabled()) {
      LOGGER.info("开始对DNS列表进行速度测试...");
      LOGGER.info("{}", ArrayUtils.toString(addresses));
    }

    Executors.newSingleThreadExecutor()
        .submit(
            new Runnable() {

              @Override
              public void run() {
                if (ArrayUtils.isNotEmpty(addresses)) {
                  while (true) {
                    testSpeed();
                    if (CollectionUtils.isNotEmpty(MAPPINGS)) {
                      if (LOGGER.isInfoEnabled()) {
                        StringBuilder result = new StringBuilder(128);
                        result
                            .append("当前可用的DNS服务数:")
                            .append(MAPPINGS.size())
                            .append(" 个,响应速度:最快 ")
                            .append(MAPPINGS.get(0).getConsumeTimeInMillis())
                            .append(" ms、最慢 ")
                            .append(MAPPINGS.get(MAPPINGS.size() - 1).getConsumeTimeInMillis())
                            .append(" ms");
                        LOGGER.info(result.toString());
                      }
                    }
                    try {
                      Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                    }
                  }
                }
              }

              private void testSpeed() {
                MAPPINGS.clear();
                for (String ip : addresses) {
                  if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("正在测试 {} 的速度...", ip);
                  }
                  Ticket4jDns dns = new Ticket4jDns();
                  HttpClient httpClient = ticket4jHttpClient.buildHttpClient(ip);
                  HttpGet httpGet = ticket4jHttpClient.buildGetMethod(uri);
                  long start = System.currentTimeMillis();
                  try {
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    long time = System.currentTimeMillis() - start;
                    int statusCode = httpResponse.getStatusLine().getStatusCode();
                    if (statusCode == 200 || statusCode == 302) {
                      // Success
                      dns.setIp(ip);
                      dns.setInetAddresses(InetAddressUtils.getByAddress(ip));
                      dns.setConsumeTimeInMillis(time);
                      dns.setTimeout(false);
                      if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("{} 响应成功,消耗时间 {} ms...", ip, time);
                      }
                      if (time <= limitConsumeTimeInMillis) {
                        if (!MAPPINGS.contains(dns)) {
                          MAPPINGS.add(dns);
                          Collections.sort(MAPPINGS, new Ticket4jDns());
                        }
                      }
                    } else {
                      if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("{} 响应失败,错误代码 {}...", ip, statusCode);
                      }
                    }
                  } catch (ClientProtocolException e) {
                    // Ignore
                  } catch (IOException e) {
                    // Ignore
                  }
                }
              }
            });
  }
Пример #12
0
 private void appendIfNotEmpty(StringBuilder sb, String label, Object[] array) {
   if (ArrayUtils.isNotEmpty(array)) {
     sb.append(label + ArrayUtils.toString(array));
   }
 }