Ejemplo n.º 1
1
  /**
   * set date source
   *
   * @param path
   */
  public void setDataSource(String path)
      throws IOException, IllegalArgumentException, IllegalStateException {

    if (mPlayStatus != VideoConst.PLAY_STATUS_END) {
      MmpTool.LOG_ERROR("Video is playing,can't set setDataSource");
      sendMsg(VideoConst.MSG_IS_PLAYING);
    }

    isEnd = false;

    try {
      mmediaplayer.setDataSource(path);
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw new IllegalArgumentException(e);
    } catch (IllegalStateException e) {
      e.printStackTrace();
      throw new IllegalStateException(e);
    }

    mPlayStatus = VideoConst.PLAY_STATUS_INITED;

    MmpTool.LOG_DBG("setDataSource finish!");
  }
Ejemplo n.º 2
1
 public DERObject getLoadedObject() throws IOException {
   try {
     return new DERExternal(_parser.readVector());
   } catch (IllegalArgumentException e) {
     throw new ASN1Exception(e.getMessage(), e);
   }
 }
Ejemplo n.º 3
0
  @Listener
  public void onGamePreInitializationEvent(GamePreInitializationEvent event) {
    if (game.getPlatform().getType() == Platform.Type.SERVER) {

      try {
        game.getServiceManager()
            .setProvider(this, IRegistrationService.class, new SimpleRegistrationService());
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      }

      game.getScheduler()
          .createTaskBuilder()
          .execute(
              (task) -> {
                try {
                  if (!requestQueue.isEmpty()) requestQueue.take().run();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                }
              })
          .name("FDS-WSAPI - CheckRequestsTask")
          .delayTicks(50)
          .interval(1, TimeUnit.MILLISECONDS)
          .submit(this);
    }
  }
Ejemplo n.º 4
0
 /**
  * Helper function for reflective invocation.
  * 
  * @param cl  class loader
  * @param className  class name
  * @param methodName  method name
  * @param argTypes  arg types (optional)
  * @param args  arguments
  * @return  return value from invoked method
  */
 public static Object invoke(ClassLoader cl, String className,
     String methodName, Class[] argTypes, Object[] args) {
     Class c;
     try {
         c = Class.forName(className, true, cl);
     } catch (ClassNotFoundException e0) {
         System.err.println("Cannot load "+className);
         e0.printStackTrace();
         return null;
     }
     Method m = getDeclaredMethod(c, methodName, argTypes);
     Object result;
     try {
         result = m.invoke(null, args);
     } catch (IllegalArgumentException e2) {
         System.err.println("Illegal argument exception");
         e2.printStackTrace();
         return null;
     } catch (IllegalAccessException e2) {
         System.err.println("Illegal access exception");
         e2.printStackTrace();
         return null;
     } catch (InvocationTargetException e2) {
         if (e2.getTargetException() instanceof RuntimeException)
             throw (RuntimeException) e2.getTargetException();
         if (e2.getTargetException() instanceof Error)
             throw (Error) e2.getTargetException();
         System.err.println("Unexpected exception thrown!");
         e2.getTargetException().printStackTrace();
         return null;
     }
     return result;
 }
