private String translateToString(Packet packet, int pos) {
   String ptr = " ";
   if (pos == currentIndex) ptr = " \2474";
   if (packet == null) return (count + pos) + "null:[]";
   String trans = ptr + (count + pos) + "\247r: " + packet.getClass().getSimpleName() + ": [";
   int vars = 0;
   for (Field f : packet.getClass().getDeclaredFields()) {
     if (!Modifier.isStatic(f.getModifiers())) {
       if (!f.isAccessible()) f.setAccessible(true);
       try {
         Object obj = f.get(packet);
         String value = "null";
         if (obj != null) value = obj.toString();
         trans += " f" + vars + "=" + value + ",";
       } catch (IllegalArgumentException | IllegalAccessException e) {
         e.printStackTrace();
       }
     }
   }
   if (trans.endsWith(",")) {
     trans = trans.substring(0, trans.length() - 1);
   }
   trans += "]";
   return trans;
 }
예제 #2
0
 private void doRequest(Object info) {
   try {
     Response response = this.callPDP(RequestParser.parseRequest(info));
     Path resultFile;
     if (this.output != null) {
       resultFile =
           Paths.get(
               this.output.toString(), "Response." + String.format("%03d", this.num) + ".json");
     } else {
       resultFile =
           Paths.get(
               this.directory, "results", "Response." + String.format("%03d", this.num) + ".json");
     }
     //
     // Write the response to the result file
     //
     logger.info("Response is: " + response.toString());
     if (resultFile != null) {
       Files.write(resultFile, response.toString().getBytes());
     }
   } catch (IllegalArgumentException
       | IllegalAccessException
       | DataTypeException
       | IOException e) {
     logger.error(e);
     e.printStackTrace();
   }
 }
예제 #3
0
 static String getNamedCurveObjectId(final ECParameterSpec namedCurve) {
   try {
     return (String) method_NamedCurve_getObjectId.invoke(namedCurve, (Object) null);
   } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
     LOG.warn("{}: {}", e.getClass().getName(), e.getMessage());
     return null;
   }
 }
예제 #4
0
 static ECParameterSpec lookupCurve(final ECParameterSpec paramSpec) {
   try {
     return (ECParameterSpec) method_CurveDB_lookup_paramSpec.invoke(null, paramSpec);
   } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
     LOG.warn("{}: {}", e.getClass().getName(), e.getMessage());
     return null;
   }
 }
예제 #5
0
 public Presets(String key) {
   for (Field f : this.getClass().getDeclaredFields()) {
     if (f.getName().equalsIgnoreCase(key)) {
       try {
         i = (Class<?>) f.get(this);
       } catch (IllegalArgumentException | IllegalAccessException e) {
         e.printStackTrace();
       }
     }
   }
 }
예제 #6
0
  private static boolean curve_isRegistered(
      final Method method_lookup, final ASN1ObjectIdentifier curveId) {
    try {
      Object curve = method_lookup.invoke(null, new Object[] {curveId.getId()});
      return curve != null;
    } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
      LOG.warn("{}: {}", e.getClass().getName(), e.getMessage());
    }

    return true; // if error occurs, just return true
  }
예제 #7
0
 /**
  * Create an instance of all variables to avoid Null Pointer Exceptions when trying to access
  * variables which aren't loaded from a file.
  */
 private void initializeVariables() {
   Field[] fields = ServerData.class.getDeclaredFields();
   for (Field field : fields) {
     try {
       if (field.get(this) == null) {
         field.set(this, field.getType().newInstance());
       }
     } catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {
       e.printStackTrace();
     }
   }
 }
