Esempio n. 1
0
  /**
   * Returns Last Numbers Dialed in human readable interpretation.
   *
   * @param position Entry position of LND that is to be read.
   * @param showAllHex if true, returns HEX representation of data. If false, returns normal
   *     representation of data.
   * @return Last Numbers Dialed in human readable interpretation.
   */
  public String getLNDString(int position, boolean showAllHex) {
    byte[] LND = null;
    String LNDString = "";
    String contactName = "";
    try {
      worker.getResponse(worker.select(DatabaseOfEF.DF_TELECOM.getFID()));
      LND =
          worker.readRecord(
              position, worker.getResponse(worker.select(DatabaseOfEF.EF_LND.getFID())));

      contactName =
          contactName.concat(Converter.bytesToHex(LND).substring(0, 3 * (LND.length - 14)));
      if (!contactName.matches("[FF ]+")) {
        for (int i = 0; i < LND.length - 14; i++) {
          LNDString = LNDString.concat(Character.toString((char) (int) LND[i]));
        }
        LNDString = LNDString.concat("; ");
      }
      if (LND[LND.length - 14 + 1] == (byte) 0x91) {
        LNDString = LNDString.concat("00");
      }
      for (int i = LND.length - 14 + 2; i <= LND.length - 14 + LND[LND.length - 14]; i++) {
        String b = Converter.byteToHex(LND[i]);
        String c = Converter.swapString(b);
        LNDString = LNDString.concat(c);
      }
    } catch (Exception ex) {
      Logger.getLogger(CardManager.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (showAllHex) {
      return Converter.bytesToHex(LND);
    } else {
      return LNDString;
    }
  }
Esempio n. 2
0
  public static void main(String[] args) {

    String rate =
        JOptionPane.showInputDialog(
            null, "Please a desired exchange rate between Dollars(US) and Euros: ");

    double userRate = Double.parseDouble(rate);

    Converter userConverter = new Converter(userRate);

    boolean completed = false;
    while (!completed) {
      String input =
          JOptionPane.showInputDialog(
              null, "Please enter the amount in US$ to be converted (Q to quit): ");

      if (input.equalsIgnoreCase("Q")) completed = true;
      else {
        double amount = Double.parseDouble(input);

        if (amount > 0) {
          double Coinexchange = userConverter.convert(amount);
          JOptionPane.showMessageDialog(
              null, "The conversion to Euro is: " + Coinexchange + " Euro");
        } else completed = true;
      }
    }
  }
Esempio n. 3
0
  public static void writeModules(String filename) {
    Data data = makeHDF();

    int i = 0;
    for (PackageInfo pkg : chooseModulePackages()) {

      data.setValue("reference", "1");
      data.setValue("reference.apilevels", sinceTagger.hasVersions() ? "1" : "0");
      data.setValue("docs.packages." + i + ".name", pkg.name());
      makeModuleListHDF(data, "docs.packages." + i + ".modules", pkg.modules());

      for (int j = 0; j < pkg.modules().length; j++) {
        Data classData = makeHDF();
        ClassInfo mod = pkg.modules()[j];
        writeModule(mod, classData);
      }

      i++;
    }

    setPageTitle(data, "Module Index");

    TagInfo.makeHDF(data, "root.descr", Converter.convertTags(root.inlineTags(), null));

    ClearPage.write(data, "modules.cs", filename);

    Proofread.writePackages(filename, Converter.convertTags(root.inlineTags(), null));
  }
Esempio n. 4
0
 public static void main(String[] args)
     throws ClassNotFoundException, IllegalAccessException, NoSuchMethodException,
         InvocationTargetException, IOException {
   MyClass mc = new MyClass();
   Converter converter = new Converter();
   converter.convert(mc.getClass(), mc);
 }
Esempio n. 5
0
  /**
   * @param args
   * @throws GeneralSecurityException
   * @throws IOException
   */
  public static void main(String[] args) throws GeneralSecurityException, IOException {

    final String rpcuser = "******"; // RPC User name (set in config)
    final String rpcpassword = "******"; // RPC Pass (set in config)

    Authenticator.setDefault(
        new Authenticator() { // This sets the default authenticator, with the set username and
          // password
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(rpcuser, rpcpassword.toCharArray());
          }
        });

    while (true) {
      Work work = getwork(); // Gets the work from the server
      String data = work.result.data; // Gets the data to hash from the work
      String target = work.result.target; // Gets the target from the work
      String realdata = data.substring(0, 160);
      byte[] databyte = endianSwitch(Converter.fromHexString(realdata));

      // Converts the target string to a byte array for easier comparison
      byte[] targetbyte = Converter.fromHexString(target);
      System.out.println(printByteArray(targetbyte));
      if (doScrypt(
          databyte,
          targetbyte)) { // Calls sCrypt with the proper parameters, and returns the correct data
        work.result.data = printByteArray(endianSwitch(databyte)) + data.substring(160, 256);
        System.out.println(sendWork(work)); // Send the work
      }
    }
  }
 @Test
 public void fromAndTo() throws Exception {
   assertEquals((Integer) 1, converter.fromString("a"));
   assertEquals((Integer) 2, converter.fromString("b"));
   assertEquals("a", converter.toString(1));
   assertEquals("b", converter.toString(2));
 }
Esempio n. 7
0
 public void pack() throws IrregularStringOfBitsException {
   // conversion of instruction parameters of "params" list to the "repr" form (32 binary value)
   repr.setBits(OPCODE_VALUE, OPCODE_VALUE_INIT);
   repr.setBits(Converter.intToBin(SA_FIELD_LENGTH, params.get(SA_FIELD)), SA_FIELD_INIT);
   repr.setBits(Converter.intToBin(RT_FIELD_LENGTH, params.get(RT_FIELD)), RT_FIELD_INIT);
   repr.setBits(Converter.intToBin(RD_FIELD_LENGTH, params.get(RD_FIELD)), RD_FIELD_INIT);
 }
Esempio n. 8
0
 /**
  * Convert the specified value to an object of the specified class (if possible). Otherwise,
  * return a String representation of the value.
  *
  * @param value Value to be converted (may be null)
  * @param clazz Java class to be converted to
  * @return The converted value
  * @exception ConversionException if thrown by an underlying Converter
  */
 public Object convert(final String value, final Class<?> clazz) {
   Converter converter = this.lookup(clazz);
   if (converter == null) {
     converter = this.lookup(String.class);
   }
   return converter.convert(clazz, value);
 }
Esempio n. 9
0
 @Test
 public void parseItemsGet() throws Exception {
   Converter jc = new JsonConverter();
   String json = TestUtils.readResource("items.json");
   PageList<Item> rsp = jc.toResponseList(json, Item.class, "taobao.items.get");
   Assert.assertEquals(new Long(277L), rsp.getTotalResults());
 }
Esempio n. 10
0
 @Test
 public void parseUserGet() throws Exception {
   Converter jc = new JsonConverter();
   String json = TestUtils.readResource("user.json");
   User user = jc.toResponse(json, User.class, "taobao.user.get");
   Assert.assertEquals("hz0799", user.getNick());
 }
Esempio n. 11
0
 public void testStringConverter_convertError() {
   Converter<String, TestEnum> converter = Enums.stringConverter(TestEnum.class);
   try {
     converter.convert("xxx");
     fail();
   } catch (IllegalArgumentException expected) {
   }
 }
Esempio n. 12
0
 @Test
 public void parseTradesSoldGet() throws Exception {
   Converter jc = new JsonConverter();
   String json = TestUtils.readResource("trades.json");
   PageList<Trade> rsp = jc.toResponseList(json, Trade.class, "taobao.trades.sold.get");
   Assert.assertEquals(new Long(897L), rsp.getTotalResults());
   Assert.assertEquals(2, rsp.getContent().size());
 }
Esempio n. 13
0
 /**
  * Registers converters mapping them to their corresponding parameterized type.
  *
  * @param converter
  * @return a reference to this builder.
  */
 public GensonBuilder withConverters(Converter<?>... converter) {
   for (Converter<?> c : converter) {
     Type typeOfConverter =
         TypeUtil.typeOf(0, TypeUtil.lookupGenericType(Converter.class, c.getClass()));
     typeOfConverter = TypeUtil.expandType(typeOfConverter, c.getClass());
     registerConverter(c, typeOfConverter);
   }
   return this;
 }
Esempio n. 14
0
 public boolean addAt(int index, Object e) {
   if (index < 0) index = size();
   while (index > size()) {
     if (!add(Converter.convert(null, type))) return false;
   }
   if (type != null) e = Converter.convert(e, type);
   super.add(index, e);
   return true;
 }
Esempio n. 15
0
 private Object convert(Object value, Class dest) {
   for (Converter c : converters) {
     if (c.getTarget().isAssignableFrom(dest)) {
       return c.convert(value);
     }
   }
   throw new RuntimeException(
       "No converters are compatible with the dest class: " + dest.getCanonicalName());
 }
Esempio n. 16
0
  void readThis() throws OldFormatException {
    newSystemData(AbstractFreespaceManager.FM_LEGACY_RAM, StandardIdSystemFactory.LEGACY);
    blockSizeReadFromFile(1);

    _fileHeader = FileHeader.read(this);

    if (config().generateCommitTimestamps().isUnspecified()) {
      config().generateCommitTimestamps(_systemData.idToTimestampIndexId() != 0);
    }

    createStringIO(_systemData.stringEncoding());

    createIdSystem();

    initializeClassMetadataRepository();
    initalizeWeakReferenceSupport();

    setNextTimeStampId(systemData().lastTimeStampID());

    classCollection().setID(_systemData.classCollectionID());
    classCollection().read(systemTransaction());

    Converter.convert(new ConversionStage.ClassCollectionAvailableStage(this));

    _fileHeader.readIdentity(this);

    if (_config.isReadOnly()) {
      return;
    }

    if (!configImpl().commitRecoveryDisabled()) {
      _fileHeader.completeInterruptedTransaction(this);
    }

    FreespaceManager blockedFreespaceManager =
        AbstractFreespaceManager.createNew(this, _systemData.freespaceSystem());

    installFreespaceManager(blockedFreespaceManager);

    blockedFreespaceManager.read(this, _systemData.inMemoryFreespaceSlot());
    blockedFreespaceManager.start(_systemData.bTreeFreespaceId());

    _fileHeader = _fileHeader.convert(this);

    if (freespaceMigrationRequired(blockedFreespaceManager)) {
      migrateFreespace(blockedFreespaceManager);
    }

    writeHeader(true, false);

    if (Converter.convert(new ConversionStage.SystemUpStage(this))) {
      _systemData.converterVersion(Converter.VERSION);
      _fileHeader.writeVariablePart(this);
      transaction().commit();
    }
  }
Esempio n. 17
0
 /**
  * Returns an appropriate <code>Converter</code> instance for <code>sourceClass</code> and <code>
  * targetClass</code>. If no matching <code>Converter</code> is found, the method throws <code>
  * ClassNotFoundException</code>.
  *
  * <p>This method is intended to be used when the source or target <code>Object</code> types are
  * unknown at compile time. If the source and target <code>Object</code> types are known at
  * compile time, then one of the "ready made" converters should be used.
  *
  * @param sourceClass The object class to convert from
  * @param targetClass The object class to convert to
  * @return A matching <code>Converter</code> instance
  * @throws ClassNotFoundException
  */
 public static <S, T> Converter<S, T> getConverter(Class<S> sourceClass, Class<T> targetClass)
     throws ClassNotFoundException {
   String key = sourceClass.getName().concat(DELIMITER).concat(targetClass.getName());
   if (Debug.verboseOn()) {
     Debug.logVerbose("Getting converter: " + key, module);
   }
   OUTER:
   do {
     Converter<?, ?> result = converterMap.get(key);
     if (result != null) {
       return UtilGenerics.cast(result);
     }
     if (noConversions.contains(key)) {
       throw new ClassNotFoundException("No converter found for " + key);
     }
     Class<?> foundSourceClass = null;
     Converter<?, ?> foundConverter = null;
     for (Converter<?, ?> value : converterMap.values()) {
       if (value.canConvert(sourceClass, targetClass)) {
         // this converter can deal with the source/target pair
         if (foundSourceClass == null
             || foundSourceClass.isAssignableFrom(value.getSourceClass())) {
           // remember the current target source class; if we find another converter, check
           // to see if it's source class is assignable to this one, and if so, it means it's
           // a child class, so we'll then take that converter.
           foundSourceClass = value.getSourceClass();
           foundConverter = value;
         }
       }
     }
     if (foundConverter != null) {
       converterMap.putIfAbsent(key, foundConverter);
       continue OUTER;
     }
     for (ConverterCreator value : creators) {
       result = createConverter(value, sourceClass, targetClass);
       if (result != null) {
         converterMap.putIfAbsent(key, result);
         continue OUTER;
       }
     }
     if (noConversions.add(key)) {
       Debug.logWarning(
           "*** No converter found, converting from "
               + sourceClass.getName()
               + " to "
               + targetClass.getName()
               + ". Please report this message to the developer community so "
               + "a suitable converter can be created. ***",
           module);
     }
     throw new ClassNotFoundException("No converter found for " + key);
   } while (true);
 }
Esempio n. 18
0
  /**
   * Returns International Mobile Subscriber Identity (IMSI) as IMSI class.
   *
   * @return International Mobile Subscriber Identity (IMSI) as IMSI class.
   */
  public IMSI getIMSI() {
    byte[] input = getEFBytes(DatabaseOfEF.EF_IMSI);
    String IMSIString = "";

    for (int i = 0; i < input.length - 2; i++) {
      String b = Converter.byteToHex(input[i]);
      String c = Converter.swapString(b);
      IMSIString = IMSIString.concat(c);
    }

    return new IMSI(IMSIString);
  }
Esempio n. 19
0
 private Value read(Type type, NodeMap nodemap, Value value) throws Exception {
   Converter converter = lookup(type, value);
   nodemap = (InputNode) nodemap.getNode();
   type = value;
   if (converter != null) {
     type = ((Type) (converter.read(nodemap)));
     if (value != null) {
       value.setValue(type);
     }
     type = new Reference(value, type);
   }
   return type;
 }
Esempio n. 20
0
  private static NCube checkForConflicts(
      ApplicationID appId,
      Map<String, Map> errors,
      String message,
      NCubeInfoDto info,
      NCubeInfoDto head,
      boolean reverse) {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("message", message);
    map.put("sha1", info.sha1);
    map.put("headSha1", head != null ? head.sha1 : null);

    try {
      if (head != null) {
        long branchCubeId = (long) Converter.convert(info.id, long.class);
        long headCubeId = (long) Converter.convert(head.id, long.class);
        NCube branchCube = getPersister().loadCubeById(branchCubeId);
        NCube headCube = getPersister().loadCubeById(headCubeId);

        if (info.headSha1 != null) {
          NCube baseCube = getPersister().loadCubeBySha1(appId, info.name, info.headSha1);

          Map delta1 = baseCube.getDelta(branchCube);
          Map delta2 = baseCube.getDelta(headCube);

          if (NCube.areDeltaSetsCompatible(delta1, delta2)) {
            if (reverse) {
              headCube.mergeCellChangeSet(delta1);
              return headCube;
            } else {
              branchCube.mergeCellChangeSet(delta2);
              return branchCube;
            }
          }
        }

        List<Delta> diff = branchCube.getDeltaDescription(headCube);
        if (diff.size() > 0) {
          map.put("diff", diff);
        } else {
          return branchCube;
        }
      } else {
        map.put("diff", null);
      }
    } catch (Exception e) {
      map.put("diff", e.getMessage());
    }
    errors.put(info.name, map);
    return null;
  }
Esempio n. 21
0
  /**
   * Returns Integrated Circuit Card Identification as ICCID class.
   *
   * @return Returns Integrated Circuit Card Identification as ICCID class.
   */
  public ICCID getICCID() {
    byte[] input = getEFBytes(DatabaseOfEF.EF_ICCID);
    String ICCIDString = "";
    for (int i = 0; i < input.length - 2; i++) {
      String b = Converter.byteToHex(input[i]);
      String c = Converter.swapString(b);
      ICCIDString = ICCIDString.concat(c);
    }

    if (ICCIDString.toUpperCase().contains("F")) {
      ICCIDString = ICCIDString.substring(0, ICCIDString.length() - 1);
    }
    return new ICCID(ICCIDString);
  }
Esempio n. 22
0
 @SuppressWarnings({"unchecked", "rawtypes"})
 private void truncate(Trace<?> dest, Trace<?> orig) throws IOException {
   long min_time = minTime * orig.ticsPerSecond();
   long max_time = maxTime * orig.ticsPerSecond();
   Converter truncater;
   if (orig.isStateful()) {
     truncater =
         new StatefulSubtraceConverter(
             (StatefulTrace<?, ?>) dest, (StatefulTrace<?, ?>) orig, min_time, max_time);
   } else {
     truncater = new SubtraceConverter(dest, orig, min_time, max_time);
   }
   truncater.convert();
 }
 @Override
 @SuppressWarnings("unchecked")
 public Object get(String name, Scriptable start) {
   if (PatchRequest.FIELD_PATCH_OPERATIONS.equals(name)) {
     final JsonValue value = new JsonValue(new ArrayList<Object>());
     for (final PatchOperation operation : request.getPatchOperations()) {
       value.add(operation.toJsonValue().getObject());
     }
     return Converter.wrap(parameter, value, start, false);
   } else if (PatchRequest.FIELD_REVISION.equals(name)) {
     return Converter.wrap(parameter, request.getRevision(), start, false);
   } else {
     return super.get(name, start);
   }
 }
Esempio n. 24
0
 /**
  * Convert an array of specified values to an array of objects of the specified class (if
  * possible). If the specified Java class is itself an array class, this class will be the type of
  * the returned value. Otherwise, an array will be constructed whose component type is the
  * specified class.
  *
  * @param values Array of values to be converted
  * @param clazz Java array or element class to be converted to
  * @return The converted value
  * @exception ConversionException if thrown by an underlying Converter
  */
 public Object convert(final String[] values, final Class<?> clazz) {
   Class<?> type = clazz;
   if (clazz.isArray()) {
     type = clazz.getComponentType();
   }
   Converter converter = this.lookup(type);
   if (converter == null) {
     converter = this.lookup(String.class);
   }
   Object array = Array.newInstance(type, values.length);
   for (int i = 0; i < values.length; i++) {
     Array.set(array, i, converter.convert(type, values[i]));
   }
   return array;
 }
Esempio n. 25
0
  @Inject
  public void prepare(ConverterRegistry registry, TypeConverter delegate) {
    this.registry = registry;
    this.delegate = delegate;

    Collection<Converter<?, ?>> converters = registry.getConvertersBySource().values();
    for (Converter<?, ?> converter : converters) {
      ParameterizedType converterType =
          (ParameterizedType) Generics.getExactSuperType(converter.getClass(), Converter.class);

      Type[] converterParameters = converterType.getActualTypeArguments();
      registerMvelHandler(converterParameters[0]);
      registerMvelHandler(converterParameters[1]);
    }
  }
Esempio n. 26
0
  public static <V, T> T convert(V value, Class<T> type) {
    Map<Object, Object> typeConverters = converters.get(value.getClass());

    if (typeConverters == null) {
      throw new NoSuchElementException("No converters from type " + value.getClass());
    }

    Converter converter = (Converter) typeConverters.get(type);

    if (converter == null) {
      throw new NoSuchElementException("No converter to type " + type);
    }

    return (T) converter.convert(value);
  }
Esempio n. 27
0
  public static PackageInfo[] chooseModulePackages() {
    ClassInfo[] classes = Converter.rootClasses();
    SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
    for (ClassInfo cl : classes) {
      if (!cl.isModule()) {
        continue;
      }

      PackageInfo pkg = cl.containingPackage();
      String name;
      if (pkg == null) {
        name = "";
      } else {
        name = pkg.name();
      }
      sorted.put(name, pkg);
    }

    ArrayList<PackageInfo> result = new ArrayList<PackageInfo>();

    for (String s : sorted.keySet()) {
      PackageInfo pkg = sorted.get(s);

      result.add(pkg);
    }

    return result.toArray(new PackageInfo[result.size()]);
  }
Esempio n. 28
0
  /**
   * Writes the list of classes that must be present in order to provide the non-hidden APIs known
   * to javadoc.
   *
   * @param filename the path to the file to write the list to
   */
  public static void writeKeepList(String filename) {
    HashSet<ClassInfo> notStrippable = new HashSet<ClassInfo>();
    ClassInfo[] all = Converter.allClasses();
    Arrays.sort(all); // just to make the file a little more readable

    // If a class is public and not hidden, then it and everything it derives
    // from cannot be stripped. Otherwise we can strip it.
    for (ClassInfo cl : all) {
      if (cl.isPublic() && !cl.isHidden()) {
        cantStripThis(cl, notStrippable);
      }
    }
    PrintStream stream = null;
    try {
      stream = new PrintStream(filename);
      for (ClassInfo cl : notStrippable) {
        stream.println(getPrintableName(cl));
      }
    } catch (FileNotFoundException e) {
      System.err.println("error writing file: " + filename);
    } finally {
      if (stream != null) {
        stream.close();
      }
    }
  }
Esempio n. 29
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
Esempio n. 30
0
 /**
  * Sets the receiver's text. The string may include the mnemonic character.
  *
  * <p>Mnemonics are indicated by an '&amp;' that causes the next character to be the mnemonic.
  * When the user presses a key sequence that matches the mnemonic, a selection event occurs. On
  * most platforms, the mnemonic appears underlined but may be emphasised in a platform specific
  * manner. The mnemonic indicator character '&amp;' can be escaped by doubling it in the string,
  * causing a single '&amp;' to be displayed.
  *
  * @param string the new text
  * @exception IllegalArgumentException
  *     <ul>
  *       <li>ERROR_NULL_ARGUMENT - if the text is null
  *     </ul>
  *
  * @exception SWTException
  *     <ul>
  *       <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed
  *       <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver
  *     </ul>
  */
 public void setText(String string) {
   checkWidget();
   if (string == null) error(SWT.ERROR_NULL_ARGUMENT);
   if ((style & SWT.SEPARATOR) != 0) return;
   if (string.equals(this.text)) return;
   super.setText(string);
   if (labelHandle == 0) return;
   char[] chars = fixMnemonic(string);
   byte[] buffer = Converter.wcsToMbcs(null, chars, true);
   OS.gtk_label_set_text_with_mnemonic(labelHandle, buffer);
   if ((style & SWT.DROP_DOWN) != 0 && OS.GTK_VERSION < OS.VERSION(2, 6, 0)) {
     if (string.length() != 0) {
       OS.gtk_widget_show(labelHandle);
     } else {
       OS.gtk_widget_hide(labelHandle);
     }
   }
   /*
    * If Text/Image of a tool-item changes, then it is
    * required to reset the proxy menu. Otherwise, the
    * old menuItem appears in the overflow menu.
    */
   if ((style & SWT.DROP_DOWN) != 0) {
     proxyMenuItem = 0;
     proxyMenuItem = OS.gtk_tool_item_retrieve_proxy_menu_item(handle);
     OS.g_signal_connect(
         proxyMenuItem, OS.activate, ToolBar.menuItemSelectedFunc.getAddress(), handle);
   }
   parent.relayout();
 }