private void process(FixtureConfig fixtureConfig) {
   log.debug("Processing " + fixtureConfig);
   String sourceClassStr = fixtureConfig.getSourceClass();
   String sourceProcessorClassStr = fixtureConfig.getSourceProcessorClass();
   try {
     Class<?> sourceClassInst = Class.forName(sourceClassStr);
     IStatsSource source = (IStatsSource) sourceClassInst.newInstance();
     Class<?> sourceProcClassInst = Class.forName(sourceProcessorClassStr);
     IStatsProcessor sourceProcessor = (IStatsProcessor) sourceProcClassInst.newInstance();
     sourceProcessor.process(source);
     List<FixtureDTO> fixtures = sourceProcessor.getFixtures();
     Collections.sort(fixtures, new FootballAPIComparator());
     for (FixtureDTO fixtureDTO : fixtures) {
       Fixture match = fixtureRepo.findByMatchId(fixtureDTO.getMatchId());
       if (match != null) {
         log.debug("Found same match. Updating the match id : [ " + match.getId() + " ]");
         fixtureDTO.setId(match.getId());
       } else {
         log.debug("Found new fixture. Creating a new match [ " + fixtureDTO + " ]");
       }
       fixtureRepo.save(fixtureMapper.fixtureDTOToFixture(fixtureDTO));
     }
   } catch (Exception e) {
     log.error("Error.. ", e);
   }
 }
Пример #2
0
  /** Creates a service and its associated manager based on fully qualified class names. */
  private Service setupService(String serviceName, String managerName, HashSet<Object> managerSet)
      throws Exception {
    // get the service class and instance
    Class<?> serviceClass = Class.forName(serviceName);
    Service service = createService(serviceClass);

    // resolve the class and the constructor, checking for constructors
    // by type since they likely take a super-type of Service
    Class<?> managerClass = Class.forName(managerName);
    Constructor<?>[] constructors = managerClass.getConstructors();
    Constructor<?> managerConstructor = null;
    for (int i = 0; i < constructors.length; i++) {
      Class<?>[] types = constructors[i].getParameterTypes();
      if (types.length == 1) {
        if (types[0].isAssignableFrom(serviceClass)) {
          managerConstructor = constructors[i];
          break;
        }
      }
    }

    // if we didn't find a matching manager constructor, it's an error
    if (managerConstructor == null)
      throw new NoSuchMethodException(
          "Could not find a constructor " + "that accepted the Service");

    // create the manager and put it in the collection
    managerSet.add(managerConstructor.newInstance(service));

    return service;
  }
Пример #3
0
 private static Class<?> getClassObject(Object o) throws ClassNotFoundException {
   if (o == null) {
     System.out.println("null");
   }
   // 基本データ型の場合
   if (o instanceof Boolean) {
     return boolean.class;
   } else if (o instanceof Integer) {
     return int.class;
   } else if (o instanceof Double) {
     return double.class;
   } else if (o instanceof Long) {
     return long.class;
   } else if (o instanceof Short) {
     return short.class;
   } else if (o instanceof Character) {
     return char.class;
   } else if (o instanceof Byte) {
     return byte.class;
   } else if (o instanceof Float) {
     return float.class;
   }
   // 基本データ型以外の場合:forName()でクラスオブジェクトを取得
   else {
     System.out.println(Class.forName(strip(o.getClass().toString(), "class ")));
     return Class.forName(strip(o.getClass().toString(), "class "));
   }
 }
Пример #4
0
  public String objectToXml(Object object) {
    String rtnStr = "";
    try {

      JAXBContext jaxbContext = cachedJaxb.get(pkgName);
      if (jaxbContext == null) {
        jaxbContext = JAXBContext.newInstance(pkgName);
        cachedJaxb.put(pkgName, jaxbContext);
      }

      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_ENCODING, BcConstants.ENCODING);
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

      Class docClazz = Class.forName(pkgName + ".Document");
      Class ofClazz = Class.forName(pkgName + ".ObjectFactory");
      Object factory = ofClazz.newInstance();
      Method method = ofClazz.getDeclaredMethod("createDocument", docClazz);
      JAXBElement jaxbElement = (JAXBElement) method.invoke(factory, docClazz.cast(object));

      StringWriter sw = new StringWriter();
      marshaller.marshal(jaxbElement, sw);
      rtnStr = sw.toString();

      // TODO remove the header in a better way: <?xml version="1.0" encoding="UTF-8"
      // standalone="yes"?>
      rtnStr = StringUtils.substringAfter(rtnStr, "?>").trim();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    return rtnStr;
  }