예제 #8
0
  // this function should only be used while the sql resultset is still valid,
  // i.e. the connection related to the resultset is still valid (not closed)
  public static String getSqlResult(ResultSet resultSet) throws SQLException {
    StringBuffer stringBuffer = new StringBuffer();
    List columnLabels = new ArrayList<String>();

    try {
      int columnCount = resultSet.getMetaData().getColumnCount();
      for (int i = 1; i <= columnCount; i++) {
        columnLabels.add(resultSet.getMetaData().getColumnLabel(i));
      }
      List<Integer> types = Lists.newArrayList();
      for (int i = 1; i <= columnCount; i++) {
        types.add(resultSet.getMetaData().getColumnType(i));
      }

      LOG.debug("Result set data types:");
      LOG.debug(Utils.getTypesInStrings(types));
      stringBuffer.append(new ColumnList(types, columnLabels).toString() + "\n");

      while (resultSet.next()) {
        List<Object> values = Lists.newArrayList();
        for (int i = 1; i <= columnCount; i++) {
          try {
            if (resultSet.getObject(i) == null) {
              values.add(null);
              continue;
            }
            if (resultSet.getMetaData().getColumnType(i) == Types.NVARCHAR) {
              values.add(new String(resultSet.getBytes(i), "UTF-16"));
            } else {
              values.add(new String(resultSet.getBytes(i), "UTF-8"));
            }
          } catch (Exception e) {
            if (resultSet.getMetaData().getColumnType(i) == Types.DATE) {
              values.add(resultSet.getDate(i));
            } else {
              values.add(resultSet.getObject(i));
            }
          }
        }
        stringBuffer.append(new ColumnList(types, values).toString() + "\n");
      }
    } catch (IllegalArgumentException | IllegalAccessException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
    }
    return stringBuffer.toString();
  }
예제 #9
0
 public static void injectFieldWithAnnotation(
     Field injectField, Object instance, Object injection) {
   if (injectField != null) {
     boolean oldAccessible = injectField.isAccessible();
     try {
       injectField.setAccessible(true);
       injectField.set(instance, injection);
     } catch (IllegalArgumentException | IllegalAccessException e) {
       e.printStackTrace();
     } finally {
       injectField.setAccessible(oldAccessible);
     }
   }
 }
예제 #10
0
  @Override
  public String serialize(Object obj) {
    if (obj == null) {
      return "\"null\"";
    }
    if (isDirectlySerializable(obj)) {
      return "\"" + obj.toString() + "\"";
    }
    if (isCollection(obj)) {
      return serializeCollection((Collection<?>) obj);
    }
    if (isArray(obj)) {
      return serializeCollection(Arrays.asList(obj));
    }

    final StringBuffer result = new StringBuffer();
    result.append("{");
    List<Field> fieldsToSerialize = getFieldsToSerialize(obj.getClass());
    for (Field field : fieldsToSerialize) {
      field.setAccessible(true);

      Object value = null;

      try {
        value = field.get(obj);
      } catch (IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
      }

      if (value != null || areIncludedNullFields()) {

        if (field.isAnnotationPresent(MapBy.class)) {
          result.append(field.getAnnotation(MapBy.class).value()).append(" : ");
        } else {
          result.append(field.getName()).append(" : ");
        }

        result.append(serialize(value));
        result.append(", ");
      }
    }
    if (!fieldsToSerialize.isEmpty()) {
      result.deleteCharAt(result.length() - 1);
      result.deleteCharAt(result.length() - 1);
    }
    result.append("}");
    return result.toString();
  }
 private void resetButtonActionPerformed(ActionEvent evt) {
   Map<String, Field> rfields = Configuration.getConfigurationFields();
   for (Entry<String, Field> entry : rfields.entrySet()) {
     String name = entry.getKey();
     Field field = entry.getValue();
     try {
       ConfigurationItem item = (ConfigurationItem) field.get(null);
       item.unset();
     } catch (IllegalArgumentException | IllegalAccessException ex) {
       // Reflection exceptions. This should never happen
       throw new Error(ex.getMessage());
     }
   }
   Configuration.saveConfig();
   setVisible(false);
   showRestartConfirmDialod();
 }
예제 #12
0
 @Override
 public Object visit(KnowledgeVariable query) {
   Class<? extends BaseDataContract> dataContractClass = instance.getClass();
   String qualifier = query.getPath().toParts().get(0);
   if (qualifier.equals(ContextSymbols.WHERE_IT_SYMBOL)) {
     String fieldName = query.getPath().toParts().get(1);
     try {
       return dataContractClass.getField(fieldName).get(instance);
     } catch (IllegalArgumentException
         | IllegalAccessException
         | NoSuchFieldException
         | SecurityException e) {
       e.printStackTrace();
       return null;
     }
   } else {
     return ensembleId;
   }
 }
