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:com.occamlab.te.parsers.ImageParser.java

private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes)
        throws Exception {
    HashMap<Object, Object> bandMap = new HashMap<Object, Object>();

    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("subimage")) {
                Element e = (Element) node;
                int x = Integer.parseInt(e.getAttribute("x"));
                int y = Integer.parseInt(e.getAttribute("y"));
                int w = Integer.parseInt(e.getAttribute("width"));
                int h = Integer.parseInt(e.getAttribute("height"));
                processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes());
            } else if (node.getLocalName().equals("checksum")) {
                CRC32 checksum = new CRC32();
                Raster raster = buffimage.getRaster();
                DataBufferByte buffer;
                if (node.getParentNode().getLocalName().equals("subimage")) {
                    WritableRaster outRaster = raster.createCompatibleWritableRaster();
                    buffimage.copyData(outRaster);
                    buffer = (DataBufferByte) outRaster.getDataBuffer();
                } else {
                    buffer = (DataBufferByte) raster.getDataBuffer();
                }/*from  w w w  .  j av a 2s  .c o m*/
                int numbanks = buffer.getNumBanks();
                for (int j = 0; j < numbanks; j++) {
                    checksum.update(buffer.getData(j));
                }
                Document doc = node.getOwnerDocument();
                node.appendChild(doc.createTextNode(Long.toString(checksum.getValue())));
            } else if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                if (sample.equals("all")) {
                    bandMap.put(band, null);
                } else {
                    HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band);
                    if (sampleMap == null) {
                        if (!bandMap.containsKey(band)) {
                            sampleMap = new HashMap<Object, Object>();
                            bandMap.put(band, sampleMap);
                        }
                    }
                    sampleMap.put(Integer.decode(sample), new Integer(0));
                }
            } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24
                                                                          // PwD
                String transparentNodata = checkTransparentNodata(buffimage, node);
                node.setTextContent(transparentNodata);
            }
        }
    }

    Iterator bandIt = bandMap.keySet().iterator();
    while (bandIt.hasNext()) {
        String band_str = (String) bandIt.next();
        int band_indexes[];
        if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY
                || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            band_indexes = new int[1];
            band_indexes[0] = 0;
        } else {
            band_indexes = new int[band_str.length()];
            for (int i = 0; i < band_str.length(); i++) {
                if (band_str.charAt(i) == 'A')
                    band_indexes[i] = 3;
                if (band_str.charAt(i) == 'B')
                    band_indexes[i] = 2;
                if (band_str.charAt(i) == 'G')
                    band_indexes[i] = 1;
                if (band_str.charAt(i) == 'R')
                    band_indexes[i] = 0;
            }
        }

        Raster raster = buffimage.getRaster();
        java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str);
        boolean addall = (sampleMap == null);
        if (sampleMap == null) {
            sampleMap = new java.util.HashMap();
            bandMap.put(band_str, sampleMap);
        }

        int minx = raster.getMinX();
        int maxx = minx + raster.getWidth();
        int miny = raster.getMinY();
        int maxy = miny + raster.getHeight();
        int bands[][] = new int[band_indexes.length][raster.getWidth()];

        for (int y = miny; y < maxy; y++) {
            for (int i = 0; i < band_indexes.length; i++) {
                raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]);
            }
            for (int x = minx; x < maxx; x++) {
                int sample = 0;
                for (int i = 0; i < band_indexes.length; i++) {
                    sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8);
                }

                Integer sampleObj = new Integer(sample);

                boolean add = addall;
                if (!addall) {
                    add = sampleMap.containsKey(sampleObj);
                }
                if (add) {
                    Integer count = (Integer) sampleMap.get(sampleObj);
                    if (count == null) {
                        count = new Integer(0);
                    }
                    count = new Integer(count.intValue() + 1);
                    sampleMap.put(sampleObj, count);
                }
            }
        }
    }

    Node node = nodes.item(0);
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            if (node.getLocalName().equals("count")) {
                String band = ((Element) node).getAttribute("bands");
                String sample = ((Element) node).getAttribute("sample");
                HashMap sampleMap = (HashMap) bandMap.get(band);
                Document doc = node.getOwnerDocument();
                if (sample.equals("all")) {
                    Node parent = node.getParentNode();
                    Node prevSibling = node.getPreviousSibling();
                    Iterator sampleIt = sampleMap.keySet().iterator();
                    Element countnode = null;
                    int digits;
                    String prefix;
                    switch (buffimage.getType()) {
                    case BufferedImage.TYPE_BYTE_BINARY:
                        digits = 1;
                        prefix = "";
                        break;
                    case BufferedImage.TYPE_BYTE_GRAY:
                        digits = 2;
                        prefix = "0x";
                        break;
                    default:
                        prefix = "0x";
                        digits = band.length() * 2;
                    }
                    while (sampleIt.hasNext()) {
                        countnode = doc.createElementNS(node.getNamespaceURI(), "count");
                        Integer sampleInt = (Integer) sampleIt.next();
                        Integer count = (Integer) sampleMap.get(sampleInt);
                        if (band.length() > 0) {
                            countnode.setAttribute("bands", band);
                        }
                        countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits));
                        Node textnode = doc.createTextNode(count.toString());
                        countnode.appendChild(textnode);
                        parent.insertBefore(countnode, node);
                        if (sampleIt.hasNext()) {
                            if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) {
                                parent.insertBefore(prevSibling.cloneNode(false), node);
                            }
                        }
                    }
                    parent.removeChild(node);
                    node = countnode;
                } else {
                    Integer count = (Integer) sampleMap.get(Integer.decode(sample));
                    if (count == null)
                        count = new Integer(0);
                    Node textnode = doc.createTextNode(count.toString());
                    node.appendChild(textnode);
                }
            }
        }
        node = node.getNextSibling();
    }
}