Пример #5
0
  public void connect() {

    try {

      Class.forName("org.postgresql.Driver"); // ドライバクラスをロード
      // JDBCドライバの登録
      String driver = "org.postgresql.Driver";
      // データベースの指定
      String server = "localhost"; // PostgreSQL サーバ ( IP または ホスト名 )
      String defaultdbname = "postgres"; // デフォルトで存在するデータベース名
      String defaulturl = "jdbc:postgresql://" + server + "/" + defaultdbname;

      // String databaseName = "testdb"; // 今後データの書き込みに使用するデータベース名
      // String databaseurl = "jdbc:postgresql://" + server + "/" +
      // databaseName;

      String user = "******"; // データベース作成ユーザ名
      String password = ""; // データベース作成ユーザパスワード
      Class.forName(driver);

      // データベースとの接続
      con = DriverManager.getConnection(defaulturl, user, password);
      // データベースへ接続
      stmt = con.createStatement();
    } catch (Exception e) {

      e.printStackTrace();
    }
  }
  /** Creates an instance of the factory. */
  public static ServiceFactory newInstance() throws ServiceException {
    String className = getFactoryClassName();

    Class cl = null;

    try {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader != null) cl = Class.forName(className, false, loader);
    } catch (NoSuchMethodError e) {
    } catch (ClassNotFoundException e) {
      throw new ServiceException(e);
    }

    if (cl == null) {
      try {
        cl = Class.forName(className);
      } catch (ClassNotFoundException e) {
        throw new ServiceException(e);
      }
    }

    try {
      return (ServiceFactory) cl.newInstance();
    } catch (IllegalAccessException e) {
      throw new ServiceException(e);
    } catch (InstantiationException e) {
      throw new ServiceException(e);
    }
  }
Пример #7
0
  static {
    classNamesToConnectionTesters.put(
        C3P0Defaults.connectionTesterClassName(), C3P0Defaults.connectionTester());

    String userManagementCoordinator = C3P0ConfigUtils.getPropsFileConfigProperty(MC_PARAM);
    if (userManagementCoordinator != null) {
      try {
        mc = (ManagementCoordinator) Class.forName(userManagementCoordinator).newInstance();
      } catch (Exception e) {
        if (logger.isLoggable(MLevel.WARNING))
          logger.log(
              MLevel.WARNING,
              "Could not instantiate user-specified ManagementCoordinator "
                  + userManagementCoordinator
                  + ". Using NullManagementCoordinator (c3p0 JMX management disabled!)",
              e);
        mc = new NullManagementCoordinator();
      }
    } else {
      try {
        Class.forName("java.lang.management.ManagementFactory");

        mc =
            (ManagementCoordinator)
                Class.forName("com.mchange.v2.c3p0.management.ActiveManagementCoordinator")
                    .newInstance();
      } catch (Exception e) {
        if (logger.isLoggable(MLevel.INFO))
          logger.log(
              MLevel.INFO, "jdk1.5 management interfaces unavailable... JMX support disabled.", e);
        mc = new NullManagementCoordinator();
      }
    }
  }
  public Result check(Descriptor descriptor) {
    this.descriptor = descriptor;
    result = getInitializedResult();
    compName = getVerifierContext().getComponentNameConstructor();
    ClassLoader cl = getVerifierContext().getClassLoader();
    List<InjectionCapable> injectables = getInjectables(getClassName());
    for (InjectionCapable injectionCapable : injectables) {
      Set<InjectionTarget> iTargets = injectionCapable.getInjectionTargets();
      for (InjectionTarget target : iTargets) {
        try {
          if (target.isFieldInjectable()) {
            Class classObj = Class.forName(getClassName(), false, cl);
            Field field = classObj.getDeclaredField(target.getFieldName());
            testMethodModifiers(field.getModifiers(), "field", field);
          }
          if (target.isMethodInjectable()) {
            Class classObj = Class.forName(getClassName(), false, cl);
            Method method = getInjectedMethod(classObj, target.getMethodName());
            if (method == null) continue;
            testMethodModifiers(method.getModifiers(), "method", method);
          }
        } catch (Exception e) {
        } // ignore as it will be caught in other tests
      }
    }

    if (result.getStatus() != Result.FAILED) {
      addGoodDetails(result, compName);
      result.passed(
          smh.getLocalString(getClass().getName() + ".passed", "Valid injection method(s)."));
    }
    return result;
  }