예제 #13
0
  private static boolean NamedCurve_add(
      final Method method_add,
      final String name,
      final String soid,
      final int type,
      final String sfield,
      final String a,
      final String b,
      final String x,
      final String y,
      final String n,
      final int h) {
    try {
      method_add.invoke(null, new Object[] {name, soid, type, sfield, a, b, x, y, n, h});
    } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
      LOG.warn("{}: {}", e.getClass().getName(), e.getMessage());
      return false;
    }

    return true;
  }
예제 #14
0
 public Field[] printFields(Object obj, boolean recursive) {
   Class<?> classObj = obj.getClass();
   Field[] fields = classObj.getDeclaredFields();
   ArrayList<Object> toInspect = new ArrayList<>();
   System.out.println("Fields: ");
   if (fields.length > 0) {
     for (Field field : fields) {
       System.out.println("\tName: " + field.getName());
       System.out.println("\tType: " + field.getType());
       int mod = field.getModifiers();
       System.out.println("\tModifiers: " + Modifier.toString(mod));
       Object value = null;
       field.setAccessible(true);
       try {
         value = field.get(obj);
       } catch (IllegalArgumentException | IllegalAccessException e) {
         e.printStackTrace();
       }
       if (recursive && !field.getType().isPrimitive()) {
         if (!inspected.contains(value) && value != null) {
           toInspect.add(value);
           System.out.println("\tCurrent Value: ...recursive call...");
         } else {
           if (value == null) System.out.println("\tCurrent Value: null");
           else System.out.println("\tCurrent Value: Already Inspected");
         }
       } else {
         if (!field.getType().isPrimitive()) System.out.println("\tCurrent Value: pointer value");
         else System.out.println("\tCurrent Value: " + value);
       }
       System.out.println("");
     }
   } else System.out.println("-");
   if (recursive)
     for (Object object : toInspect) {
       inspect(object, recursive);
     }
   return fields;
 }
예제 #15
0
파일: myPlugin.java 프로젝트: caliog/myRPG
 private void mkdir() {
   for (Field f : FilePath.class.getFields()) {
     try {
       String value = (String) f.get(this);
       String[] split = value.split("/");
       String name = split[split.length - 1];
       File file = new File(value);
       if (!value.equals(FilePath.mic))
         if (!file.exists()) {
           if (value.endsWith("/")) {
             file.mkdir();
           } else {
             if (value.equals(FilePath.mic)) continue;
             if (value.equals(FilePath.spellCollection)) continue;
             file.createNewFile();
             fc.copyFile(value, name);
           }
         }
     } catch (IllegalArgumentException | IllegalAccessException | IOException e) {
       e.printStackTrace();
     }
   }
 }