From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java

@Override
public ArrayList<ImportKeysListEntry> search(String query)
        throws QueryException, TooManyResponses, InsufficientQuery {
    ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>();

    if (query.length() < 3) {
        throw new InsufficientQuery();
    }//from  w w  w  . ja v  a  2s.  c o  m

    String encodedQuery;
    try {
        encodedQuery = URLEncoder.encode(query, "utf8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery;

    String data;
    try {
        data = query(request);
    } catch (HttpError e) {
        if (e.getCode() == 404) {
            return results;
        } else {
            if (e.getData().toLowerCase(Locale.US).contains("no keys found")) {
                return results;
            } else if (e.getData().toLowerCase(Locale.US).contains("too many")) {
                throw new TooManyResponses();
            } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) {
                throw new InsufficientQuery();
            }
        }
        throw new QueryException("querying server(s) for '" + mHost + "' failed");
    }

    final Matcher matcher = PUB_KEY_LINE.matcher(data);
    while (matcher.find()) {
        final ImportKeysListEntry entry = new ImportKeysListEntry();

        entry.setBitStrength(Integer.parseInt(matcher.group(3)));

        final int algorithmId = Integer.decode(matcher.group(2));
        entry.setAlgorithm(PgpKeyHelper.getAlgorithmInfo(algorithmId));

        // group 1 contains the full fingerprint (v4) or the long key id if available
        // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr
        String fingerprintOrKeyId = matcher.group(1);
        if (fingerprintOrKeyId.length() > 16) {
            entry.setFingerprintHex(fingerprintOrKeyId.toLowerCase(Locale.US));
            entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16,
                    fingerprintOrKeyId.length()));
        } else {
            // set key id only
            entry.setKeyIdHex("0x" + fingerprintOrKeyId);
        }

        final long creationDate = Long.parseLong(matcher.group(4));
        final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        tmpGreg.setTimeInMillis(creationDate * 1000);
        entry.setDate(tmpGreg.getTime());

        entry.setRevoked(matcher.group(6).contains("r"));

        ArrayList<String> userIds = new ArrayList<String>();
        final String uidLines = matcher.group(7);
        final Matcher uidMatcher = UID_LINE.matcher(uidLines);
        while (uidMatcher.find()) {
            String tmp = uidMatcher.group(1).trim();
            if (tmp.contains("%")) {
                try {
                    // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt".
                    tmp = (URLDecoder.decode(tmp, "UTF8"));
                } catch (UnsupportedEncodingException ignored) {
                    // will never happen, because "UTF8" is supported
                }
            }
            userIds.add(tmp);
        }
        entry.setUserIds(userIds);
        entry.setPrimaryUserId(userIds.get(0));

        results.add(entry);
    }
    return results;
}