Пример #9
0
  private Object readValueFromDisk(InputStream is) throws IOException {
    BufferedReader fss = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    String className = fss.readLine();

    if (className == null) {
      return null;
    }

    String line = null;
    String content = "";
    while ((line = fss.readLine()) != null) {
      content += line;
    }

    fss.close();

    Class<?> clazz;
    try {
      if (className.contains("google")) {
        clazz = Class.forName(className);
        return mJsonFactory.createJsonParser(content).parseAndClose(clazz, null);
      } else {
        clazz = Class.forName(className);
        return mGson.fromJson(content, clazz);
      }
    } catch (IllegalArgumentException e) {
      Timber.e("Deserializing from disk failed", e);
      return null;
    } catch (ClassNotFoundException e) {
      throw new IOException(e.getMessage());
    }
  }
 private <T extends Object> Result doCircuitBreak(Invoker<?> invoker, Invocation invocation)
     throws RpcException {
   String interfaceName = invoker.getUrl().getParameter(Constants.INTERFACE_KEY);
   String circuitBreaker = interfaceName + "CircuitBreak";
   incrementBreakCount(invoker, invocation);
   try {
     logger.info("[{}] check has class [{}] to handle circuit break", localHost, circuitBreaker);
     Invoker<?> breakerInvoker = null;
     if (CIRCUIT_BREAKER_INVOKER_CACHE.containsKey(circuitBreaker)) {
       breakerInvoker = CIRCUIT_BREAKER_INVOKER_CACHE.get(circuitBreaker);
     } else {
       Class<T> breakerType = (Class<T>) Class.forName(circuitBreaker);
       Class<T> interfaceType = (Class<T>) Class.forName(interfaceName);
       if (interfaceType.isAssignableFrom(breakerType)) {
         logger.info("[{}] handle circuit break by class [{}]", localHost, circuitBreaker);
         T breaker = breakerType.newInstance();
         breakerInvoker = proxyFactory.getInvoker(breaker, interfaceType, invoker.getUrl());
         Invoker<?> oldInvoker =
             CIRCUIT_BREAKER_INVOKER_CACHE.putIfAbsent(circuitBreaker, breakerInvoker);
         if (oldInvoker != null) {
           breakerInvoker = oldInvoker;
         }
       }
     }
     if (breakerInvoker != null) {
       return breakerInvoker.invoke(invocation);
     }
   } catch (Exception e) {
     logger.error("failed to invoke circuit breaker", e);
   }
   logger.info("[{}] handle circuit break by exception", localHost);
   CircuitBreakerException baseBusinessException =
       new CircuitBreakerException(interfaceName, invocation.getMethodName());
   throw baseBusinessException;
 }
Пример #11
0
  protected void registerFromProperties(Properties properties) {
    if (properties != null) {
      class2ElementRegistry.clear();
      //            for ( String keyOrClassName: properties.keySet() ) {
      for (Iterator iter = properties.keySet().iterator(); iter.hasNext(); ) {
        String keyOrClassName = (String) iter.next();
        String element = (String) properties.get(keyOrClassName);

        Object key = keyOrClassName;
        try {
          key = Class.forName(keyOrClassName);
        } catch (ClassNotFoundException e) {
        }
        if (handlerClass == null) {
          try {
            register(key, Class.forName(element));
          } catch (ClassNotFoundException e) {
            e.printStackTrace();
          }
        } else {
          register(key, element);
        }
      }
    }
  }
Пример #12
0
  public boolean endCall() {
    if (_prevRingerMode == null) {
      _prevRingerMode = _audioManager.getRingerMode();
    }

    _audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

    try {
      String serviceManagerName = "android.os.ServiceManager";
      String serviceManagerNativeName = "android.os.ServiceManagerNative";
      String telephonyName = "com.android.internal.telephony.ITelephony";

      Class<?> telephonyClass = Class.forName(telephonyName);
      Class<?> telephonyStubClass = telephonyClass.getClasses()[0];
      Class<?> serviceManagerClass = Class.forName(serviceManagerName);
      Class<?> serviceManagerNativeClass = Class.forName(serviceManagerNativeName);

      Binder tmpBinder = new Binder();
      tmpBinder.attachInterface(null, "fake");
      Method tempInterfaceMethod =
          serviceManagerNativeClass.getMethod("asInterface", IBinder.class);
      Object serviceManagerObject = tempInterfaceMethod.invoke(null, tmpBinder);
      Method getService = serviceManagerClass.getMethod("getService", String.class);
      IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone");

      Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class);
      Object telephonyObject = serviceMethod.invoke(null, retbinder);
      Method telephonyEndCall = telephonyClass.getMethod("endCall");
      telephonyEndCall.invoke(telephonyObject);
      return true;
    } catch (Exception e) {
      Log.e(TAG, "Could not connect to telephony subsystem", e);
      return false;
    }
  }