예제 #16
0
    /** Map function for non-indexed blocks */
    public void map(
        final Prism cellMbr,
        final Writable value,
        final OutputCollector<Writable, IntWritable> output,
        Reporter reporter)
        throws IOException {
      if (value instanceof Shape) {
        try {
          Shape shape = (Shape) value;
          Class<?> c = shape.getClass();
          Field f;
          f = c.getDeclaredField(queryField);
          f.setAccessible(true);

          if (shape.isIntersected(queryShape)) {
            boolean report_result = false;
            if (cellMbr.isValid()) {
              // Check for duplicate avoidance using reference
              // point
              // technique
              double reference_t = Math.max(queryMbr.t1, shape.getMBR().t1);
              double reference_x = Math.max(queryMbr.x1, shape.getMBR().x1);
              double reference_y = Math.max(queryMbr.y1, shape.getMBR().y1);
              report_result = cellMbr.contains(reference_t, reference_x, reference_y);
            } else {
              // A heap block, report right away
              report_result = true;
            }

            if (report_result) {
              Writable result = null;
              if (f.getType().equals(Integer.TYPE)) {
                try {
                  result = new IntWritable((int) f.get(shape));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              } else if (f.getType().equals(Long.TYPE)) {
                try {
                  result = new LongWritable((int) f.get(shape));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              } else if (f.getType().equals(Double.TYPE)) {
                try {
                  result = new DoubleWritable((int) f.get(shape));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              }
              output.collect(result, one);
            }
          }
        } catch (IllegalArgumentException | NoSuchFieldException | SecurityException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } else if (value instanceof RTree) {
        RTree<Shape> shapes = (RTree<Shape>) value;
        if (shapes.columnar) {
          shapes.searchColumnar(
              queryMbr,
              new ResultCollector<Writable>() {
                @Override
                public void collect(Writable shape) {
                  try {
                    output.collect(shape, one);
                  } catch (IOException e) {
                    e.printStackTrace();
                  }
                }
              },
              queryField);
        } else {
          shapes.search(
              queryMbr,
              new ResultCollector<Shape>() {
                @Override
                public void collect(Shape shape) {
                  try {
                    Class<?> c = shape.getClass();
                    Field f;
                    f = c.getDeclaredField(queryField);
                    f.setAccessible(true);
                    Writable result = null;
                    if (f.getType().equals(Integer.class)) {
                      result = new IntWritable((int) f.get(shape));
                    } else if (f.getType().equals(Integer.class)) {
                      result = new IntWritable((int) f.get(shape));
                    } else if (f.getType().equals(Integer.class)) {
                      result = new IntWritable((int) f.get(shape));
                    }
                    output.collect(result, one);

                  } catch (IOException e) {
                    e.printStackTrace();
                  } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (NoSuchFieldException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                }
              },
              queryField);
        }
      }
    }
  @SuppressWarnings("unchecked")
  private void okButtonActionPerformed(ActionEvent evt) {
    boolean modified = false;
    Map<String, Field> fields = Configuration.getConfigurationFields();
    Map<String, Object> values = new HashMap<>();
    for (String name : fields.keySet()) {
      Component c = componentsMap.get(name);
      Object value = null;

      ParameterizedType listType = (ParameterizedType) fields.get(name).getGenericType();
      java.lang.reflect.Type itemType2 = listType.getActualTypeArguments()[0];
      if (!(itemType2 instanceof Class<?>)) {
        continue;
      }

      Class itemType = (Class<?>) itemType2;
      if (name.equals("gui.skin")) {
        value = ((SkinSelect) ((JComboBox<SkinSelect>) c).getSelectedItem()).className;
      } else if (itemType == String.class) {
        value = ((JTextField) c).getText();
      }
      if (itemType == Boolean.class) {
        value = ((JCheckBox) c).isSelected();
      }

      if (itemType == Calendar.class) {
        Calendar cal = Calendar.getInstance();
        try {
          cal.setTime(new SimpleDateFormat().parse(((JTextField) c).getText()));
        } catch (ParseException ex) {
          c.requestFocusInWindow();
          return;
        }
        value = cal;
      }

      if (itemType.isEnum()) {
        String stringValue = (String) ((JComboBox<String>) c).getSelectedItem();
        value = Enum.valueOf(itemType, stringValue);
      }

      try {
        if (itemType == Integer.class) {
          value = Integer.parseInt(((JTextField) c).getText());
        }
        if (itemType == Long.class) {
          value = Long.parseLong(((JTextField) c).getText());
        }
        if (itemType == Double.class) {
          value = Double.parseDouble(((JTextField) c).getText());
        }
        if (itemType == Float.class) {
          value = Float.parseFloat(((JTextField) c).getText());
        }
      } catch (NumberFormatException nfe) {
        if (!((JTextField) c).getText().isEmpty()) {
          c.requestFocusInWindow();
          return;
        } // else null
      }
      values.put(name, value);
    }

    for (String name : fields.keySet()) {
      Component c = componentsMap.get(name);
      Object value = values.get(name);

      Field field = fields.get(name);
      ConfigurationItem item = null;
      try {
        item = (ConfigurationItem) field.get(null);
      } catch (IllegalArgumentException | IllegalAccessException ex) {
        // Reflection exceptions. This should never happen
        throw new Error(ex.getMessage());
      }
      if (item.get() == null || !item.get().equals(value)) {
        if (item.hasValue() || value != null) {
          item.set(value);
          modified = true;
        }
      }
    }
    Configuration.saveConfig();
    setVisible(false);
    if (modified) {
      showRestartConfirmDialod();
    }
  }
예제 #18
0
  private static void addNamedCurves_jdk17() {
    final Class<?>[] Param_NamedCurve_add =
        new Class[] {
          String.class,
          String.class,
          int.class,
          String.class,
          String.class,
          String.class,
          String.class,
          String.class,
          String.class,
          int.class
        };
    final Class<?>[] Param_getCurve = new Class[] {String.class};

    Method method_add = getMethod(class_NamedCurve, "add", Param_NamedCurve_add);
    if (method_add == null) {
      return;
    }

    Method method_getCurve = getMethod(class_NamedCurve, "getECParameterSpec", Param_getCurve);
    if (method_getCurve == null) {
      return;
    }

    Field field_SPLIT_PATTERN = getField(class_NamedCurve, "SPLIT_PATTERN");
    if (field_SPLIT_PATTERN == null) {
      return;
    }

    try {
      field_SPLIT_PATTERN.set(null, SPLIT_PATTERN);
    } catch (IllegalArgumentException | IllegalAccessException e) {
      final String message = "could not set Field SPLIT_PATTERN";
      if (LOG.isWarnEnabled()) {
        LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
      }
      LOG.debug(message, e);
      return;
    }

    Set<String> processedCurveOids = new HashSet<>();
    Map<String, String> addedCurves = new HashMap<>();

    Enumeration<?> curveNames = ECNamedCurveTable.getNames();
    while (curveNames.hasMoreElements()) {
      String curveName = (String) curveNames.nextElement();
      ASN1ObjectIdentifier curveId = getCurveId(curveName);

      if (curveId == null) {
        LOG.info("cound not find curve OID for curve {}, ignore it", curveName);
        continue;
      }

      String curveDesc = "named curve " + curveName + " (" + curveId + ")";

      if (processedCurveOids.contains(curveId.getId())) {
        LOG.debug("{} is already processed, ignore it", curveDesc);
        continue;
      }

      processedCurveOids.add(curveId.getId());

      if (curve_isRegistered(method_getCurve, curveId)) {
        LOG.debug("{} is already registered, ignore it", curveDesc);
        continue;
      }

      X9ECParameters params = ECNamedCurveTable.getByOID(curveId);
      ECCurve curve = params.getCurve();

      if (curve instanceof ECCurve.Fp || curve instanceof ECCurve.F2m) {
        CurveData c = new CurveData(params);
        boolean added =
            NamedCurve_add(
                method_add,
                curveName,
                curveId.getId(),
                c.type,
                c.sfield,
                c.a,
                c.b,
                c.x,
                c.y,
                c.n,
                c.h);

        if (added) {
          LOG.debug("added {}", curveDesc);
          addedCurves.put(curveName, curveId.getId());
        } else {
          LOG.warn("could not add {}", curveDesc);
        }
      } else {
        LOG.info("unknown curve type {}", curve.getClass().getName());
      }
    }

    try {
      field_SPLIT_PATTERN.set(null, null);
    } catch (IllegalArgumentException | IllegalAccessException e) {
      final String message = "could not set Field SPLIT_PATTERN";
      if (LOG.isWarnEnabled()) {
        LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
      }
      LOG.debug(message, e);
      return;
    }

    logAddedCurves(addedCurves);
  }
  @SuppressWarnings("unchecked")
  public <E> E doSession(
      Object session,
      String sessionMethodName,
      Object[] parameterList,
      String expectedJSONObjectFileName,
      String expectedJSONArrayFileName,
      String expectedXMLFileName,
      ExpectedExceptionObject expectedException)
      throws TestException, IOException, JSONException {

    E actualResult = null;

    Class<?>[] parameterClassList = new Class<?>[parameterList.length];
    for (int i = 0; i < parameterList.length; i++) {
      parameterClassList[i] = parameterList[i].getClass();
    }

    Method method = null;
    try {
      method = session.getClass().getMethod(sessionMethodName, parameterClassList);
    } catch (NoSuchMethodException | SecurityException e) {
      e.printStackTrace();
      throw new Error(e);
    }

    try {
      actualResult = (E) method.invoke(session, parameterList);
      System.out.println("--- Result ---");
      System.out.println(JsonService.getJsonStringFromJavaObject(actualResult));
      System.out.println("--------------");
      if (null != expectedException) {
        throw new TestNoExceptionException(expectedException.getExpectedClass().toString());
      }
    } catch (IllegalArgumentException | IllegalAccessException e) {
      e.printStackTrace();
      throw new Error(e);
    } catch (InvocationTargetException e) {

      Throwable targetException = e.getTargetException();

      // There was an exception but was not defined the expected OR it was not the expected !!!!
      if (null == expectedException
          || !targetException.getClass().equals(expectedException.getExpectedClass())) {
        throw new TestNotExpectedExceptionException(
            expectedException.getClass().getSimpleName(),
            targetException.getClass().getSimpleName());

        // The exception was the expected but probably the message was different
      } else {

        String expectedMessage = expectedException.getExactMessage();

        // The exact message was specified but it not the same as the catched
        if (null != expectedMessage && !expectedMessage.equals(targetException.getMessage())) {
          throw new TestNotExpectedExceptionMessageException(
              expectedMessage, targetException.getLocalizedMessage());
        }
      }
    }

    // --------------------
    // Compare XML the DB
    // --------------------
    if (null != expectedXMLFileName) {
      try {
        String difference = CompareXMLToDB.getDifference(expectedXMLFileName, conn, database);
        if (null != difference) {
          throw new TestCompareXMLToDBException(expectedXMLFileName, difference);
        }
      } catch (ParserConfigurationException | SAXException | IOException | SQLException e) {
        // e.printStackTrace();
        throw new TestCompareXMLToDBFormatException(e.getLocalizedMessage());
      }
    }

    // ---------------------------------
    // Compare JSONObject to the result
    // ---------------------------------
    if (null != expectedJSONObjectFileName) {
      CompareJSONToResult.doCompareAsJSONObject(expectedJSONObjectFileName, actualResult);

      // ---------------------------------
      // Compare JSONArray to the result
      // ---------------------------------
    } else if (null != expectedJSONArrayFileName) {
      CompareJSONToResult.doCompareAsJSONArray(expectedJSONArrayFileName, actualResult);
    }

    return actualResult;
  }
예제 #20
0
  private static void addNamedCurves_jdk18on() {
    final Class<?>[] Param_CurveDB_add =
        new Class[] {
          String.class,
          String.class,
          int.class,
          String.class,
          String.class,
          String.class,
          String.class,
          String.class,
          String.class,
          int.class,
          Pattern.class
        };
    final Class<?>[] Param_getCurve = new Class[] {String.class};

    Method method_add = getMethod(class_CurveDB, "add", Param_CurveDB_add);
    if (method_add == null) {
      return;
    }

    Method method_getCurve = getMethod(class_CurveDB, "lookup", Param_getCurve);
    if (method_getCurve == null) {
      return;
    }

    Field field_oidMap = getField(class_CurveDB, "oidMap");
    if (field_oidMap == null) {
      return;
    }

    Field field_specCollection = getField(class_CurveDB, "specCollection");
    if (field_specCollection == null) {
      return;
    }

    Set<String> processedCurveOids = new HashSet<>();
    Map<String, String> addedCurves = new HashMap<>();

    Enumeration<?> curveNames = ECNamedCurveTable.getNames();
    while (curveNames.hasMoreElements()) {
      String curveName = (String) curveNames.nextElement();
      ASN1ObjectIdentifier curveId = getCurveId(curveName);
      if (curveId == null) {
        LOG.debug("cound not find curve OID for curve {}, ignore it", curveName);
        continue;
      }

      String curveDesc = "named curve " + curveName + " (" + curveId + ")";

      if (processedCurveOids.contains(curveId.getId())) {
        LOG.debug("{} is already processed, ignore it", curveDesc);
        continue;
      }

      processedCurveOids.add(curveId.getId());

      if (curve_isRegistered(method_getCurve, curveId)) {
        LOG.info("{} is already registered, ignore it", curveDesc);
        continue;
      }

      X9ECParameters params = ECNamedCurveTable.getByOID(curveId);
      ECCurve curve = params.getCurve();
      if (curve instanceof ECCurve.Fp || curve instanceof ECCurve.F2m) {
        CurveData c = new CurveData(params);
        boolean added =
            CurveDB_add(
                method_add,
                curveName,
                curveId.getId(),
                c.type,
                c.sfield,
                c.a,
                c.b,
                c.x,
                c.y,
                c.n,
                c.h);

        if (added) {
          LOG.debug("added {}", curveDesc);
          addedCurves.put(curveName, curveId.getId());
        } else {
          LOG.warn("could not add {}", curveDesc);
        }
      } else {
        LOG.info("unknown curve type {}", curve.getClass().getName());
      }
    }

    try {
      Map<?, ?> oidMap = (Map<?, ?>) field_oidMap.get(null);
      Collection<?> namedCurves = Collections.unmodifiableCollection(oidMap.values());

      field_specCollection.set(null, namedCurves);
    } catch (IllegalArgumentException | IllegalAccessException | ClassCastException e) {
      final String message = "could not update change the value of field CurveDB.specCollection.";
      if (LOG.isWarnEnabled()) {
        LOG.warn(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage());
      }
      LOG.debug(message, e);
    }

    logAddedCurves(addedCurves);
  }
예제 #21
0
  void getMemberInfo(AccessibleObject[] accessers, MemberType type) {
    for (AccessibleObject a : accessers) {
      if (!a.isAnnotationPresent(JsApi.class) && !a.isAnnotationPresent(JsConstructor.class))
        continue;

      MemberInfo mInfo = new MemberInfo();
      String name = ((Member) a).getName();
      mInfo.javaName = name;
      mInfo.accesser = a;
      mInfo.isStatic = Modifier.isStatic(((Member) a).getModifiers());
      if (a.isAnnotationPresent(JsApi.class)) {
        JsApi mAnno = a.getAnnotation(JsApi.class);

        // Get eventList from properties.
        if (type == MemberType.JS_PROPERTY && mAnno.isEventList()) {
          if (!((Field) a).getType().equals(String[].class)) {
            Log.w(TAG, "Invalid type for Supported JS event list" + name);
            continue;
          }
          try {
            // Event List should be a class property with "static".
            eventList = (String[]) (((Field) a).get(null));
          } catch (IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          continue;
        }

        mInfo.type = type;
        mInfo.isWritable = mAnno.isWritable();
        mInfo.isEntryPoint = mAnno.isEntryPoint();
        mInfo.withPromise = mAnno.withPromise();
        mInfo.jsName = name;
        mInfo.wrapArgs = mAnno.wrapArgs();
        mInfo.wrapReturns = mAnno.wrapReturns();
      } else if (a.isAnnotationPresent(JsConstructor.class)) {
        if (type != MemberType.JS_METHOD) {
          Log.w(TAG, "Invalid @JsConstructor on non-function member:" + name);
          continue;
        }
        JsConstructor cAnno = a.getAnnotation(JsConstructor.class);
        mInfo.type = MemberType.JS_CONSTRUCTOR;
        mInfo.isEntryPoint = cAnno.isEntryPoint();
        mInfo.mainClass = cAnno.mainClass();
        // Currently Constructor with promise is not supported.
        mInfo.withPromise = false;
        // TODO: more detail checking for main class.
        // Is there a way to throw compile error if main class missing?
        if (mInfo.mainClass == null) continue;

        mInfo.jsName = mInfo.mainClass.getSimpleName();
        // Create relections for constructor main classes.
        bindingClasses.put(mInfo.mainClass.getName(), mInfo.jsName);
        constructorReflections.put(mInfo.jsName, new ReflectionHelper(mInfo.mainClass));
      }

      if (mInfo.isEntryPoint) {
        // Always get the first entry point setting.
        if (entryPoint != null) {
          Log.w(TAG, "Entry point already exist, try to set another:" + mInfo.jsName);
          continue;
        }
        // Flag isEntryPoint only meaningful for methods, constructors and BindingObjects.
        if (type == MemberType.JS_PROPERTY
            && !(isBindingClass(((Field) (mInfo.accesser)).getType()))) {
          Log.w(TAG, "Invalid entry point setting on property:" + name);
          continue;
        }
        // The first entry point will be used.
        entryPoint = mInfo;
      }
      if (members.containsKey(mInfo.jsName)) {
        Log.w(TAG, "Conflict namespace - " + mInfo.jsName);
        continue;
      }
      members.put(mInfo.jsName, mInfo);
    }
  }
  public static void getCategories(
      Map<String, Component> componentsMap,
      Map<String, Component> tabs,
      JComboBox<?> skinComboBox,
      ResourceBundle resourceBundle) {
    Map<String, Map<String, Field>> categorized = new HashMap<>();

    Map<String, Field> fields = Configuration.getConfigurationFields();
    String[] keys = new String[fields.size()];
    keys = fields.keySet().toArray(keys);
    Arrays.sort(keys);

    for (String name : keys) {
      Field field = fields.get(name);
      ConfigurationCategory cat = field.getAnnotation(ConfigurationCategory.class);
      String scat = cat == null ? "other" : cat.value();
      if (!categorized.containsKey(scat)) {
        categorized.put(scat, new HashMap<>());
      }

      categorized.get(scat).put(name, field);
    }

    for (String cat : categorized.keySet()) {
      JPanel configPanel = new JPanel(new SpringLayout());
      int itemCount = 0;
      for (String name : categorized.get(cat).keySet()) {
        Field field = categorized.get(cat).get(name);

        String locName = resourceBundle.getString("config.name." + name);

        try {
          ConfigurationItem item = (ConfigurationItem) field.get(null);

          ParameterizedType listType = (ParameterizedType) field.getGenericType();
          java.lang.reflect.Type itemType2 = listType.getActualTypeArguments()[0];
          if (!(itemType2 instanceof Class<?>)) {
            continue;
          }

          Class itemType = (Class<?>) itemType2;

          String description = resourceBundle.getString("config.description." + name);

          Object defaultValue = Configuration.getDefaultValue(field);
          if (name.equals("gui.skin")) {
            Class c;
            try {
              c = Class.forName((String) defaultValue);
              defaultValue = c.getField("NAME").get(c);
            } catch (ClassNotFoundException | NoSuchFieldException | SecurityException ex) {
              Logger.getLogger(AdvancedSettingsDialog.class.getName()).log(Level.SEVERE, null, ex);
            }
          }

          if (defaultValue != null) {
            description += " (" + resourceBundle.getString("default") + ": " + defaultValue + ")";
          }

          JLabel l = new JLabel(locName, JLabel.TRAILING);
          l.setToolTipText(description);
          configPanel.add(l);
          Component c = null;
          if (name.equals("gui.skin")) {
            skinComboBox.setToolTipText(description);
            skinComboBox.setMaximumSize(
                new Dimension(Integer.MAX_VALUE, skinComboBox.getPreferredSize().height));
            c = skinComboBox;
          } else if ((itemType == String.class)
              || (itemType == Integer.class)
              || (itemType == Long.class)
              || (itemType == Double.class)
              || (itemType == Float.class)
              || (itemType == Calendar.class)) {
            JTextField tf = new JTextField();
            Object val = item.get();
            if (val == null) {
              val = "";
            }
            if (itemType == Calendar.class) {
              tf.setText(new SimpleDateFormat().format(((Calendar) item.get()).getTime()));
            } else {
              tf.setText(val.toString());
            }
            tf.setToolTipText(description);
            tf.setMaximumSize(new Dimension(Integer.MAX_VALUE, tf.getPreferredSize().height));
            c = tf;
          } else if (itemType == Boolean.class) {
            JCheckBox cb = new JCheckBox();
            cb.setSelected((Boolean) item.get());
            cb.setToolTipText(description);
            c = cb;
          } else if (itemType.isEnum()) {
            JComboBox<String> cb = new JComboBox<>();
            @SuppressWarnings("unchecked")
            EnumSet enumValues = EnumSet.allOf(itemType);
            String stringValue = null;
            for (Object enumValue : enumValues) {
              String enumValueStr = enumValue.toString();
              if (stringValue == null) {
                stringValue = enumValueStr;
              }
              cb.addItem(enumValueStr);
            }
            if (item.get() != null) {
              stringValue = item.get().toString();
            }
            cb.setToolTipText(description);
            cb.setSelectedItem(stringValue);
            cb.setMaximumSize(new Dimension(Integer.MAX_VALUE, cb.getPreferredSize().height));
            c = cb;
          } else {
            throw new UnsupportedOperationException(
                "Configuration ttem type '" + itemType.getName() + "' is not supported");
          }

          componentsMap.put(name, c);
          l.setLabelFor(c);
          configPanel.add(c);
        } catch (IllegalArgumentException | IllegalAccessException ex) {
          // Reflection exceptions. This should never happen
          throw new Error(ex.getMessage());
        }

        itemCount++;
      }

      SpringUtilities.makeCompactGrid(
          configPanel,
          itemCount,
          2, // rows, cols
          6,
          6, // initX, initY
          6,
          6); // xPad, yPad
      tabs.put(cat, new JScrollPane(configPanel));
    }
  }