Ejemplo n.º 5
0
  private static void applyGroupMatching(TestNG testng, Map options) throws TestSetFailedException {
    String groups = (String) options.get(ProviderParameterNames.TESTNG_GROUPS_PROP);
    String excludedGroups = (String) options.get(ProviderParameterNames.TESTNG_EXCLUDEDGROUPS_PROP);

    if (groups == null && excludedGroups == null) {
      return;
    }

    // the class is available in the testClassPath
    String clazzName = "org.apache.maven.surefire.testng.utils.GroupMatcherMethodSelector";
    // looks to need a high value
    testng.addMethodSelector(clazzName, 9999);
    try {
      Class clazz = Class.forName(clazzName);

      // HORRIBLE hack, but TNG doesn't allow us to setup a method selector instance directly.
      Method method = clazz.getMethod("setGroups", new Class[] {String.class, String.class});
      method.invoke(null, new Object[] {groups, excludedGroups});
    } catch (ClassNotFoundException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (SecurityException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (NoSuchMethodException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalArgumentException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    }
  }
Ejemplo n.º 6
0
 /**
  * @param component The component to analyse.
  * @return All config options of the component with their respective value.
  */
 public static Map<ConfigOption, Object> getConfigOptionValues(Component component) {
   Map<ConfigOption, Object> optionValues = new HashMap<ConfigOption, Object>();
   List<Field> fields = getAllFields(component);
   for (Field field : fields) {
     ConfigOption option = field.getAnnotation(ConfigOption.class);
     if (option != null) {
       try {
         // we invoke the public getter instead of accessing a private field (may cause problem
         // with SecurityManagers)
         // use Spring BeanUtils TODO: might be unnecessarily slow because we already have the
         // field?
         Object value =
             BeanUtils.getPropertyDescriptor(component.getClass(), field.getName())
                 .getReadMethod()
                 .invoke(component);
         optionValues.put(option, value);
       } catch (IllegalArgumentException e1) {
         e1.printStackTrace();
       } catch (IllegalAccessException e1) {
         e1.printStackTrace();
       } catch (BeansException e) {
         e.printStackTrace();
       } catch (InvocationTargetException e) {
         e.printStackTrace();
       }
     }
   }
   return optionValues;
 }
Ejemplo n.º 7
0
  private void dumpDocuments() throws IOException {
    outputBanner("Documents");

    int totalDocs = mIndexReader.numDocs();

    outputLn();
    outputLn("There are " + totalDocs + " documents in this index.");

    mConsole.debug("Total number of documents: " + totalDocs);
    for (int i = 0; i < totalDocs; i++) {
      Document doc = null;
      try {
        doc = mIndexReader.document(i, null);
      } catch (IllegalArgumentException e) {
        if ("attempt to access a deleted document".equals(e.getMessage())) {
          mConsole.warn(
              "encountered exception while dumping document " + i + ": " + e.getMessage());
        } else {
          throw e;
        }
      }
      dumpDocument(i, doc);

      if ((i + 1) % 100 == 0) {
        mConsole.debug("Dumped " + (i + 1) + " documents");
      }
    }
  }
Ejemplo n.º 8
0
  public static void main(String[] args) throws Exception {
    System.out.println("Well, you think your EnumSingleton is really a singleton");

    System.out.println(
        "The id of the INSTANCE object is " + System.identityHashCode(EnumSingleton.INSTANCE));

    System.out.println("I will create another instance using reflection");
    Constructor<EnumSingleton> privateConstructor =
        EnumSingleton.class.getDeclaredConstructor(String.class, int.class);
    privateConstructor.setAccessible(true);
    try {
      privateConstructor.newInstance();
    } catch (IllegalArgumentException e) {
      System.out.println(
          "D'oh! An exception prevented me from creating a new instance: " + e.getMessage());
    }

    System.out.println("Hmm, I will try one more option - Serialisation");

    EnumSingleton clone = SerializationUtils.clone(EnumSingleton.INSTANCE);

    System.out.println(
        "D'oh! Even serialization did not work. id = " + System.identityHashCode(clone));

    System.out.println("I give up");
  }
Ejemplo n.º 9
0
  /**
   * Parses the arguments.
   *
   * @param args the args
   */
  private void parseArguments(String[] args) {
    try {
      for (int i = 0; i < args.length; ) {
        logger.fine("Parsing argument '" + args[i] + "' = '" + args[i + 1] + "'");

        if ("-jcreport".equals(args[i])) {
          addReport(new File(args[i + 1]));
        } else if ("-filter".equals(args[i])) {
          addFilter(new File(args[i + 1]));
        } else if ("-old".equals(args[i])) {
          setOldFile(new File(args[i + 1]));
        } else if ("-loglevel".equals(args[i])) {
          setLogLevel(Level.parse(args[i + 1]));
        } else if ("-out".equals(args[i])) {
          setOutFile(new File(args[i + 1]));
        } else {
          throw new IllegalArgumentException("Invalid argument '" + args[i] + "'");
        }

        ++i;
        ++i;
      }
    } catch (IndexOutOfBoundsException e) {
      final IllegalArgumentException ex =
          new IllegalArgumentException("Missing value for " + args[args.length - 1]);
      ex.initCause(e);
      throw ex;
    } catch (IOException e) {
      final IllegalArgumentException ex =
          new IllegalArgumentException("Wrong out folder " + args[args.length - 1]);
      ex.initCause(e);
      throw ex;
    }
  }
Ejemplo n.º 10
0
  private void executeBatchQueries(HttpRequest request, HttpResponder responder) {
    if (HttpHeaders.getContentLength(request) > 0) {
      try {
        String json = request.getContent().toString(Charsets.UTF_8);
        Map<String, QueryRequestFormat> queries =
            GSON.fromJson(json, new TypeToken<Map<String, QueryRequestFormat>>() {}.getType());

        LOG.trace("Received Queries {}", queries);

        Map<String, MetricQueryResult> queryFinalResponse = Maps.newHashMap();
        for (Map.Entry<String, QueryRequestFormat> query : queries.entrySet()) {
          MetricQueryRequest queryRequest = getQueryRequestFromFormat(query.getValue());
          queryFinalResponse.put(query.getKey(), executeQuery(queryRequest));
        }
        responder.sendJson(HttpResponseStatus.OK, queryFinalResponse);
      } catch (IllegalArgumentException e) {
        LOG.warn("Invalid request", e);
        responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage());
      } catch (Exception e) {
        LOG.error("Exception querying metrics ", e);
        responder.sendString(
            HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics");
      }
    } else {
      responder.sendJson(HttpResponseStatus.BAD_REQUEST, "Batch request with empty content");
    }
  }
 /**
  * 获取状态栏高度
  *
  * @param activity
  * @return
  */
 public int getStatusHeight(Activity activity) {
   int statusHeight = 0;
   Rect localRect = new Rect();
   activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
   statusHeight = localRect.top;
   if (0 == statusHeight) {
     Class<?> localClass;
     try {
       localClass = Class.forName("com.android.internal.R$dimen");
       Object localObject = localClass.newInstance();
       int i5 =
           Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
       statusHeight = activity.getResources().getDimensionPixelSize(i5);
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InstantiationException e) {
       e.printStackTrace();
     } catch (NumberFormatException e) {
       e.printStackTrace();
     } catch (IllegalArgumentException e) {
       e.printStackTrace();
     } catch (SecurityException e) {
       e.printStackTrace();
     } catch (NoSuchFieldException e) {
       e.printStackTrace();
     }
   }
   return statusHeight;
 }
Ejemplo n.º 12
0
  /** Verify that the launch configuration name is valid. */
  private void verifyName() throws CoreException {
    if (configNameText.isVisible()) {
      ILaunchManager mgr = getLaunchManager();
      String currentName = configNameText.getText().trim();

      // If there is no name, complain
      if (currentName.length() < 1) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                DartDebugUIPlugin.PLUGIN_ID,
                0,
                Messages.ManageLaunchesDialog_Name_required_for_launch_configuration,
                null));
      }
      try {
        mgr.isValidLaunchConfigurationName(currentName);
      } catch (IllegalArgumentException iae) {
        throw new CoreException(
            new Status(IStatus.ERROR, DartDebugUIPlugin.PLUGIN_ID, 0, iae.getMessage(), null));
      }
      // Otherwise, if there's already a config with the same name, complain
      if (!launchConfig.getName().equals(currentName)) {
        if (mgr.isExistingLaunchConfigurationName(currentName)) {
          throw new CoreException(
              new Status(
                  IStatus.ERROR,
                  DartDebugUIPlugin.PLUGIN_ID,
                  0,
                  Messages.ManageLaunchesDialog_Launch_configuration_already_exists_with_this_name,
                  null));
        }
      }
    }
  }
 public void testSameAggregationName() throws Exception {
   final String name = randomAsciiOfLengthBetween(1, 10);
   String source =
       JsonXContent.contentBuilder()
           .startObject()
           .startObject(name)
           .startObject("terms")
           .field("field", "a")
           .endObject()
           .endObject()
           .startObject(name)
           .startObject("terms")
           .field("field", "b")
           .endObject()
           .endObject()
           .endObject()
           .string();
   try {
     XContentParser parser = XContentFactory.xContent(source).createParser(source);
     QueryParseContext parseContext =
         new QueryParseContext(queriesRegistry, parser, parseFieldMatcher);
     assertSame(XContentParser.Token.START_OBJECT, parser.nextToken());
     aggParsers.parseAggregators(parseContext);
     fail();
   } catch (IllegalArgumentException e) {
     assertThat(
         e.toString(),
         containsString("Two sibling aggregations cannot have the same name: [" + name + "]"));
   }
 }