From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java

@Override
public ArrayList<ImportKeysListEntry> search(String query)
        throws QueryFailedException, QueryNeedsRepairException {
    ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>();

    if (query.length() < 3) {
        throw new QueryTooShortException();
    }// w  w w  . ja va2 s . co m

    String encodedQuery;
    try {
        encodedQuery = URLEncoder.encode(query, "utf8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery;

    String data;
    try {
        data = query(request);
    } catch (HttpError e) {
        if (e.getCode() == 404) {
            return results;
        } else {
            if (e.getData().toLowerCase(Locale.US).contains("no keys found")) {
                return results;
            } else if (e.getData().toLowerCase(Locale.US).contains("too many")) {
                throw new TooManyResponsesException();
            } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) {
                throw new QueryTooShortException();
            }
        }
        throw new QueryFailedException("querying server(s) for '" + mHost + "' failed");
    }

    final Matcher matcher = PUB_KEY_LINE.matcher(data);
    while (matcher.find()) {
        final ImportKeysListEntry entry = new ImportKeysListEntry();
        entry.setQuery(query);

        entry.setBitStrength(Integer.parseInt(matcher.group(3)));

        final int algorithmId = Integer.decode(matcher.group(2));
        entry.setAlgorithm(PgpKeyHelper.getAlgorithmInfo(algorithmId));

        // group 1 contains the full fingerprint (v4) or the long key id if available
        // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr
        String fingerprintOrKeyId = matcher.group(1);
        if (fingerprintOrKeyId.length() > 16) {
            entry.setFingerprintHex(fingerprintOrKeyId.toLowerCase(Locale.US));
            entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16,
                    fingerprintOrKeyId.length()));
        } else {
            // set key id only
            entry.setKeyIdHex("0x" + fingerprintOrKeyId);
        }

        final long creationDate = Long.parseLong(matcher.group(4));
        final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        tmpGreg.setTimeInMillis(creationDate * 1000);
        entry.setDate(tmpGreg.getTime());

        entry.setRevoked(matcher.group(6).contains("r"));

        ArrayList<String> userIds = new ArrayList<String>();
        final String uidLines = matcher.group(7);
        final Matcher uidMatcher = UID_LINE.matcher(uidLines);
        while (uidMatcher.find()) {
            String tmp = uidMatcher.group(1).trim();
            if (tmp.contains("%")) {
                try {
                    // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt".
                    tmp = (URLDecoder.decode(tmp, "UTF8"));
                } catch (UnsupportedEncodingException ignored) {
                    // will never happen, because "UTF8" is supported
                }
            }
            userIds.add(tmp);
        }
        entry.setUserIds(userIds);
        entry.setPrimaryUserId(userIds.get(0));

        results.add(entry);
    }
    return results;
}

From source file:org.ohmage.domain.campaign.prompt.MultiChoicePrompt.java

/**
 * Validates that a given value is valid and, if so, converts it into an
 * appropriate object.//from   w  ww  .jav a 2s  . c om
 * 
 * @param value The value to be validated. This must be one of the  
 *             following:<br />
 *             <ul>
 *             <li>{@link NoResponse}</li>
 *             <li>{@link Integer}. This will be converted into a list of
 *               one items that contains this integer. The {@link Integer}
 *               should be the key of the item that the user chose.</li>
 *             <li>A {@link Collection} of {@link Integer}s where each
 *               {@link Integer} is a key to a unique item the user chose.
 *               </li>
 *             <li>A {@link JSONArray} of {@link Integer}s where each
 *               {@link Integer} is a key to a unique item the user chose.
 *               </li>
 *             <li>{@link String} that represents:</li>
 *               <ul>
 *                 <li>{@link NoResponse}</li>
 *                 <li>A {@link JSONArray} of {@link Integer}s where each
 *                   {@link Integer} is a key to a unique item the user 
 *                   chose.</li>
 *                 <li>A comma-separated list of {@link Integer}s where 
 *                   each {@link Integer} is a key to a unique item the 
 *                   user chose.</li>
 *               <ul>
 *             </ul>
 * 
 * @return A {@link Collection} of {@link Integer}s or a {@link NoResponse}
 *          object.
 * 
 * @throws DomainException The value is invalid.
 */
