Example usage for java.lang Integer decode

List of usage examples for java.lang Integer decode

Introduction

In this page you can find the example usage for java.lang Integer decode.

Prototype

public static Integer decode(String nm) throws NumberFormatException 

Source Link

Document

Decodes a String into an Integer .

Usage

From source file:org.jbpm.formModeler.core.processing.formProcessing.Functions.java

public Map getValidDays(String sMonth, String sYear) {

    int month = Integer.decode(sMonth).intValue();
    int year = Integer.decode(sYear).intValue();
    GregorianCalendar gc = new GregorianCalendar(year, month, 1);

    Map days = new HashMap();

    while (gc.get(GregorianCalendar.MONTH) == month) {
        Integer value = new Integer(gc.get(GregorianCalendar.DAY_OF_MONTH));
        days.put(value, value.toString());
        gc.set(GregorianCalendar.DAY_OF_MONTH, value.intValue() + 1);
    }/*from   w  w w.  j  ava 2  s  . co m*/

    return days;
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.VersionRedirect.java

/**
 * Call this to rename the default version directory to its version file.
 *
 * @throws IOException//from www  . j  a  v  a  2s .co m
 */
public void updateVersion(String nnHostAddress, String userName) throws IOException {
    String[] nnHost = nnHostAddress.split(":");

    String uri = (path != null) ? path.getFullHdfsObjPath() : request.getPathInfo();

    String versionpath = replaceUri(uri, OBJECT_FILE_NAME, VERSION_FILE_NAME);

    GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
            "OPEN", userName, versionpath, GET);

    httpClient.executeMethod(httpGet);

    String version = readInputStream(httpGet.getResponseBodyAsStream());
    httpGet.releaseConnection();

    if (httpGet.getStatusCode() == 200) {
        String renameDst = replaceUri(uri, DEFAULT_VERSION + "/" + OBJECT_FILE_NAME, version);
        String renameSrc = replaceUri(uri, DEFAULT_VERSION + "/" + OBJECT_FILE_NAME, DEFAULT_VERSION);

        PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]),
                "RENAME&destination=" + renameDst, userName, renameSrc, PUT);

        httpClient.executeMethod(httpPut);
        httpPut.releaseConnection();

        assert httpPut.getStatusCode() == 200;
    }
}

From source file:com.l2jfree.gameserver.datatables.EnchantHPBonusData.java

private EnchantHPBonusData() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);/*from w  w  w .j ava  2  s.c  o  m*/
    factory.setIgnoringComments(true);
    File file = new File(Config.DATAPACK_ROOT, "data/enchantHPBonus.xml");
    Document doc = null;

    try {
        doc = factory.newDocumentBuilder().parse(file);
    } catch (Exception e) {
        _log.warn("", e);
        return;
    }

    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("enchantHP".equalsIgnoreCase(d.getNodeName())) {
                    NamedNodeMap attrs = d.getAttributes();
                    Node att;
                    boolean fullArmor;

                    att = attrs.getNamedItem("grade");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing grade, skipping");
                        continue;
                    }

                    int grade = Integer.parseInt(att.getNodeValue());

                    att = attrs.getNamedItem("fullArmor");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing fullArmor, skipping");
                        continue;
                    }
                    fullArmor = Boolean.valueOf(att.getNodeValue());

                    att = attrs.getNamedItem("values");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing bonus id: " + grade + ", skipping");
                        continue;
                    }
                    StringTokenizer st = new StringTokenizer(att.getNodeValue(), ",");
                    int tokenCount = st.countTokens();
                    Integer[] bonus = new Integer[tokenCount];
                    for (int i = 0; i < tokenCount; i++) {
                        Integer value = Integer.decode(st.nextToken().trim());
                        if (value == null) {
                            _log.warn("[EnchantHPBonusData] Bad Hp value!! grade: " + grade + " FullArmor? "
                                    + fullArmor + " token: " + i);
                            value = 0;
                        }
                        bonus[i] = value;
                    }
                    if (fullArmor)
                        _fullArmorHPBonus.set(grade, bonus);
                    else
                        _singleArmorHPBonus.set(grade, bonus);
                }
            }
        }
    }

    if (_fullArmorHPBonus.isEmpty() && _singleArmorHPBonus.isEmpty())
        return;

    int count = 0;

    for (L2Item item0 : ItemTable.getInstance().getAllTemplates()) {
        if (!(item0 instanceof L2Equip))
            continue;

        final L2Equip item = (L2Equip) item0;

        if (item.getCrystalType() == L2Item.CRYSTAL_NONE)
            continue;

        boolean shouldAdd = false;

        // normally for armors
        if (item instanceof L2Armor) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_CHEST:
            case L2Item.SLOT_FEET:
            case L2Item.SLOT_GLOVES:
            case L2Item.SLOT_HEAD:
            case L2Item.SLOT_LEGS:
            case L2Item.SLOT_BACK:
            case L2Item.SLOT_FULL_ARMOR:
            case L2Item.SLOT_UNDERWEAR:
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }
        // shields in the weapons table
        else if (item instanceof L2Weapon) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }

        if (shouldAdd) {
            count++;
            item.attach(new FuncTemplate(null, "EnchantHp", Stats.MAX_HP, 0x60, 0));
        }
    }

    _log.info("Enchant HP Bonus registered for " + count + " items!");
}