Пример #13
0
 /**
  * Opens the specified web page in the user's default browser
  *
  * @param url A web address (URL) of a web page (ex: "http://www.google.com/")
  */
 public static void openURL(String url) {
   try { // attempt to use Desktop library from JDK 1.6+ (even if on 1.5)
     Class<?> d = Class.forName("java.awt.Desktop");
     d.getDeclaredMethod("browse", new Class[] {java.net.URI.class})
         .invoke(
             d.getDeclaredMethod("getDesktop").invoke(null),
             new Object[] {java.net.URI.create(url)});
     // above code mimics:
     //   java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
   } catch (Exception ignore) { // library not available or failed
     String osName = System.getProperty("os.name");
     try {
       if (osName.startsWith("Mac OS")) {
         Class.forName("com.apple.eio.FileManager")
             .getDeclaredMethod("openURL", new Class[] {String.class})
             .invoke(null, new Object[] {url});
       } else if (osName.startsWith("Windows"))
         Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
       else { // assume Unix or Linux
         boolean found = false;
         for (String browser : browsers)
           if (!found) {
             found = Runtime.getRuntime().exec(new String[] {"which", browser}).waitFor() == 0;
             if (found) Runtime.getRuntime().exec(new String[] {browser, url});
           }
         if (!found) throw new Exception(Arrays.toString(browsers));
       }
     } catch (Exception e) {
       JOptionPane.showMessageDialog(null, errMsg + "\n" + e.toString());
     }
   }
 }
 @Override
 public FieldProviderResponse overrideViaXml(
     OverrideViaXmlRequest overrideViaXmlRequest, Map<String, FieldMetadata> metadata) {
   Map<String, FieldMetadataOverride> overrides =
       getTargetedOverride(
           overrideViaXmlRequest.getRequestedConfigKey(),
           overrideViaXmlRequest.getRequestedCeilingEntity());
   if (overrides != null) {
     for (String propertyName : overrides.keySet()) {
       final FieldMetadataOverride localMetadata = overrides.get(propertyName);
       for (String key : metadata.keySet()) {
         if (key.equals(propertyName)) {
           try {
             if (metadata.get(key) instanceof AdornedTargetCollectionMetadata) {
               AdornedTargetCollectionMetadata serverMetadata =
                   (AdornedTargetCollectionMetadata) metadata.get(key);
               if (serverMetadata.getTargetClass() != null) {
                 Class<?> targetClass = Class.forName(serverMetadata.getTargetClass());
                 Class<?> parentClass = null;
                 if (serverMetadata.getOwningClass() != null) {
                   parentClass = Class.forName(serverMetadata.getOwningClass());
                 }
                 String fieldName = serverMetadata.getFieldName();
                 Field field =
                     overrideViaXmlRequest
                         .getDynamicEntityDao()
                         .getFieldManager()
                         .getField(targetClass, fieldName);
                 Map<String, FieldMetadata> temp = new HashMap<String, FieldMetadata>(1);
                 temp.put(field.getName(), serverMetadata);
                 FieldInfo info = buildFieldInfo(field);
                 buildAdornedTargetCollectionMetadata(
                     parentClass,
                     targetClass,
                     temp,
                     info,
                     localMetadata,
                     overrideViaXmlRequest.getDynamicEntityDao());
                 serverMetadata = (AdornedTargetCollectionMetadata) temp.get(field.getName());
                 metadata.put(key, serverMetadata);
                 if (overrideViaXmlRequest.getParentExcluded()) {
                   if (LOG.isDebugEnabled()) {
                     LOG.debug(
                         "applyAdornedTargetCollectionMetadataOverrides:Excluding "
                             + key
                             + "because parent is marked as excluded.");
                   }
                   serverMetadata.setExcluded(true);
                 }
               }
             }
           } catch (Exception e) {
             throw new RuntimeException(e);
           }
         }
       }
     }
   }
   return FieldProviderResponse.HANDLED;
 }