@Override
public Object validateValue(final Object value) throws DomainException {
    Collection<Integer> collectionValue = null;
    Map<Integer, LabelValuePair> choices = getChoices();

    // If it's already a NoResponse value, then return make sure that if it
    // was skipped that it as skippable.
    if (value instanceof NoResponse) {
        if (NoResponse.SKIPPED.equals(value) && (!skippable())) {
            throw new DomainException("The prompt, '" + getId() + "', was skipped, but it is not skippable.");
        }

        return value;
    }
    // If it's already an integer, add it as the only result item.
    else if (value instanceof Integer) {
        collectionValue = new ArrayList<Integer>(1);
        collectionValue.add((Integer) value);
    }
    // If it's already a collection, first ensure that all of the elements
    // are integers.
    else if (value instanceof Collection<?>) {
        Collection<?> values = (Collection<?>) value;
        collectionValue = new HashSet<Integer>(values.size());

        for (Object currResponse : values) {
            if (currResponse instanceof Integer) {
                collectionValue.add((Integer) currResponse);
            } else {
                throw new DomainException(
                        "The value was a collection, but not all of the items were integers for prompt '"
                                + getId() + "'.");
            }
        }
    }
    // If it's a JSONArray, parse it and get the items.
    else if (value instanceof JSONArray) {
        JSONArray responses = (JSONArray) value;
        int numResponses = responses.length();
        collectionValue = new HashSet<Integer>(numResponses);

        for (int i = 0; i < numResponses; i++) {
            try {
                collectionValue.add(responses.getInt(i));
            } catch (JSONException notKey) {
                throw new DomainException(
                        "The value was a JSONArray, but not all of the elements were integers for prompt '"
                                + getId() + "'.",
                        notKey);
            }
        }
    }
    // If it's a sting, parse it to check if it's a NoResponse value and,
    // if not, parse it and generate a list of values.
    else if (value instanceof String) {
        String valueString = (String) value;

        try {
            return NoResponse.valueOf(valueString);
        } catch (IllegalArgumentException notNoResponse) {
            collectionValue = new HashSet<Integer>();

            try {
                JSONArray responses = new JSONArray(valueString);

                int numResponses = responses.length();
                for (int i = 0; i < numResponses; i++) {
                    try {
                        collectionValue.add(responses.getInt(i));
                    } catch (JSONException notKey) {
                        throw new DomainException(
                                "The value was a JSONArray, but not all of the elements were integers for prompt '"
                                        + getId() + "'.",
                                notKey);
                    }
                }
            } catch (JSONException notJsonArray) {
                String[] responses = valueString.split(",");

                collectionValue = new HashSet<Integer>(responses.length);
                for (int i = 0; i < responses.length; i++) {
                    String currResponse = responses[i];

                    if (StringUtils.isEmptyOrWhitespaceOnly(currResponse)) {
                        try {
                            collectionValue.add(Integer.decode(currResponse));
                        } catch (NumberFormatException notKey) {
                            throw new DomainException(
                                    "The value was a comma-separated list, but not all of the elemtns were integers for prompt '"
                                            + getId() + "'.",
                                    notKey);
                        }
                    }
                }
            }
        }
    } else {
        throw new DomainException("The value is not decodable as a reponse value for prompt '" + getId() + "': "
                + value.toString());
    }

    for (Integer key : collectionValue) {
        if (!choices.containsKey(key)) {
            throw new DomainException(
                    "A key was given that isn't a known choice for prompt '" + getId() + "': " + key);
        }
    }

    return collectionValue;
}

From source file:org.openhab.binding.canopen.internal.CANOpenBinding.java