From source file:it.cilea.osd.jdyna.controller.DecoratorATypeNestedController.java

protected ModelAndView handleDelete(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    String paramOTipologiaProprietaId = request.getParameter("pDId");
    String boxId = request.getParameter("boxId");
    String tabId = request.getParameter("tabId");
    Integer tipologiaProprietaId = Integer.decode(paramOTipologiaProprietaId);

    try {//w ww .j  av a  2 s . c  o  m

        A tip = applicationService.get(targetModel, tipologiaProprietaId);

        applicationService.deleteNestedObjectByTypeID(objectModel, tipologiaProprietaId);

        IContainable containable = applicationService.findContainableByDecorable(tip.getDecoratorClass(),
                tipologiaProprietaId);
        applicationService.<H, T>deleteContainableInPropertyHolder(holderModel, containable);
        applicationService.delete(tip.getDecoratorClass(), containable.getId());

        saveMessage(request, getText("action.propertiesdefinition.deleted", request.getLocale()));
    } catch (Exception ecc) {
        saveMessage(request, getText("action.propertiesdefinition.deleted.noSuccess", request.getLocale()));
    }

    return new ModelAndView(getListView() + "?id=" + boxId + "&tabId=" + tabId + "&path="
            + Utils.getAdminSpecificPath(request, null), model);
}

From source file:com.chumbok.aauth.otp.TOTP.java

/**
 * This method generates a TOTP value for the given set of parameters.
 *
 * @param key//from  w  w  w .j a v a2  s  . c  om
 *            : the shared secret, HEX encoded
 * @param time
 *            : a value that reflects a time
 * @param returnDigits
 *            : number of digits to return
 * @param crypto
 *            : the crypto function to use
 *
 * @return: a numeric String in base 10 that includes
 *          {@link truncationDigits} digits
 */

public static String generateTOTP(String key, String time, String returnDigits, String crypto) {
    int codeDigits = Integer.decode(returnDigits).intValue();
    String result = null;

    // Using the counter
    // First 8 bytes are for the movingFactor
    // Compliant with base RFC 4226 (HOTP)
    while (time.length() < 16)
        time = "0" + time;

    // Get the HEX in a Byte[]
    byte[] msg = hexStr2Bytes(time);
    byte[] k = hexStr2Bytes(key);
    byte[] hash = hmac_sha(crypto, k, msg);

    // put selected bytes into result int
    int offset = hash[hash.length - 1] & 0xf;

    int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16)
            | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff);

    int otp = binary % DIGITS_POWER[codeDigits];

    result = Integer.toString(otp);
    while (result.length() < codeDigits) {
        result = "0" + result;
    }
    return result;
}