Пример #15
0
 public static <K, V> Map<K, V> getMapFromString(
     String s, Class<K> keyClass, Class<V> valueClass, MapFactory<K, V> mapFactory)
     throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
         InvocationTargetException, InstantiationException {
   Constructor<K> keyC = keyClass.getConstructor(new Class[] {Class.forName("java.lang.String")});
   Constructor<V> valueC =
       valueClass.getConstructor(new Class[] {Class.forName("java.lang.String")});
   if (s.charAt(0) != '{') throw new RuntimeException("");
   s = s.substring(1); // get rid of first brace
   String[] fields = s.split("\\s+");
   Map<K, V> m = mapFactory.newMap();
   // populate m
   for (int i = 0; i < fields.length; i++) {
     // System.err.println("Parsing " + fields[i]);
     fields[i] = fields[i].substring(0, fields[i].length() - 1); // get rid of
     // following
     // comma or
     // brace
     String[] a = fields[i].split("=");
     K key = keyC.newInstance(a[0]);
     V value;
     if (a.length > 1) {
       value = valueC.newInstance(a[1]);
     } else {
       value = valueC.newInstance("");
     }
     m.put(key, value);
   }
   return m;
 }
Пример #16
0
  static Object lookupUsingOSGiServiceLoader(String factoryId, Logger logger) {

    try {
      // Use reflection to avoid having any dependendcy on ServiceLoader class
      Class serviceClass = Class.forName(factoryId);
      Class target = Class.forName(OSGI_SERVICE_LOADER_CLASS_NAME);
      Method m = target.getMethod(OSGI_SERVICE_LOADER_METHOD_NAME, Class.class);
      Iterator iter = ((Iterable) m.invoke(null, serviceClass)).iterator();
      if (iter.hasNext()) {
        Object next = iter.next();
        logger.fine(
            "Found implementation using OSGi facility; returning object ["
                + next.getClass().getName()
                + "].");
        return next;
      } else {
        return null;
      }
    } catch (IllegalAccessException
        | InvocationTargetException
        | ClassNotFoundException
        | NoSuchMethodException ignored) {

      logger.log(Level.FINE, "Unable to find from OSGi: [" + factoryId + "]", ignored);
      return null;
    }
  }
Пример #17
0
    /**
     * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the fix is not needed.
     *
     * @throws SecurityException if the fix is needed but could not be applied.
     */
    private static void applyOpenSSLFix() throws SecurityException {
      if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN)
          || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) {
        // No need to apply the fix
        return;
      }

      try {
        // Mix in the device- and invocation-specific seed.
        Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
            .getMethod("RAND_seed", byte[].class)
            .invoke(null, generateSeed());

        // Mix output of Linux PRNG into OpenSSL's PRNG
        int bytesRead =
            (Integer)
                Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
                    .getMethod("RAND_load_file", String.class, long.class)
                    .invoke(null, "/dev/urandom", 1024);
        if (bytesRead != 1024) {
          throw new IOException("Unexpected number of bytes read from Linux PRNG: " + bytesRead);
        }
      } catch (Exception e) {
        throw new SecurityException("Failed to seed OpenSSL PRNG", e);
      }
    }
Пример #18
0
 /**
  * Deserialize an object from a given byte buffer.
  *
  * @param b The bytebuf to deserialize.
  * @return The deserialized object.
  */
 @Override
 public Object deserialize(ByteBuf b, CorfuRuntime rt) {
   int classNameLength = b.readShort();
   byte[] classNameBytes = new byte[classNameLength];
   b.readBytes(classNameBytes, 0, classNameLength);
   String className = new String(classNameBytes);
   if (className.equals("null")) {
     return null;
   } else if (className.equals("CorfuObject")) {
     int SMRClassNameLength = b.readShort();
     byte[] SMRClassNameBytes = new byte[SMRClassNameLength];
     b.readBytes(SMRClassNameBytes, 0, SMRClassNameLength);
     String SMRClassName = new String(SMRClassNameBytes);
     try {
       return rt.getObjectsView()
           .build()
           .setStreamID(new UUID(b.readLong(), b.readLong()))
           .setType(Class.forName(SMRClassName))
           .open();
     } catch (ClassNotFoundException cnfe) {
       log.error("Exception during deserialization!", cnfe);
       throw new RuntimeException(cnfe);
     }
   } else {
     try (ByteBufInputStream bbis = new ByteBufInputStream(b)) {
       try (InputStreamReader r = new InputStreamReader(bbis)) {
         return gson.fromJson(r, Class.forName(className));
       }
     } catch (IOException | ClassNotFoundException ie) {
       log.error("Exception during deserialization!", ie);
       throw new RuntimeException(ie);
     }
   }
 }