/**
 * @{inheritDoc}//from   w  ww. j ava2 s  .  co m
 */
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {

        // to override the default refresh interval one has to add a 
        // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
        refreshInterval = 60000;
        String refreshIntervalString = (String) config.get("refresh");
        if (StringUtils.isNotBlank(refreshIntervalString)) {
            refreshInterval = Long.parseLong(refreshIntervalString);
        }

        sdoResponseTimeout = 1000;
        String sdoResponseTimeoutString = (String) config.get("sdo_timeout");
        if (StringUtils.isNotBlank(sdoResponseTimeoutString)) {
            sdoResponseTimeout = Integer.parseInt(sdoResponseTimeoutString);
        }

        autoStartNodes.clear();
        autoStartAll = false;
        String autoStartString = (String) config.get("auto_start_nodes");
        if (StringUtils.isNotBlank(autoStartString)) {
            String[] nodes = autoStartString.split(",");
            for (String node : nodes) {
                if (node.trim().toLowerCase().equals("all"))
                    autoStartAll = true;

                try {
                    autoStartNodes.add(Integer.decode(node));
                } catch (NumberFormatException e) {
                }
            }
        }

        syncInterfaces.clear();
        String syncInterfaceString = (String) config.get("sync_master_for");
        if (StringUtils.isNotBlank(syncInterfaceString)) {
            if (syncInterfaceString.contains(","))
                syncInterfaces.addAll(Arrays.asList(syncInterfaceString.split("\\s*,\\s*")));
            else
                syncInterfaces.add(syncInterfaceString.trim());
            logger.debug("Sync master for: " + syncInterfaces);
        }

        syncMaxVal = 0;
        String syncMaxValString = (String) config.get("sync_max_val");
        if (StringUtils.isNotBlank(syncMaxValString)) {
            try {
                syncMaxVal = Integer.parseInt(syncMaxValString);
                if (syncMaxVal > 255)
                    syncMaxVal = 255;
                if (syncMaxVal < 0)
                    syncMaxVal = 0;
            } catch (NumberFormatException e) {
                logger.error("Could not parse sync_max_val from string " + syncMaxValString);
            }
        }

        setProperlyConfigured(true);
    }
}

From source file:com.aurel.track.admin.customize.category.filter.execute.SavedFilterExecuteBL.java

/**
 * Executes an encoded query//  www  . j  ava  2  s .  c  o m
 * @return
 */