From source file:com.reddyetwo.hashmypass.app.AddProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_profile);

    // Setup action bar
    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }/* w  ww  .ja va  2 s  .co  m*/

    /* Get UI widgets */
    mNameEditText = (EditText) findViewById(R.id.profile_name_text);
    mPrivateKeyEditText = (EditText) findViewById(R.id.private_key_text);

    // Populating password length spinner is a bit more tricky
    // We have to restore its value from savedInstanceState...
    mPasswordLengthSpinner = (Spinner) findViewById(R.id.password_length_spinner);
    int passwordLength;
    if (savedInstanceState != null) {
        passwordLength = savedInstanceState.getInt(KEY_PASSWORD_LENGTH);
    } else {
        passwordLength = PasswordLength.DEFAULT;
    }
    ProfileFormInflater.populatePasswordLengthSpinner(this, mPasswordLengthSpinner, passwordLength);
    // Show number picker dialog when the spinner is touched
    mPasswordLengthSpinner
            .setOnTouchListener(new MovementTouchListener(this, new MovementTouchListener.OnPressedListener() {
                @Override
                public void onPressed() {
                    showDialog();
                }
            }));

    mPasswordTypeSpinner = (Spinner) findViewById(R.id.password_type_spinner);
    ProfileFormInflater.populatePasswordTypeSpinner(this, mPasswordTypeSpinner,
            PasswordType.ALPHANUMERIC_AND_SPECIAL_CHARS);

    Button addButton = (Button) findViewById(R.id.add_button);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Profile profile = new Profile(Profile.NO_ID, mNameEditText.getText().toString(),
                    mPrivateKeyEditText.getText().toString(),
                    Integer.decode((String) mPasswordLengthSpinner.getSelectedItem()),
                    PasswordType.values()[mPasswordTypeSpinner.getSelectedItemPosition()], mColor);
            long profileId = ProfileSettings.insertProfile(AddProfileActivity.this, profile);
            if (profileId == -1) {
                // Error!
                Toast.makeText(AddProfileActivity.this, R.string.error, Toast.LENGTH_LONG).show();
                setResult(RESULT_CANCELED);
            } else {
                Intent resultIntent = new Intent();
                resultIntent.putExtra(RESULT_KEY_PROFILE_ID, profileId);
                setResult(RESULT_OK, resultIntent);
            }

            // Navigate to previous activity
            NavUtils.navigateUpFromSameTask(AddProfileActivity.this);
        }
    });

    Button discardButton = (Button) findViewById(R.id.discard_button);
    discardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setResult(RESULT_CANCELED);

            // Navigate to previous activity
            NavUtils.navigateUpFromSameTask(AddProfileActivity.this);
        }
    });

    // Add form watcher for enabling/disabling Add button
    ProfileFormWatcher profileFormWatcher = new ProfileFormWatcher(getApplicationContext(), Profile.NO_ID,
            mNameEditText, mPrivateKeyEditText, addButton);
    mNameEditText.addTextChangedListener(profileFormWatcher);
    mPrivateKeyEditText.addTextChangedListener(profileFormWatcher);
    mPrivateKeyEditText.setText(RandomPrivateKeyGenerator.generate());

    mColorPaletteView = (ColorPaletteView) findViewById(R.id.profile_color);
    mColorPaletteView.setOnColorSelectedListener(new ColorPaletteView.OnColorSelectedListener() {
        @Override
        public void onColorSelected(ColorPaletteView source, int color) {
            mColor = color;
        }
    });
}

From source file:org.rti.zcore.dar.struts.action.HomeAction.java