Ejemplo n.º 14
0
  public static void Setup() {

    String musicDir = Environment.getExternalStorageDirectory().getAbsolutePath() + MUSIC_DIR;

    mediaPlayer = new MediaPlayer();

    try {

      mediaPlayer.setDataSource(musicDir);
      mediaPlayer.prepare();
      mediaPlayer.setLooping(true);

    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 15
0
  public static String CreateZip(String[] filesToZip, String zipFileName) {

    byte[] buffer = new byte[18024];

    try {

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      out.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < filesToZip.length; i++) {
        FileInputStream in = new FileInputStream(filesToZip[i]);
        String fileName = null;
        for (int X = filesToZip[i].length() - 1; X >= 0; X--) {
          if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') {
            fileName = filesToZip[i].substring(X + 1);
            break;
          } else if (X == 0) fileName = filesToZip[i];
        }
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        out.closeEntry();
        in.close();
      }
      out.close();
    } catch (IllegalArgumentException e) {
      return "Failed to create zip: " + e.toString();
    } catch (FileNotFoundException e) {
      return "Failed to create zip: " + e.toString();
    } catch (IOException e) {
      return "Failed to create zip: " + e.toString();
    }
    return "Success";
  }
  @Override
  public void onBindViewHolder(GroupsViewHolder groupViewHolder, int i) {
    if (getItemViewType(i) == 0) {
      holder1 = (ProfileInfoViewHolder) groupViewHolder;
      // Log.d("name",SharedpreferenceUtility.getInstance(context).getString(AppConstants.PERSON_NAME));
      String url = SharedpreferenceUtility.getInstance(context).getString(AppConstants.PHOTO_URL);
      Log.d("URL", url);
      try {
        Picasso.with(context).load(url).into(profile_image);
      } catch (IllegalArgumentException e) {
        // profile_image.setImageDrawable(default_profile);
        e.printStackTrace();
      }
      profile_name.setText(
          SharedpreferenceUtility.getInstance(context).getString(AppConstants.PERSON_NAME));
      tv_branch.setText(
          SharedpreferenceUtility.getInstance(context).getString(AppConstants.BRANCH));
      tv_batch_of.setText(
          "Batch of " + SharedpreferenceUtility.getInstance(context).getString(AppConstants.BATCH));

      if (GroupsJoinedList.size() == 1) {
        grps_heading.setVisibility(View.GONE);
        no_grps_heading.setVisibility(View.VISIBLE);
      }
    } else {
      if (GroupsJoinedList.size() > 0 && GroupsJoinedList.size() != 1) {
        holder2 = (GroupsJoinedListHolder) groupViewHolder;
        Log.d("ViewProfilePageAdapter", String.valueOf(i));
        holder2.group_joined.setText(this.GroupsJoinedList.get(i - 1).getAbb());
      }
    }
  }
  @Test
  public void testWithAdditionalRequestHeader() {
    RequestHeader additionalRequestHeader =
        new RequestHeader(additionalHeaderName, UUID.randomUUID().toString());

    MetaDataProviderBuilder builder = new MetaDataProviderBuilder("Ingenico");
    if (isAllowed) {
      MetaDataProvider metaDataProvider =
          builder.withAdditionalRequestHeader(additionalRequestHeader).build();
      Collection<RequestHeader> requestHeaders = metaDataProvider.getServerMetaDataHeaders();
      Assert.assertEquals(2, requestHeaders.size());

      Iterator<RequestHeader> requestHeaderIterator = requestHeaders.iterator();
      RequestHeader requestHeader = requestHeaderIterator.next();
      Assert.assertEquals("X-GCS-ServerMetaInfo", requestHeader.getName());

      requestHeader = requestHeaderIterator.next();
      Assert.assertThat(requestHeader, new RequestHeaderMatcher(additionalRequestHeader));
    } else {
      try {
        builder.withAdditionalRequestHeader(additionalRequestHeader);
        Assert.fail("expected IllegalArgumentException");
      } catch (IllegalArgumentException e) {
        Assert.assertThat(e.getMessage(), Matchers.containsString(additionalHeaderName));
      }
    }
  }