static EncodedQueryCtx executeEncodedQuery(String query, Map<String, Object> session)
        throws NotLoggedException, HasParametersException {
    EncodedQueryCtx encodedQueryCtx = new EncodedQueryCtx();
    boolean keepMeLogged = false;
    TPersonBean personBean;
    Locale locale;
    if (query != null && query.length() > 0) {
        String linkReport = ReportQueryBL.b(query);
        Map<String, String> queryEncodedMap = ReportQueryBL.decodeMapFromUrl(linkReport);
        String user = queryEncodedMap.get("user");
        String pswd = queryEncodedMap.get("pswd");
        String keepMeLoggedStr = queryEncodedMap.get("keepMeLogged");
        if (user == null) {
            personBean = (TPersonBean) session.get(Constants.USER_KEY);
            keepMeLogged = true;
        } else {
            keepMeLogged = keepMeLoggedStr != null && keepMeLoggedStr.equalsIgnoreCase("true");
            personBean = SavedFilterExecuteBL.getByLoginName(user, pswd);
        }
        if (keepMeLogged) {
            session.put("forceLoggoffAfterReportOverview", Boolean.FALSE);
        } else {
            session.put("forceLoggoffAfterReportOverview", Boolean.TRUE);
        }
        if (personBean == null) {
            throw new NotLoggedException();
        }
        locale = personBean.getLocale();
        String queryIDStr = queryEncodedMap.get("queryID");
        Integer filterID = null;
        if (queryIDStr != null) {
            filterID = Integer.decode(queryIDStr);
        }
        IntegerStringBean result = encodedQueryContainsNotSpecifiedParameter(query, personBean, locale);
        QueryContext queryContext = new QueryContext();
        switch (result.getValue()) {
        case NO_PARAMETER:
            queryContext = new QueryContext();
            queryContext.setQueryID(filterID);
            queryContext.setQueryType(ItemNavigatorBL.QUERY_TYPE.SAVED);
            encodedQueryCtx.setKeepMeLogged(keepMeLogged);
            encodedQueryCtx.setParametrized(false);
            encodedQueryCtx.setPersonBean(personBean);
            encodedQueryCtx.setLocale(locale);
            encodedQueryCtx.setQueryContext(queryContext);
            return encodedQueryCtx;
        case CONTAINS_PARAMETER_AFTER_REQUEST_REPLACE:
        case CONTAINS_PARAMETER_ORIGINAL:
            queryContext = new QueryContext();
            //although a parameterized filter is a saved filter, it is saved in QueryContext as INSTANT_REPORT_FILTER
            //independently whether it was executed from edit mode (possibly "instantly" modified)
            //or directly because the parameters have to be replaced anyway and then the resulting expression should be saved in QueryContext
            queryContext.setQueryType(ItemNavigatorBL.QUERY_TYPE.INSTANT);
            queryContext.setQueryID(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER);
            queryContext.setFilterExpression(result.getLabel());
            encodedQueryCtx.setKeepMeLogged(keepMeLogged);
            encodedQueryCtx.setParametrized(false);
            encodedQueryCtx.setPersonBean(personBean);
            encodedQueryCtx.setLocale(locale);
            encodedQueryCtx.setQueryContext(queryContext);
            return encodedQueryCtx;
        }
    }
    return null;
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.multipleSubform.SubFormSendHandler.java

public void actionDeleteItem(CommandRequest request) throws Exception {
    String[] uids = request.getRequestObject().getParameterValues("child_uid_value");
    String uid = "";
    if (uids != null) {
        for (int i = 0; i < uids.length; i++) {
            if (uids[i] != null && !"".equals(uids[i]))
                uid = uids[i];// ww  w  .ja v a 2 s. c om
        }
    }
    String sIndex = request.getParameter(uid + "_index");
    String parentFormId = request.getParameter(uid + "_parentFormId");
    String parentNamespace = request.getParameter(uid + "_parentNamespace");
    String fieldName = request.getParameter(uid + "_field");
    String inputName = request.getParameter(uid + "_inputName");

    Form parentForm = subformFinderService.getFormById(Long.decode(parentFormId), parentNamespace);

    getFormProcessor().setValues(parentForm, parentNamespace, request.getRequestObject().getParameterMap(),
            request.getFilesByParamName());
    Field field = parentForm.getField(fieldName);
    FieldHandler handler = getFieldHandlersManager().getHandler(field.getFieldType());
    if (handler instanceof CreateDynamicObjectFieldHandler) {
        CreateDynamicObjectFieldHandler fHandler = (CreateDynamicObjectFieldHandler) handler;
        int index = Integer.decode(sIndex).intValue();
        Object deletedResultValue = fHandler.deleteElementInPosition(parentForm, parentNamespace, fieldName,
                index);

        List<Integer> removedValues = helper.getRemovedFieldPositions(inputName);

        if (removedValues == null)
            helper.setRemovedFieldPositions(inputName, (removedValues = new ArrayList<Integer>()));

        removedValues.add(index);

        getFormProcessor().modify(parentForm, parentNamespace, fieldName, deletedResultValue);
    } else {
        log.error("Cannot delete value in a field which is not a CreateDynamicObjectFieldHandler.");
    }
    getFormProcessor().clearFieldErrors(parentForm, parentNamespace);
}

From source file:org.thialfihar.android.apg.pgp.HkpKeyServer.java

@Override
public ArrayList<ImportKeysListEntry> search(String query)
        throws QueryException, TooManyResponses, InsufficientQuery {
    ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>();

    if (query.length() < 3) {
        throw new InsufficientQuery();
    }//from   w w w .j  a  v a2  s.  c  o  m

    String encodedQuery;
    try {
        encodedQuery = URLEncoder.encode(query, "utf8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery;

    String data;
    try {
        data = query(request);
    } catch (HttpError e) {
        if (e.getCode() == 404) {
            return results;
        } else {
            if (e.getData().toLowerCase(Locale.US).contains("no keys found")) {
                return results;
            } else if (e.getData().toLowerCase(Locale.US).contains("too many")) {
                throw new TooManyResponses();
            } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) {
                throw new InsufficientQuery();
            }
        }
        throw new QueryException("querying server(s) for '" + mHost + "' failed");
    }

    final Matcher matcher = PUB_KEY_LINE.matcher(data);
    while (matcher.find()) {
        final ImportKeysListEntry entry = new ImportKeysListEntry();

        entry.setBitStrength(Integer.parseInt(matcher.group(3)));

        final int algorithmId = Integer.decode(matcher.group(2));
        entry.setAlgorithm(ImportKeysListEntry.getAlgorithmFromId(algorithmId));

        // group 1 contains the full fingerprint (v4) or the long key id if available
        // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr
        String fingerprintOrKeyId = matcher.group(1);
        if (fingerprintOrKeyId.length() > 16) {
            entry.setFingerPrintHex(fingerprintOrKeyId.toLowerCase(Locale.US));
            entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16,
                    fingerprintOrKeyId.length()));
        } else {
            // set key id only
            entry.setKeyIdHex("0x" + fingerprintOrKeyId);
        }

        final long creationDate = Long.parseLong(matcher.group(4));
        final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        tmpGreg.setTimeInMillis(creationDate * 1000);
        entry.setDate(tmpGreg.getTime());

        entry.setRevoked(matcher.group(6).contains("r"));

        ArrayList<String> userIds = new ArrayList<String>();
        final String uidLines = matcher.group(7);
        final Matcher uidMatcher = UID_LINE.matcher(uidLines);
        while (uidMatcher.find()) {
            String tmp = uidMatcher.group(1).trim();
            if (tmp.contains("%")) {
                try {
                    // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt".
                    tmp = (URLDecoder.decode(tmp, "UTF8"));
                } catch (UnsupportedEncodingException ignored) {
                    // will never happen, because "UTF8" is supported
                }
            }
            userIds.add(tmp);
        }
        entry.setUserIds(userIds);

        results.add(entry);
    }
    return results;
}