/**
 * Build the ZEPRS home page, incorporating the search interface/results
 * if it's a report-only user, send to reports
 * otherwise, send to permissions page./*from w  w  w . j  av  a  2s.  c  om*/
 *
 * @param mapping  The ActionMapping used to select this instance
 * @param form     The optional ActionForm bean for this request (if any)
 * @param request  The HTTP request we are processing
 * @param response The HTTP response we are creating
 * @return Action to forward to
 * @throws Exception if an input/output error or servlet exception occurs
 */
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    HttpSession session = request.getSession();
    Principal user = request.getUserPrincipal();
    String username = user.getName();
    Integer maxRows = 0;
    Integer offset = 0;
    Integer prevRows = 0;
    Integer nextRows = 0;
    Connection conn = null;
    try {
        conn = DatabaseUtils.getZEPRSConnection(username);
        if (request.isUserInRole("VIEW_INDIVIDUAL_PATIENT_RECORDS")
                || request.isUserInRole("CREATE_NEW_PATIENTS_AND_SEARCH")) {
            String searchStringRequest = request.getParameter("search_string");
            String firstSurname = request.getParameter("first_surname"); // used in a-z search
            String labour = request.getParameter("labour"); // used in a-z search
            String searchType = "keyword";
            String searchString = "";
            if (searchStringRequest == null) {
                searchString = "";
            } else {
                searchString = searchStringRequest.trim().toLowerCase();
            }
            if (firstSurname != null && !firstSurname.equals("")) {
                searchType = "firstSurname";
                searchString = firstSurname;
                request.setAttribute("firstSurname", firstSurname);
            }
            request.setAttribute("searchString", searchString);
            String patientSiteId = SessionUtil.getInstance(session).getClientSettings().getSiteId().toString();
            request.setAttribute("patientSiteId", patientSiteId);

            String site = request.getParameter("site");
            request.setAttribute("site", site);
            if (site != null) {
                if (site.equals("")) {
                    site = patientSiteId;
                }
            }
            if (request.getParameter("maxRows") != null) {
                maxRows = Integer.decode(request.getParameter("maxRows"));
            } else if (request.getAttribute("maxRows") != null) {
                maxRows = Integer.decode(request.getAttribute("maxRows").toString());
            } else {
                maxRows = 20;
            }
            if (request.getParameter("offset") != null) {
                offset = Integer.decode(request.getParameter("offset"));
            } else if (request.getAttribute("offset") != null) {
                offset = Integer.decode(request.getAttribute("offset").toString());
            }
            if (request.getParameter("prevRows") != null) {
                prevRows = Integer.decode(request.getParameter("prevRows"));
                offset = prevRows;
            } else if (request.getAttribute("prevRows") != null) {
                prevRows = Integer.decode(request.getAttribute("prevRows").toString());
                offset = prevRows;
            }
            if (request.getParameter("nextRows") != null) {
                nextRows = Integer.decode(request.getParameter("nextRows"));
            } else if (request.getAttribute("nextRows") != null) {
                nextRows = Integer.decode(request.getAttribute("nextRows").toString());
            }
            if (site == null) {
                site = patientSiteId;
            }
            List results = null;
            results = PatientSearchDAO.getResults(conn, site, searchString, offset, maxRows, searchType, 0,
                    username);
            request.setAttribute("results", results);

            request.setAttribute("maxRows", maxRows);
            nextRows = offset + maxRows;
            if (results.size() < maxRows) {
                if (offset == 0) {
                    request.setAttribute("noNavigationWidget", "1");
                }
            } else {
                request.setAttribute("offset", nextRows);
            }

            if (offset - maxRows >= 0) {
                prevRows = offset - maxRows;
                request.setAttribute("prevRows", prevRows);
            }
            request.setAttribute("nextRows", nextRows);
            SessionUtil.getInstance(session).setSessionPatient(null);

            List sites = null;
            sites = DynaSiteObjects.getClinics();//
            request.setAttribute("sites", sites);

            if (SessionUtil.getInstance(request.getSession()).isClientConfigured()) {
                String sitename = SessionUtil.getInstance(session).getClientSettings().getSite().getName();
                request.setAttribute("sitename", sitename);
            } else {
                request.setAttribute("sitename", "Configure PC: ");
            }
            String fullname = null;
            try {
                fullname = SessionUtil.getInstance(session).getFullname();
            } catch (SessionUtil.AttributeNotFoundException e) {
                // ok
            }
            //List activeProblems = PatientRecordUtils.assembleProblemTaskList(conn);
            //List<Task> stockAlertList = PatientRecordUtils.getStockAlerts();
            List<Task> stockAlertList = null;
            if (DynaSiteObjects.getStatusMap().get("stockAlertList") != null) {
                stockAlertList = (List<Task>) DynaSiteObjects.getStatusMap().get("stockAlertList");
            }
            request.setAttribute("activeProblems", stockAlertList);
            request.setAttribute("fullname", fullname);
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("success");
        } else if (request.isUserInRole("VIEW_SELECTED_REPORTS_AND_VIEW_STATISTICAL_SUMMARIES")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }
            return mapping.findForward("reports");
        } else if (request.isUserInRole("CREATE_MEDICAL_STAFF_IDS_AND_PASSWORDS_FOR_MEDICAL_STAFF")) {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                conn = null;
            }

            // Create user accounts
            ActionForward fwd = mapping.findForward("admin/records/list");
            String path = fwd.getPath();
            path += "?formId=";
            path += "170";
            return new ActionForward(path);
        }
    } catch (ServletException e) {
        log.error(e);
        request.setAttribute("exception",
                "There is an error generating the Search Results for the Home page. Please stand by - the system may be undergoing maintenance.");
        return mapping.findForward("error");
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
            conn = null;
        }

    }

    return mapping.findForward("noPermissions");
}

From source file:com.l2jfree.gameserver.document.DocumentBase.java