Пример #19
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
Пример #20
0
  /**
   * @author ZhangXiang
   * @param args 2011-4-7
   * @throws NoSuchMethodException
   * @throws InvocationTargetException
   * @throws SecurityException
   * @throws IllegalArgumentException
   */
  public static void main(String[] args)
      throws IllegalArgumentException, SecurityException, InvocationTargetException,
          NoSuchMethodException {

    StringBuilder classStr = new StringBuilder("package dyclass;public class Foo{");
    classStr.append("public void test(){");
    classStr.append("System.out.println(\"Foo2\");}}");

    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = jc.getStandardFileManager(null, null, null);
    Location location = StandardLocation.CLASS_OUTPUT;
    File[] outputs = new File[] {new File("D:/CodeProject/ToxinD/test-export/target/classes")};
    try {
      fileManager.setLocation(location, Arrays.asList(outputs));
    } catch (IOException e) {
      e.printStackTrace();
    }

    JavaFileObject jfo = new JavaSourceFromString("dyclass.Foo", classStr.toString());
    JavaFileObject[] jfos = new JavaFileObject[] {jfo};
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(jfos);
    boolean b = jc.getTask(null, fileManager, null, null, null, compilationUnits).call();
    if (b) { // 如果编译成功
      try {
        Object c = Class.forName("dyclass.Foo").newInstance();
        Class.forName("dyclass.Foo").getMethod("test").invoke(c);
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
Пример #21
0
  static {
    Class<Object> clazz;

    logger = LoggerManager.getLogger(Base64.class.getName());

    try {
      clazz = (Class<Object>) Class.forName("android.util.Base64");
      // Looking for encode( byte[] input, int flags)
      aMethod = clazz.getMethod("encode", byte[].class, Integer.TYPE);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of android.util.Base64", x);
    }

    try {
      clazz = (Class<Object>) Class.forName("org.bouncycastle.util.encoders.Base64Encoder");
      bEncoder = clazz.newInstance();
      // Looking for encode( byte[] input, int offset, int length, OutputStream output)
      bMethod =
          clazz.getMethod("encode", byte[].class, Integer.TYPE, Integer.TYPE, OutputStream.class);
      logger.info(clazz.getName() + " is available.");
    } catch (ClassNotFoundException x) {
    } // Ignore
    catch (Exception x) {
      logger.error("Failed to initialize use of org.bouncycastle.util.encoders.Base64Encoder", x);
    }

    if (aMethod == null && bMethod == null)
      throw new IllegalStateException("No base64 encoder implementation is available.");
  }
  public int search(String x) {

    try {

      Class.forName("com.mysql.jdbc.Driver").newInstance();
      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      String connectionUrl = "jdbc:mysql://localhost:3306/ehealthfolder";
      String connectionUser = "******";
      String connectionPassword = "";
      conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
      stmt = conn.createStatement();
      this.x = x;
      rs = stmt.executeQuery("SELECT * FROM patients WHERE AFM = '" + x + "'");
      if (rs.next()) {
        check = 1;
        fields[0] = rs.getString("Lname");
        fields[1] = rs.getString("Fname");
        fields[2] = rs.getString("Birth");
        fields[3] = rs.getString("Town");
        fields[4] = rs.getString("Street");
        fields[5] = rs.getString("Telephone");
        fields[6] = rs.getString("AFM");
      }

    } catch (Exception e) {

      e.printStackTrace();
    }
    return check;
  }
Пример #23
0
  static {
    // check if we have JAI and or ImageIO

    // if these classes are here, then the runtine environment has
    // access to JAI and the JAI ImageI/O toolbox.
    boolean available = true;
    try {
      Class.forName("javax.media.jai.JAI");
    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      available = false;
    }
    JAIAvailable = available;

    available = true;
    try {
      Class<?> clazz = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi");
      readerSpi = (ImageReaderSpi) clazz.newInstance();
      Class<?> clazz1 = Class.forName("com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi");
      writerSpi = (ImageWriterSpi) clazz1.newInstance();

    } catch (Throwable e) {
      if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
      readerSpi = null;
      writerSpi = null;
      available = false;
    }
    TiffAvailable = available;

    final HashSet<String> tempSet = new HashSet<String>(2);
    tempSet.add(".tfw");
    tempSet.add(".tiffw");
    tempSet.add(".wld");
    TIFF_WORLD_FILE_EXT = Collections.unmodifiableSet(tempSet);
  }
Пример #24
0
 // setHandler creates a Proxy object from the passed OSXAdapter and adds it as an
 // ApplicationListener
 public static void setHandler(OSXAdapter adapter) {
   try {
     Class applicationClass = Class.forName("com.apple.eawt.Application");
     if (macOSXApplication == null) {
       macOSXApplication =
           applicationClass.getConstructor((Class[]) null).newInstance((Object[]) null);
     }
     Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
     Method addListenerMethod =
         applicationClass.getDeclaredMethod(
             "addApplicationListener", new Class[] {applicationListenerClass});
     // Create a proxy object around this handler that can be reflectively added as an Apple
     // ApplicationListener
     Object osxAdapterProxy =
         Proxy.newProxyInstance(
             OSXAdapter.class.getClassLoader(), new Class[] {applicationListenerClass}, adapter);
     addListenerMethod.invoke(macOSXApplication, new Object[] {osxAdapterProxy});
   } catch (ClassNotFoundException cnfe) {
     System.err.println(
         "This version of Mac OS X does not support the Apple EAWT.  ApplicationEvent handling has been disabled ("
             + cnfe
             + ")");
   } catch (
       Exception
           ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking
                 // eawt.Application methods
     System.err.println("Mac OS X Adapter could not talk to EAWT:");
     ex.printStackTrace();
   }
 }
Пример #25
0
 /** Instantiates the identified custom selector class. */
 public void selectorCreate() {
   if (classname != null && classname.length() > 0) {
     try {
       Class c = null;
       if (classpath == null) {
         c = Class.forName(classname);
       } else {
         // Memory-Leak in line below
         AntClassLoader al = getProject().createClassLoader(classpath);
         c = Class.forName(classname, true, al);
       }
       dynselector = (FileSelector) c.newInstance();
       final Project p = getProject();
       if (p != null) {
         p.setProjectReference(dynselector);
       }
     } catch (ClassNotFoundException cnfexcept) {
       setError("Selector " + classname + " not initialized, no such class");
     } catch (InstantiationException iexcept) {
       setError("Selector " + classname + " not initialized, could not create class");
     } catch (IllegalAccessException iaexcept) {
       setError("Selector " + classname + " not initialized, class not accessible");
     }
   } else {
     setError("There is no classname specified");
   }
 }
Пример #26
0
  /**
   * Reads a run from a DOM node representing an XML parameter file.
   *
   * @param n the DOM node to read the run from
   */
  public void readFromNode(Element e) {
    String mclass = null, expRunnerClass = null;
    mclass = e.getAttribute("model");
    expRunnerClass = e.getAttribute("expRunner");
    if (mclass == "") mclass = null;
    if (expRunnerClass == "") expRunnerClass = null;

    try {
      if (mclass != null) model = (Model) Class.forName(mclass).newInstance();
      if (expRunnerClass != null) {
        expRunner = (ExperimentRunner) Class.forName(expRunnerClass).newInstance();
      } else if (expRunner == null) {
        expRunner = createDefaultExperimentRunner();
        System.out.println(
            "** WARNING: No ExperimentRunner specified. Using desmoj.util.ExperimentRunner");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      model = null;
      expRunner = null;
    }

    Node settings = null, params = null;
    NodeList nl = e.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
      Node n = nl.item(i);
      if (n.getNodeName().equals("exp")) settings = n;
      if (n.getNodeName().equals("model")) params = n;
    }

    if (settings != null) readParamList(settings, expSettings);

    if (params != null) readParamList(params, modelParams);
  }
Пример #27
0
  /**
   * In the absence of webapp faces-config.xml and META-INF/services, verify that the overrides
   * specified in the implementation faces-config.xml take precedence.
   *
   * @throws java.lang.Exception
   */
  public void testJSFImplCase() throws Exception {
    Object factory = null;
    Class clazz = null;

    FactoryFinder.releaseFactories();
    int len, i = 0;

    // this testcase only simulates the "faces implementation
    // specific" part
    for (i = 0, len = FactoryFinderTestCase2.FACTORIES.length; i < len; i++) {
      FactoryFinder.setFactory(
          FactoryFinderTestCase2.FACTORIES[i][0], FactoryFinderTestCase2.FACTORIES[i][1]);
    }

    for (i = 0, len = FactoryFinderTestCase2.FACTORIES.length; i < len; i++) {
      clazz = Class.forName(FactoryFinderTestCase2.FACTORIES[i][0]);
      factory = FactoryFinder.getFactory(FactoryFinderTestCase2.FACTORIES[i][0]);
      assertTrue(
          "Factory for " + clazz.getName() + " not of expected type.",
          clazz.isAssignableFrom(factory.getClass()));
      clazz = Class.forName(FactoryFinderTestCase2.FACTORIES[i][1]);
      assertTrue(
          "Factory " + FactoryFinderTestCase2.FACTORIES[i][1] + " not of expected type",
          clazz.isAssignableFrom(factory.getClass()));
    }
  }
Пример #28
0
 static {
   Class<?> clazz = null;
   // -Ddmm4j.http.httpClient=dmm4j.HttpClient
   String httpClientImpl = System.getProperty(HTTP_CLIENT_IMPLEMENTATION);
   if (httpClientImpl != null) {
     try {
       clazz = Class.forName(httpClientImpl);
     } catch (ClassNotFoundException ignore) {
     }
   }
   if (null == clazz) {
     try {
       clazz = Class.forName("dmm4j.http.AlternativeHttpClientImpl");
     } catch (ClassNotFoundException ignore) {
     }
   }
   if (null == clazz) {
     try {
       clazz = Class.forName("dmm4j.http.HttpClientImpl");
     } catch (ClassNotFoundException cnfe) {
       throw new AssertionError(cnfe);
     }
   }
   try {
     HTTP_CLIENT_CONSTRUCTOR = clazz.getConstructor(HttpClientConfiguration.class);
   } catch (NoSuchMethodException nsme) {
     throw new AssertionError(nsme);
   }
 }
  protected WebDriver createInstanceOf(String className) {
    try {
      DesiredCapabilities capabilities = createCommonCapabilities();
      capabilities.setJavascriptEnabled(true);
      capabilities.setCapability(TAKES_SCREENSHOT, true);
      capabilities.setCapability(ACCEPT_SSL_CERTS, true);
      capabilities.setCapability(SUPPORTS_ALERTS, true);
      if (isPhantomjs()) {
        capabilities.setCapability(
            "phantomjs.cli.args", // PhantomJSDriverService.PHANTOMJS_CLI_ARGS ==
                                  // "phantomjs.cli.args"
            new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
      }

      Class<?> clazz = Class.forName(className);
      if (WebDriverProvider.class.isAssignableFrom(clazz)) {
        return ((WebDriverProvider) clazz.newInstance()).createDriver(capabilities);
      } else {
        Constructor<?> constructor = Class.forName(className).getConstructor(Capabilities.class);
        return (WebDriver) constructor.newInstance(capabilities);
      }
    } catch (InvocationTargetException e) {
      throw runtime(e.getTargetException());
    } catch (Exception invalidClassName) {
      throw new IllegalArgumentException(invalidClassName);
    }
  }
Пример #30
0
  static {

    // Is Log4J Available?
    try {
      if (null != Class.forName("org.apache.log4j.Logger")) {
        log4jIsAvailable = true;
      } else {
        log4jIsAvailable = false;
      }
    } catch (Throwable t) {
      log4jIsAvailable = false;
    }

    // Is JDK 1.4 Logging Available?
    try {
      if ((null != Class.forName("java.util.logging.Logger"))
          && (null != Class.forName("org.apache.commons.logging.impl.Jdk14Logger"))) {
        jdk14IsAvailable = true;
      } else {
        jdk14IsAvailable = false;
      }
    } catch (Throwable t) {
      jdk14IsAvailable = false;
    }

    // Set the default Log implementation
    String name = null;
    try {
      name = System.getProperty("org.apache.commons.logging.log");
      if (name == null) {
        name = System.getProperty("org.apache.commons.logging.Log");
      }
    } catch (Throwable t) {
    }
    if (name != null) {
      try {
        setLogImplementation(name);
      } catch (Throwable t) {
        try {
          setLogImplementation("org.apache.commons.logging.impl.NoOpLog");
        } catch (Throwable u) {;
        }
      }
    } else {
      try {
        if (log4jIsAvailable) {
          setLogImplementation("org.apache.commons.logging.impl.Log4JLogger");
        } else if (jdk14IsAvailable) {
          setLogImplementation("org.apache.commons.logging.impl.Jdk14Logger");
        } else {
          setLogImplementation("org.apache.commons.logging.impl.NoOpLog");
        }
      } catch (Throwable t) {
        try {
          setLogImplementation("org.apache.commons.logging.impl.NoOpLog");
        } catch (Throwable u) {;
        }
      }
    }
  }