From source file:org.kchine.rpf.reg.ServantProviderFactoryReg.java

void initPoolsHashMap(InputStream poolsXmlStream) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/* w w  w .  j a  v  a2s .c  o  m*/
    domFactory.setValidating(false);
    DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(poolsXmlStream);
    NodeList pools = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < pools.getLength(); ++i) {
        Node p = pools.item(i);
        if (p.getNodeName().equals("pool")) {
            String name = p.getAttributes().getNamedItem("name").getNodeValue();
            int timeout = p.getAttributes().getNamedItem("borrowTimeout") == null ? DEFAULT_TIMEOUT
                    : Integer.decode(p.getAttributes().getNamedItem("borrowTimeout").getNodeValue());
            PoolData poolData = new PoolData(name, timeout, new Vector<PoolNode>());
            _poolHashMap.put(poolData.getPoolName(), poolData);

            NodeList pnodes = p.getChildNodes();
            for (int j = 0; j < pnodes.getLength(); ++j) {
                Node pn = pnodes.item(j);
                if (pn.getNodeName().equals("node")) {
                    String prefix = pn.getAttributes().getNamedItem("prefix") == null ? DEFAULT_PREFIX
                            : pn.getAttributes().getNamedItem("prefix").getNodeValue();
                    String host = pn.getAttributes().getNamedItem("registryHost") == null
                            ? DEFAULT_REGISTRY_HOST
                            : pn.getAttributes().getNamedItem("registryHost").getNodeValue();
                    int port = pn.getAttributes().getNamedItem("registryPort") == null ? DEFAULT_REGISTRY_PORT
                            : Integer.decode(pn.getAttributes().getNamedItem("registryPort").getNodeValue());
                    poolData.getNodes().add(new PoolNode(prefix, host, port));
                }
            }
        }
    }

    _defaultPoolName = document.getDocumentElement().getAttribute("default");
    if (_poolHashMap.get(_defaultPoolName) == null)
        throw new Exception("bad default pool name");
}

From source file:com.excelsiorjet.api.util.Utils.java

public static String deriveFourDigitVersion(String version) {
    String[] versions = version.split("\\.");
    String[] finalVersions = new String[] { "0", "0", "0", "0" };
    for (int i = 0; i < Math.min(versions.length, 4); ++i) {
        try {/*from  w  ww  .  ja v  a 2 s  .co  m*/
            finalVersions[i] = Integer.decode(versions[i]).toString();
        } catch (NumberFormatException e) {
            int minusPos = versions[i].indexOf('-');
            if (minusPos > 0) {
                String v = versions[i].substring(0, minusPos);
                try {
                    finalVersions[i] = Integer.decode(v).toString();
                } catch (NumberFormatException ignore) {
                }
            }
        }
    }
    return String.join(".", (CharSequence[]) finalVersions);
}