final void attachFunc(Node n, Object template, String name) {
    final NamedNodeMap attrs = n.getAttributes();

    final Stats stat = Stats.valueOfXml(attrs.getNamedItem("stat").getNodeValue());
    final int ord = Integer.decode(attrs.getNamedItem("order").getNodeValue());
    final double lambda = getLambda(n, template);

    final Condition applayCond = parseConditionIfExists(n.getFirstChild(), template);

    final FuncTemplate ft = new FuncTemplate(applayCond, name, stat, ord, lambda);

    if (template instanceof L2Equip)
        ((L2Equip) template).attach(ft);

    else if (template instanceof L2Skill)
        ((L2Skill) template).attach(ft);

    else if (template instanceof EffectTemplate)
        ((EffectTemplate) template).attach(ft);

    else// w  w w. j a  va2  s  . c om
        throw new IllegalStateException("Invalid template for a Func");
}

From source file:com.mcreations.usb.windows.WindowsUsbServices.java

/** Set variables from user-specified properties */
private void checkProperties() {
    Properties p = null;//from   w w w . jav a 2s.c om

    try {
        p = UsbHostManager.getProperties();
    } catch (Exception e) {
        return;
    }

    try {
        if (p.containsKey(TOPOLOGY_UPDATE_DELAY_KEY))
            topologyUpdateDelay = Integer.decode(p.getProperty(TOPOLOGY_UPDATE_DELAY_KEY)).intValue();
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TOPOLOGY_UPDATE_NEW_DEVICE_DELAY_KEY))
            topologyUpdateNewDeviceDelay = Integer.decode(p.getProperty(TOPOLOGY_UPDATE_NEW_DEVICE_DELAY_KEY))
                    .intValue();
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TOPOLOGY_UPDATE_USE_POLLING_KEY))
            topologyUpdateUsePolling = Boolean.valueOf(p.getProperty(TOPOLOGY_UPDATE_USE_POLLING_KEY))
                    .booleanValue();
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TRACING_KEY))
            JavaxUsb.setTracing(Boolean.valueOf(p.getProperty(TRACING_KEY)).booleanValue());
    } catch (Exception e) {
    }

    //FIXME - the names of the tracers should be more generically processed
    try {
        if (p.containsKey(TRACE_DEFAULT_KEY))
            JavaxUsb.setTraceType(Boolean.valueOf(p.getProperty(TRACE_DEFAULT_KEY)).booleanValue(), "default");
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TRACE_HOTPLUG_KEY))
            JavaxUsb.setTraceType(Boolean.valueOf(p.getProperty(TRACE_HOTPLUG_KEY)).booleanValue(), "hotplug");
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TRACE_XFER_KEY))
            JavaxUsb.setTraceType(Boolean.valueOf(p.getProperty(TRACE_XFER_KEY)).booleanValue(), "xfer");
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TRACE_URB_KEY))
            JavaxUsb.setTraceType(Boolean.valueOf(p.getProperty(TRACE_URB_KEY)).booleanValue(), "urb");
    } catch (Exception e) {
    }

    try {
        if (p.containsKey(TRACE_LEVEL_KEY))
            JavaxUsb.setTraceLevel(Integer.decode(p.getProperty(TRACE_LEVEL_KEY)).intValue());
    } catch (Exception e) {
    }
}

From source file:org.ohmage.prompt.multichoicecustom.MultiChoiceCustomPrompt.java

@Override
protected Object getTypeSpecificExtrasObject() {
    JSONArray jsonArray = new JSONArray();
    for (KVLTriplet choice : mChoices) {
        JSONObject jsonChoice = new JSONObject();
        try {//from www .  j av a 2  s. c  o  m
            jsonChoice.put("choice_id", Integer.decode(choice.key));
            jsonChoice.put("choice_value", choice.label);
        } catch (NumberFormatException e) {
            Log.e(TAG, "NumberFormatException when trying to parse custom choice key", e);
            return null;
        } catch (JSONException e) {
            Log.e(TAG, "JSONException when trying to generate custom_choices json", e);
            return null;
        }
        jsonArray.put(jsonChoice);
    }
    for (KVLTriplet choice : mCustomChoices) {
        JSONObject jsonChoice = new JSONObject();
        try {
            jsonChoice.put("choice_id", Integer.decode(choice.key));
            jsonChoice.put("choice_value", choice.label);
        } catch (NumberFormatException e) {
            Log.e(TAG, "NumberFormatException when trying to parse custom choice key", e);
            return null;
        } catch (JSONException e) {
            Log.e(TAG, "JSONException when trying to generate custom_choices json", e);
            return null;
        }
        jsonArray.put(jsonChoice);
    }
    return jsonArray;
}