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.kchine.rpf.reg.ServantProviderFactoryReg.java

public ServantProviderFactoryReg() {

    if (System.getProperty("pools.regmode.configuration.file") != null
            && !System.getProperty("pools.regmode.configuration.file").equals("")) {
        try {//  ww  w .j av a  2  s .  c o  m
            initPoolsHashMap(new FileInputStream(System.getProperty("pools.regmode.configuration.file")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (System.getProperty("pools.regmode.configuration.resource") != null
            && !System.getProperty("pools.regmode.configuration.resource").equals("")) {
        try {
            initPoolsHashMap(this.getClass()
                    .getResourceAsStream(System.getProperty("pools.regmode.configuration.resource")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        String poolPrefix = ServerDefaults._servantPoolPrefix;
        String registryHost = ServerDefaults._registryHost;
        int registryPort = ServerDefaults._registryPort;

        int timeOutMillisec = System.getProperty("timeout") != null && !System.getProperty("timeout").equals("")
                ? Integer.decode(System.getProperty("timeout"))
                : DEFAULT_TIMEOUT;

        _defaultPoolName = "DEFAULT";
        PoolData poolData = new PoolData(_defaultPoolName, timeOutMillisec, new Vector<PoolNode>());
        poolData.getNodes().add(new PoolNode(poolPrefix, registryHost, registryPort));
        _poolHashMap.put(poolData.getPoolName(), poolData);

        try {
            _rmiRegistry = LocateRegistry.getRegistry(registryHost, registryPort);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    System.out.println(_poolHashMap);

    _servantProvider = new ServantProvider() {

        public ManagedServant borrowServantProxy(String poolName) throws TimeoutException {
            ManagedServant proxy = null;
            int nodesSize = _poolHashMap.get(poolName).getNodes().size();
            Vector<Integer> order = PoolUtils.getRandomOrder(nodesSize);
            int nodeIndex = 0;
            PoolNode node = null;
            long tstart = System.currentTimeMillis();
            do {
                try {
                    node = _poolHashMap.get(poolName).getNodes().elementAt(order.elementAt(nodeIndex));
                    proxy = (ManagedServant) ServantProxyPoolSingletonReg.getInstance(node.getRegistryHost(),
                            node.getRegistryPort(), node.getServantPoolPrefix()).borrowObject();
                } catch (NoSuchElementException e) {
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                if (proxy != null) {
                    try {
                        log.info("<" + Thread.currentThread().getName() + "> obtained resource : "
                                + proxy.getServantName());
                    } catch (Exception e) {
                    }
                    break;
                } else {
                    nodeIndex = (nodeIndex + 1) % nodesSize;
                }

                if (System.currentTimeMillis() - tstart > _poolHashMap.get(poolName).getBorrowTimeout())
                    throw new TimeoutException();
                try {
                    Thread.sleep(20);
                } catch (Exception e) {
                }

                log.info("<" + Thread.currentThread().getName() + "> thread waiting for resource for  : "
                        + ((System.currentTimeMillis() - tstart) / 1000) + " seconds");

            } while (true);

            _borrowedServants.put(proxy, node);
            return proxy;
        }

        public ManagedServant borrowServantProxyNoWait(String poolName) {
            ManagedServant proxy = null;
            int nodesSize = _poolHashMap.get(poolName).getNodes().size();
            Vector<Integer> order = PoolUtils.getRandomOrder(nodesSize);
            int nodeIndex = 0;
            PoolNode node = null;
            do {
                try {
                    node = _poolHashMap.get(poolName).getNodes().elementAt(order.elementAt(nodeIndex));
                    proxy = (ManagedServant) ServantProxyPoolSingletonReg.getInstance(node.getRegistryHost(),
                            node.getRegistryPort(), node.getServantPoolPrefix()).borrowObject();
                } catch (NoSuchElementException e) {
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                if (proxy != null) {
                    try {
                        log.info("<" + Thread.currentThread().getName() + "> obtained resource : "
                                + proxy.getServantName());
                    } catch (Exception e) {
                    }
                    break;
                } else {
                    nodeIndex = (nodeIndex + 1);
                    if (nodeIndex >= nodesSize)
                        break;
                }

            } while (true);

            if (proxy != null)
                _borrowedServants.put(proxy, node);
            return proxy;
        }

        public void returnServantProxy(ManagedServant proxy) {
            if (proxy == null)
                return;
            try {
                PoolNode node = _borrowedServants.get(proxy);
                _borrowedServants.remove(proxy);
                ServantProxyPoolSingletonReg.getInstance(node.getRegistryHost(), node.getRegistryPort(),
                        node.getServantPoolPrefix()).returnObject(proxy);
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(0);
            }
        }

        public void returnServantProxy(String poolName, ManagedServant proxy) {
            if (proxy == null)
                return;
            try {
                PoolNode node = _borrowedServants.get(proxy);
                _borrowedServants.remove(proxy);
                ServantProxyPoolSingletonReg.getInstance(node.getRegistryHost(), node.getRegistryPort(),
                        node.getServantPoolPrefix()).returnObject(proxy);
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(0);
            }
        }

        public ManagedServant borrowServantProxy() throws TimeoutException {
            return borrowServantProxy(_defaultPoolName);
        }

        public ManagedServant borrowServantProxyNoWait() {
            return borrowServantProxyNoWait(_defaultPoolName);
        }

        public String getDefaultPoolName() {
            return _defaultPoolName;
        }

        public Registry getRegistry() {
            return _rmiRegistry;
        }

    };

}

From source file:gobblin.tunnel.ConnectProxyServer.java

@Override
void handleClientSocket(Socket clientSocket) throws IOException {
    final InputStream clientToProxyIn = clientSocket.getInputStream();
    BufferedReader clientToProxyReader = new BufferedReader(new InputStreamReader(clientToProxyIn));
    final OutputStream clientToProxyOut = clientSocket.getOutputStream();
    String line = clientToProxyReader.readLine();
    String connectRequest = "";
    while (line != null && isServerRunning()) {
        connectRequest += line + "\r\n";
        if (connectRequest.endsWith("\r\n\r\n")) {
            break;
        }/*from  w  w w  .  ja  va 2  s .c  om*/
        line = clientToProxyReader.readLine();
    }
    // connect to given host:port
    Matcher matcher = hostPortPattern.matcher(connectRequest);
    if (!matcher.find()) {
        try {
            sendConnectResponse("400 Bad Request", clientToProxyOut, null, 0);
        } finally {
            clientSocket.close();
            stopServer();
        }
        return;
    }
    String host = matcher.group(1);
    int port = Integer.decode(matcher.group(2));

    // connect to server
    Socket serverSocket = new Socket();
    try {
        serverSocket.connect(new InetSocketAddress(host, port));
        addSocket(serverSocket);
        byte[] initialServerResponse = null;
        int nbytes = 0;
        if (mixServerAndProxyResponse) {
            // we want to mix the initial server response with the 200 OK
            initialServerResponse = new byte[64];
            nbytes = serverSocket.getInputStream().read(initialServerResponse);
        }
        sendConnectResponse("200 OK", clientToProxyOut, initialServerResponse, nbytes);
    } catch (IOException e) {
        try {
            sendConnectResponse("404 Not Found", clientToProxyOut, null, 0);
        } finally {
            clientSocket.close();
            stopServer();
        }
        return;
    }
    final InputStream proxyToServerIn = serverSocket.getInputStream();
    final OutputStream proxyToServerOut = serverSocket.getOutputStream();
    _threads.add(new EasyThread() {
        @Override
        void runQuietly() throws Exception {
            try {
                IOUtils.copy(clientToProxyIn, proxyToServerOut);
            } catch (IOException e) {
                LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort());
            }
        }
    }.startThread());
    try {
        if (nBytesToCloseSocketAfter > 0) {
            // Simulate proxy abruptly closing connection
            int leftToRead = nBytesToCloseSocketAfter;
            byte[] buffer = new byte[leftToRead + 256];
            while (true) {
                int numRead = proxyToServerIn.read(buffer, 0, leftToRead);
                if (numRead < 0) {
                    break;
                }
                clientToProxyOut.write(buffer, 0, numRead);
                clientToProxyOut.flush();
                leftToRead -= numRead;
                if (leftToRead <= 0) {
                    LOG.warn("Cutting connection after " + nBytesToCloseSocketAfter + " bytes");
                    break;
                }
            }
        } else {
            IOUtils.copy(proxyToServerIn, clientToProxyOut);
        }
    } catch (IOException e) {
        LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort());
    }
    clientSocket.close();
    serverSocket.close();
}

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

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

    try {//from  ww  w.  j  av  a 2 s. com

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

        //cancello tutte le proprieta' salvate in passato
        applicationService.deleteAllProprietaByTipologiaProprieta(tip.getPropertyHolderClass(), tip);
        //cancello se fanno parte di qualche property holder      
        IContainable containable = applicationService.findContainableByDecorable(tip.getDecoratorClass(),
                tipologiaProprietaId);
        TTP ttp = applicationService.get(holderModel, parentId);
        ttp.getMask().remove(tip);
        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:org.jboss.dashboard.ui.components.DashboardFilterRequestProcessor.java

public Object parseValueForLabelProperty(HttpServletRequest request,
        DashboardFilterProperty dashboardFilterProperty) throws Exception {
    if (!dashboardFilterProperty.isLabelProperty())
        throw new UnsupportedOperationException();

    Map parameters = request.getParameterMap();
    String key = DashboardFilterHandler.PARAM_VALUE + "_" + dashboardFilterProperty.getPropertyId();
    if (parameters.containsKey(key)) {
        String value = ((String[]) parameters.get(key))[0];
        Collection allowedValues = new ArrayList();
        if (DashboardFilterHandler.PARAM_NULL_VALUE.equals(value))
            return null;

        // Free text input.
        if (DashboardFilterHandler.PARAM_CUSTOM_VALUE.equals(value)) {
            value = ((String[]) parameters.get(DashboardFilterHandler.PARAM_CUSTOM_VALUE + "_"
                    + dashboardFilterProperty.getPropertyId()))[0];
            if (value == null || value.trim().length() == 0)
                return null;
            for (String token : StringUtils.split(value, ",")) {
                allowedValues.add(token.trim());
            }//from  www.ja  va 2s  . c  om
        }
        // Combo selection.
        else {
            List propsValues = dashboardFilterProperty.getPropertyDistinctValues();
            if (propsValues != null && !propsValues.isEmpty()) {
                Object propSelectedvalue = propsValues.get(Integer.decode(value).intValue() - 2);
                allowedValues.add(propSelectedvalue);
            }
        }
        return allowedValues;
    }
    return null;
}

From source file:org.kchine.rpf.ManagedServantAbstract.java

/**
 * Obtain the name this servant is registered under
 * /*w  w  w .j a  v  a 2s  .c  om*/
 * @return Servant's name, if any.
 * @throws java.rmi.RemoteException
 */
public static String makeName(String servantPoolPrefix, Registry rmiRegistry) throws RemoteException {

    String servantName = null;
    String[] servantNames = rmiRegistry.list();

    Vector<Integer> idsVector = new Vector<Integer>();
    for (int i = 0; i < servantNames.length; ++i) {
        String name = PoolUtils.shortRmiName(servantNames[i]);
        if (name.startsWith(servantPoolPrefix)) {
            String prefix = name.substring(servantPoolPrefix.length());
            try {
                idsVector.add(Integer.decode(prefix));
            } catch (Exception e) {
            }
        }
    }

    if (idsVector.size() == 0) {
        servantName = servantPoolPrefix + "1";
    } else {
        idsVector.add(0);
        int[] ids = new int[idsVector.size()];
        for (int i = 0; i < ids.length; ++i) {
            ids[i] = idsVector.elementAt(i);
        }
        Arrays.sort(ids);

        for (int i = 0; i < ids.length - 1; ++i) {
            if (ids[i + 1] > (ids[i] + 1)) {
                servantName = servantPoolPrefix + (ids[i] + 1);
                break;
            }
        }
        if (servantName == null) {
            servantName = servantPoolPrefix + (ids[ids.length - 1] + 1);
        }
    }
    return servantName;

}

From source file:NumberUtils.java

/**
 * Parse the given text into a number instance of the given target class,
 * using the corresponding default <code>decode</code> methods. Trims the
 * input <code>String</code> before attempting to parse the number. Supports
 * numbers in hex format (with leading 0x) and in octal format (with leading 0).
 *
 * @param text        the text to convert
 * @param targetClass the target class to parse into
 * @return the parsed number/*w  w  w .j a  v  a  2s .  co m*/
 * @throws IllegalArgumentException if the target class is not supported
 *                                  (i.e. not a standard Number subclass as included in the JDK)
 * @see java.lang.Byte#decode
 * @see java.lang.Short#decode
 * @see java.lang.Integer#decode
 * @see java.lang.Long#decode
 * @see #decodeBigInteger(String)
 * @see java.lang.Float#valueOf
 * @see java.lang.Double#valueOf
 * @see java.math.BigDecimal#BigDecimal(String)
 */
public static Number parseNumber(String text, Class targetClass) {
    String trimmed = text.trim();

    if (targetClass.equals(Byte.class)) {
        return Byte.decode(trimmed);
    } else if (targetClass.equals(Short.class)) {
        return Short.decode(trimmed);
    } else if (targetClass.equals(Integer.class)) {
        return Integer.decode(trimmed);
    } else if (targetClass.equals(Long.class)) {
        return Long.decode(trimmed);
    } else if (targetClass.equals(BigInteger.class)) {
        return decodeBigInteger(trimmed);
    } else if (targetClass.equals(Float.class)) {
        return Float.valueOf(trimmed);
    } else if (targetClass.equals(Double.class)) {
        return Double.valueOf(trimmed);
    } else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
        return new BigDecimal(trimmed);
    } else {
        throw new IllegalArgumentException(
                "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
    }
}

From source file:sawtooth.examples.intkey.IntegerKeyHandler.java

@Override
public void apply(TpProcessRequest transactionRequest, State state)
        throws InvalidTransactionException, InternalError {
    /*//from w w  w.j  a va  2s  . c o m
     * Integer Key state will be stored at an address of the name
     * with the key being the name and the value an Integer. so { "foo": 20, "bar": 26}
     * would be a possibility if the hashing algorithm hashes foo and bar to the
     * same address
     */
    try {
        HashMap updateMap = this.mapper.readValue(transactionRequest.getPayload().toByteArray(), HashMap.class);
        String name = updateMap.get("Name").toString();
        String address = null;
        try {
            address = this.intkeyNameSpace + Utils.hash512(name.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException usee) {
            usee.printStackTrace();
            throw new InternalError("Internal Error, " + usee.toString());
        }
        if (name.length() == 0) {
            throw new InvalidTransactionException("Name is required");
        }
        String verb = updateMap.get("Verb").toString();
        if (verb.length() == 0) {
            throw new InvalidTransactionException("Verb is required");
        }
        Integer value = Integer.decode(updateMap.get("Value").toString());
        if (value == null) {
            throw new InvalidTransactionException("Value is required");
        }

        if (!Arrays.asList("set", "dec", "inc").contains(verb)) {
            throw new InvalidTransactionException("Verb must be set, inc, dec not " + verb);
        }
        Collection<String> addresses = new ArrayList<String>(0);
        if (verb.equals("set")) {
            // The ByteString is cbor encoded dict/hashmap
            Map<String, ByteString> possibleAddressValues = state.get(Arrays.asList(address));
            byte[] stateValueRep = possibleAddressValues.get(address).toByteArray();
            Map<String, Integer> stateValue = null;
            if (stateValueRep.length > 0) {
                stateValue = this.mapper.readValue(stateValueRep, HashMap.class);
                if (stateValue.containsKey(name)) {
                    throw new InvalidTransactionException("Verb is set but Name already in state, " + "Name: "
                            + name + " Value: " + stateValue.get(name).toString());
                }
            }

            if (value < 0) {
                throw new InvalidTransactionException("Verb is set but Value is less than 0");
            }
            // 'set' passes checks so store it in the state
            if (stateValue == null) {
                stateValue = new HashMap<String, Integer>();
            }
            Map<String, Integer> setValue = stateValue;
            setValue.put(name, value);
            Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address,
                    ByteString.copyFrom(this.mapper.writeValueAsBytes(setValue)));

            Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry);
            addresses = state.set(addressValues);
        }
        if (verb.equals("inc")) {
            Map<String, ByteString> possibleValues = state.get(Arrays.asList(address));
            byte[] stateValueRep = possibleValues.get(address).toByteArray();
            if (stateValueRep.length == 0) {
                throw new InvalidTransactionException("Verb is inc but Name is not in state");
            }
            Map<String, Integer> stateValue = this.mapper.readValue(stateValueRep, HashMap.class);
            if (!stateValue.containsKey(name)) {
                throw new InvalidTransactionException("Verb is inc but Name is not in state");
            }

            // Increment the value in state by value
            Map<String, Integer> incValue = stateValue;
            incValue.put(name, stateValue.get(name) + value);
            Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address,
                    ByteString.copyFrom(this.mapper.writeValueAsBytes(incValue)));
            Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry);
            addresses = state.set(addressValues);
        }
        if (verb.equals("dec")) {
            Map<String, ByteString> possibleAddressResult = state.get(Arrays.asList(address));
            byte[] stateValueRep = possibleAddressResult.get(address).toByteArray();

            if (stateValueRep.length == 0) {
                throw new InvalidTransactionException("Verb is dec but Name is not in state");
            }
            Map<String, Integer> stateValue = this.mapper.readValue(stateValueRep, HashMap.class);
            if (!stateValue.containsKey(name)) {
                throw new InvalidTransactionException("Verb is dec but Name is not in state");
            }
            if (stateValue.get(name) - value < 0) {
                throw new InvalidTransactionException("Dec would set Value to less than 0");
            }
            Map<String, Integer> decValue = stateValue;
            // Decrement the value in state by value
            decValue.put(name, stateValue.get(name) - value);
            Map.Entry<String, ByteString> entry = new AbstractMap.SimpleEntry<String, ByteString>(address,
                    ByteString.copyFrom(this.mapper.writeValueAsBytes(decValue)));

            Collection<Map.Entry<String, ByteString>> addressValues = Arrays.asList(entry);
            addresses = state.set(addressValues);
        }
        // if the 'set', 'inc', or 'dec' set to state didn't work
        if (addresses.size() == 0) {
            throw new InternalError("State error!.");
        }
        logger.info("Verb: " + verb + " Name: " + name + " value: " + value);

    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new InternalError("State error" + ioe.toString());
    }
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.dialcharts.Meter.java

/**
 * set parameters for the creation of the chart getting them from template or from LOV.
 * // w  w w.  j  a  va 2  s.  c  om
 * @param content the content of the template.
 * 
 * @return A chart that displays a value as a dial.
 */

public void configureChart(SourceBean content) {
    logger.info("IN");
    super.configureChart(content);

    if (!isLovConfDefined) {
        logger.info("Configuration parameters set in template");
        //reading intervals information
        SourceBean intervalsSB = (SourceBean) content.getAttribute("INTERVALS");
        if (intervalsSB == null) {
            intervalsSB = (SourceBean) content.getAttribute("CONF.INTERVALS");
        }
        List intervalsAttrsList = null;
        if (intervalsSB != null) {
            intervalsAttrsList = intervalsSB.getContainedSourceBeanAttributes();
        }

        if (intervalsAttrsList == null || intervalsAttrsList.isEmpty()) { // if intervals are not defined realize a single interval
            KpiInterval interval = new KpiInterval();
            interval.setLabel("");
            interval.setMin(getLower());
            interval.setMax(getUpper());
            interval.setColor(Color.WHITE);
            addInterval(interval);
        } else {

            Iterator intervalsAttrsIter = intervalsAttrsList.iterator();
            while (intervalsAttrsIter.hasNext()) {
                SourceBeanAttribute paramSBA = (SourceBeanAttribute) intervalsAttrsIter.next();
                SourceBean param = (SourceBean) paramSBA.getValue();

                String label = "";
                if (param.getAttribute("label") != null)
                    label = (String) param.getAttribute("label");
                String min = (String) param.getAttribute(MIN_INTERVAL);
                String max = (String) param.getAttribute(MAX_INTERVAL);
                String col = (String) param.getAttribute(COLOR_INTERVAL);

                KpiInterval interval = new KpiInterval();
                interval.setLabel(label);
                interval.setMin(Double.valueOf(min).doubleValue());
                interval.setMax(Double.valueOf(max).doubleValue());

                Color color = new Color(Integer.decode(col).intValue());
                if (color != null) {
                    interval.setColor(color);
                } else {
                    interval.setColor(Color.RED);
                }
                addInterval(interval);
            }
        }
    } else {
        logger.info("Configuration parameters set in LOV");
        String intervalsNumber = (String) sbRow.getAttribute(INTERVALS_NUMBER);
        if (intervalsNumber == null || intervalsNumber.equals("") || intervalsNumber.equals("0")) { // if intervals are not specified
            logger.warn("intervals not correctly defined, use default settings");
            KpiInterval interval = new KpiInterval();
            interval.setLabel("");
            interval.setMin(getLower());
            interval.setMax(getUpper());
            interval.setColor(Color.WHITE);
            addInterval(interval);
        } else {
            for (int i = 1; i <= Integer.valueOf(intervalsNumber).intValue(); i++) {
                KpiInterval interval = new KpiInterval();
                String label = "";
                if (sbRow.getAttribute("label" + (new Integer(i)).toString()) != null) {
                    label = (String) sbRow.getAttribute("label" + (new Integer(i)).toString());
                }
                String min = (String) sbRow.getAttribute("min" + (new Integer(i)).toString());
                String max = (String) sbRow.getAttribute("max" + (new Integer(i)).toString());
                String col = (String) sbRow.getAttribute("color" + (new Integer(i)).toString());
                interval.setLabel(label);
                interval.setMin(Double.valueOf(min).doubleValue());
                interval.setMax(Double.valueOf(max).doubleValue());
                Color color = new Color(Integer.decode(col).intValue());
                interval.setColor(color);
                addInterval(interval);

            }
        }
    }
    logger.debug("OUT");

}

From source file:org.lieuofs.util.dao.FichierOFSTxtDao.java

protected Mutable creerMutation(String numero, String typeMutation, String date, boolean radiation)
        throws ParseException {
    if (!StringUtils.hasText(numero) || !StringUtils.hasText(typeMutation) || !StringUtils.hasText(date))
        return null;
    Integer num = Integer.decode(numero);
    TypeMutation type = TypeMutation.getParId(Long.decode(typeMutation));
    Date dtSuisse = getDateFmt().parse(date);
    Date dateMutation = radiation ? DateUtil.derniereMillisecondeDeLaJournee(dtSuisse)
            : DateUtil.premierMillisecondeDeLaJournee(dtSuisse);
    return creerMutation(num, type, dateMutation);
}

From source file:org.jahia.security.TOTP.java

/**
 * This method generates a TOTP value for the given set of parameters.
 * /*from   w ww . ja va  2s. c om*/
 * @param key
 *            : 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;
}