Ejemplo n.º 18
0
  public void setEntity(java.lang.Object ent) {
    Method[] methods = ent.getClass().getDeclaredMethods();
    box.removeAll();
    for (Method m : methods) {
      if (m.getName().toLowerCase().startsWith("get")) {
        String attName = m.getName().substring(3);
        Object result;
        try {
          result = m.invoke(ent, new Object[] {});
          String value = "null";
          if (result != null) value = result.toString();
          JPanel attPane = new JPanel(new FlowLayout(FlowLayout.LEFT));
          attPane.add(new JLabel(attName + " : " + m.getReturnType().getName() + " = " + value));
          box.add(attPane);
        } catch (IllegalArgumentException e) {

          e.printStackTrace();
        } catch (IllegalAccessException e) {

          e.printStackTrace();
        } catch (InvocationTargetException e) {

          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 19
0
  /**
   * Program entry point.
   *
   * @param args program arguments
   */
  public static void main(String[] args) {
    try {

      // configure Orekit
      Autoconfiguration.configureOrekit();

      // input/out
      File input =
          new File(VisibilityCircle.class.getResource("/visibility-circle.in").toURI().getPath());
      File output = new File(input.getParentFile(), "visibility-circle.csv");

      new VisibilityCircle().run(input, output, ",");

      System.out.println("visibility circle saved as file " + output);

    } catch (URISyntaxException use) {
      System.err.println(use.getLocalizedMessage());
      System.exit(1);
    } catch (IOException ioe) {
      System.err.println(ioe.getLocalizedMessage());
      System.exit(1);
    } catch (IllegalArgumentException iae) {
      System.err.println(iae.getLocalizedMessage());
      System.exit(1);
    } catch (OrekitException oe) {
      System.err.println(oe.getLocalizedMessage());
      System.exit(1);
    }
  }
 public void testConstructingWithNullActionAsKey() {
   try {
     new ActionWithKeyOverride(null, null);
   } catch (IllegalArgumentException iae) {
     assertEquals(ActionWithKeyOverride.ERROR_ACTIONASKEY_MISSING, iae.getMessage());
   }
 }
Ejemplo n.º 21
0
      private String lastURL() throws URISyntaxException {
        try {
          Address adr = getAddress();
          String scheme = decode(getScheme()).toString();
          int port = adr.getPort();
          if ((scheme.equals("http") && port == 80) || (scheme.equals("https") && port == 443)) {
            port = -1;
          }

          URI uri = new URI(scheme, null, adr.getHost(), port, null, null, null);

          uri = uri.resolve(getRequestURI());
          return uri.toString();
        }
        // URI can also throw IllegalArgumentException wrapping
        // a URISyntaxException. Unwrap it.
        catch (IllegalArgumentException x) {
          Throwable cause = x.getCause();
          if ((cause != null) && (cause instanceof URISyntaxException)) {
            throw (URISyntaxException) cause;
          } else {
            throw x;
          }
        }
      }
Ejemplo n.º 22
0
 protected void test(String fileName, String errorMessage) throws Exception {
   try {
     _seleniumBuilderFileUtil.getRootElement(_DIR_NAME + "/" + fileName);
   } catch (IllegalArgumentException e) {
     Assert.assertEquals(errorMessage, e.getMessage());
   }
 }
Ejemplo n.º 23
0
  @Override
  public void register(final ExtensionBuilder builder) {
    if (ArquillianUtil.isCurrentAdapter(ADAPTER)) {

      final ReentrantLock l = lock;
      l.lock();

      try {

        if (!registered.getAndSet(true)) {

          try {
            builder.observer(DeploymentExceptionObserver.class);
            builder.observer(RemoteInitialContextObserver.class);

            builder
                .service(DeployableContainer.class, TomEEWebappContainer.class)
                .service(
                    AuxiliaryArchiveAppender.class, TomEEWebappEJBEnricherArchiveAppender.class)
                .service(ResourceProvider.class, DeploymentExceptionProvider.class);
          } catch (IllegalArgumentException e) {
            Logger.getLogger(TomEEWebappExtension.class.getName())
                .log(Level.WARNING, "TomEEWebappExtension: " + e.getMessage());
          }
        }
      } finally {
        l.unlock();
      }
    }
  }
Ejemplo n.º 24
0
 /**
  * Main method
  *
  * @param args commandline arguments
  */
 public static void main(String... args) {
   Exception error = null;
   try {
     InitLog.initLogger(args, getParser());
     log.info(getParser().getAppName() + ": Start");
     new XSLTranslator(args).execute();
   } catch (IllegalArgumentException e) {
     log.error(e.getMessage());
     log.debug("Stacktrace:", e);
     System.out.println(getParser().getUsage());
     error = e;
   } catch (UsageException e) {
     log.info("Printing Usage:");
     System.out.println(getParser().getUsage());
     error = e;
   } catch (Exception e) {
     log.error(e.getMessage());
     log.debug("Stacktrace:", e);
     error = e;
   } finally {
     log.info(getParser().getAppName() + ": End");
     if (error != null) {
       System.exit(1);
     }
   }
 }
Ejemplo n.º 25
0
  public void testRegisteredQueries() throws IOException {
    SearchModule module = new SearchModule(Settings.EMPTY, false, emptyList());
    List<String> allSupportedQueries = new ArrayList<>();
    Collections.addAll(allSupportedQueries, NON_DEPRECATED_QUERIES);
    Collections.addAll(allSupportedQueries, DEPRECATED_QUERIES);
    String[] supportedQueries = allSupportedQueries.toArray(new String[allSupportedQueries.size()]);
    assertThat(module.getQueryParserRegistry().getNames(), containsInAnyOrder(supportedQueries));

    IndicesQueriesRegistry indicesQueriesRegistry = module.getQueryParserRegistry();
    XContentParser dummyParser = XContentHelper.createParser(new BytesArray("{}"));
    for (String queryName : supportedQueries) {
      indicesQueriesRegistry.lookup(
          queryName, ParseFieldMatcher.EMPTY, dummyParser.getTokenLocation());
    }

    for (String queryName : NON_DEPRECATED_QUERIES) {
      QueryParser<?> queryParser =
          indicesQueriesRegistry.lookup(
              queryName, ParseFieldMatcher.STRICT, dummyParser.getTokenLocation());
      assertThat(queryParser, notNullValue());
    }
    for (String queryName : DEPRECATED_QUERIES) {
      try {
        indicesQueriesRegistry.lookup(
            queryName, ParseFieldMatcher.STRICT, dummyParser.getTokenLocation());
        fail("query is deprecated, getQueryParser should have failed in strict mode");
      } catch (IllegalArgumentException e) {
        assertThat(e.getMessage(), containsString("Deprecated field [" + queryName + "] used"));
      }
    }
  }
  @Test
  public void testUnknownProperty() throws Exception {
    context.addRoutes(
        new RouteBuilder() {
          @Override
          public void configure() throws Exception {
            // define socket connector properties
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put("acceptors", 4);
            properties.put("statsOn", "false");
            properties.put("soLingerTime", "5000");
            properties.put("doesNotExist", 2000);

            // create jetty component
            JettyHttpComponent jetty = new JettyHttpComponent();
            // set properties
            jetty.setSslSocketConnectorProperties(properties);
            // add jetty to camel context
            context.addComponent("jetty", jetty);

            from("jetty:https://localhost:{{port}}/myapp/myservice").to("log:foo");
          }
        });
    try {
      context.start();
      fail("Should have thrown exception");
    } catch (IllegalArgumentException e) {
      assertTrue(e.getMessage().endsWith("Unknown parameters=[{doesNotExist=2000}]"));
    }
  }
Ejemplo n.º 27
0
  private static void applyMethodNameFiltering(TestNG testng, String methodNamePattern)
      throws TestSetFailedException {
    // the class is available in the testClassPath
    String clazzName = "org.apache.maven.surefire.testng.utils.MethodSelector";
    // looks to need a high value
    testng.addMethodSelector(clazzName, 10000);
    try {
      Class clazz = Class.forName(clazzName);

      Method method = clazz.getMethod("setMethodName", new Class[] {String.class});
      method.invoke(null, new Object[] {methodNamePattern});
    } catch (ClassNotFoundException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (SecurityException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (NoSuchMethodException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalArgumentException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      throw new TestSetFailedException(e.getMessage(), e);
    }
  }
  static void testReflectionTest3() {
    try {
      String imei = taintedString();

      Class c = Class.forName("de.ecspride.ReflectiveClass");
      Object o = c.newInstance();
      Method m = c.getMethod("setIme" + "i", String.class);
      m.invoke(o, imei);

      Method m2 = c.getMethod("getImei");
      String s = (String) m2.invoke(o);

      assert (getTaint(s) != 0);
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 29
0
  public static int getResourseIdByName(String packageName, String className, String name) {
    Class r = null;
    int id = 0;
    try {
      r = Class.forName(packageName + ".R");

      Class[] classes = r.getClasses();
      Class desireClass = null;

      for (int i = 0; i < classes.length; i++) {
        if (classes[i].getName().split("\\$")[1].equals(className)) {
          desireClass = classes[i];

          break;
        }
      }

      if (desireClass != null) id = desireClass.getField(name).getInt(desireClass);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    }

    return id;
  }
Ejemplo n.º 30
0
 /**
  * * 保存实体
  *
  * @param entity 实体类
  * @param keyName 实体类中获取主键的方法名字, 例如:getId<br>
  *     当为空时({@link StringUtils#isBlank(CharSequence)}),系统会自动找出注解有{@link
  *     javax.persistence.Id}的方法(即主键的get方法)
  * @return 返回保存实体的主键
  */
 public Object save(final T entity, String keyName) {
   entityManager.persist(entity);
   Object o = null;
   try {
     if (StringUtils.isNotBlank(keyName)) {
       o = clazz.getMethod(keyName).invoke(entity);
     } else {
       for (Method m1 : clazz.getMethods()) {
         if (m1.isAnnotationPresent(javax.persistence.Id.class)) {
           o = m1.invoke(entity);
           break;
         }
       }
     }
   } catch (SecurityException e) {
     e.printStackTrace();
   } catch (NoSuchMethodException e) {
     e.printStackTrace();
   } catch (IllegalArgumentException e) {
     e.printStackTrace();
   } catch (IllegalAccessException e) {
     e.printStackTrace();
   } catch (InvocationTargetException e) {
     e.printStackTrace();
   }
   return o;
 }