Example usage for java.util SortedMap remove

List of usage examples for java.util SortedMap remove

Introduction

In this page you can find the example usage for java.util SortedMap remove.

Prototype

V remove(Object key);

Source Link

Document

Removes the mapping for a key from this map if it is present (optional operation).

Usage

From source file:Main.java

public static <T extends Comparable, U> SortedMap<T, U> removeObjectSortedMap(SortedMap<T, U> map, T key) {
    if (map == null) {
        return new TreeMap<T, U>();
    }// ww w .ja va2  s .c om
    map.remove(key);
    return map;
}

From source file:io.wcm.caravan.commons.httpclient.impl.BeanUtil.java

/**
 * Get map with key/value pairs for properties of a java bean (using {@link BeanUtils#describe(Object)}).
 * An array of property names can be passed that should be masked with "***" because they contain sensitive
 * information.// w ww .jav  a 2 s. c o  m
 * @param beanObject Bean object
 * @param maskProperties List of property names
 * @return Map with masked key/value pairs
 */
public static SortedMap<String, Object> getMaskedBeanProperties(Object beanObject, String[] maskProperties) {
    try {
        SortedMap<String, Object> configProperties = new TreeMap<String, Object>(
                BeanUtils.describe(beanObject));

        // always ignore "class" properties which is added by BeanUtils.describe by default
        configProperties.remove("class");

        // Mask some properties with confidential information (if set to any value)
        if (maskProperties != null) {
            for (String propertyName : maskProperties) {
                if (configProperties.containsKey(propertyName) && configProperties.get(propertyName) != null) {
                    configProperties.put(propertyName, "***");
                }
            }
        }

        return configProperties;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
        throw new IllegalArgumentException("Unable to get properties from: " + beanObject, ex);
    }
}

From source file:org.shept.util.FileUtils.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate)
 * /*from w ww  . ja  v a2  s.c  o  m*/
 * @param destPath
 * @param sourcePath
 * @param filePattern
 * @return the number of files being copied
 */
public static Integer syncAdd(String sourcePath, String destPath, String filePattern) {
    // check for new files since the last check which need to be copied
    Integer number = 0;
    SortedMap<FileNameDate, File> destMap = fileMapByNameAndDate(destPath, filePattern);
    SortedMap<FileNameDate, File> sourceMap = fileMapByNameAndDate(sourcePath, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (File file : sourceMap.values()) {
        log.debug(file.getName() + ": " + new Date(file.lastModified()));
        File copy = new File(destPath, file.getName());
        try {
            if (!copy.exists()) {
                // copy to tmp file first to avoid clashes during lengthy copy action
                File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile());
                FileCopyUtils.copy(file, tmp);
                if (!tmp.renameTo(copy)) {
                    tmp.delete(); // cleanup if we fail
                }
                number++;
            }
        } catch (IOException ex) {
            log.error("FileCopy error for file " + file.getName(), ex);
        }
    }
    return number;
}

From source file:com.cloudera.oryx.kmeans.common.Weighted.java

/**
 * Sample items from a {@code List<Weighted>} where items with higher weights
 * have a higher probability of being included in the sample.
 * //ww w .j  av a2 s  .com
 * @param things The iterable to sample from
 * @param size The number of items to sample
 * @return A list containing the sampled items
 */
public static <T extends Weighted<?>> List<T> sample(Iterable<T> things, int size, RandomGenerator random) {
    if (random == null) {
        random = RandomManager.getRandom();
    }
    SortedMap<Double, T> sampled = Maps.newTreeMap();
    for (T thing : things) {
        if (thing.weight() > 0) {
            double score = Math.log(random.nextDouble()) / thing.weight();
            if (sampled.size() < size || score > sampled.firstKey()) {
                sampled.put(score, thing);
            }
            if (sampled.size() > size) {
                sampled.remove(sampled.firstKey());
            }
        }
    }
    return Lists.newArrayList(sampled.values());
}

From source file:eu.trentorise.opendata.josman.Josmans.java

/**
 * Returns new sorted map of only version tags to be processed of the format
 * repoName-x.y.z filtered tags, the latter having the highest version.
 *
 * @param repoName the github repository name i.e. josman
 * @param tags a list of tags from the repository
 * @param ignoredVersions These versions will be filtered in the output.
 * @return map of version as string and correspondig RepositoryTag
 *///from w  ww .  j  a va 2s  .  c o m
public static SortedMap<String, RepositoryTag> versionTagsToProcess(String repoName, List<RepositoryTag> tags,
        List<SemVersion> ignoredVersions) {
    SortedMap<String, RepositoryTag> map = versionTags(repoName, tags);
    for (SemVersion versionToSkip : ignoredVersions) {
        String tag = releaseTag(repoName, versionToSkip);
        if (map.containsKey(tag)) {
            map.remove(tag);
        }
    }
    return map;
}

From source file:lti.oauth.OAuthFilter.java

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain fc)
        throws ServletException, IOException {

    LaunchRequest launchRequest = new LaunchRequest(req.getParameterMap());
    SortedMap<String, String> alphaSortedMap = launchRequest.toSortedMap();
    String signature = alphaSortedMap.remove(OAuthUtil.SIGNATURE_PARAM);

    String calculatedSignature = null;
    try {//w  ww . j  ava 2 s.c om
        calculatedSignature = new OAuthMessageSigner().sign(secret,
                OAuthUtil.mapToJava(alphaSortedMap.get(OAuthUtil.SIGNATURE_METHOD_PARAM)), "POST",
                req.getRequestURL().toString(), alphaSortedMap);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        res.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return;
    }

    if (!signature.equals(calculatedSignature)) {
        // try again with http
        String recalculatedSignature = null;

        if (StringUtils.startsWithIgnoreCase(req.getRequestURL().toString(), "https:")) {
            String url = StringUtils.replaceOnce(req.getRequestURL().toString(), "https:", "http:");
            try {
                recalculatedSignature = new OAuthMessageSigner().sign(secret,
                        OAuthUtil.mapToJava(alphaSortedMap.get(OAuthUtil.SIGNATURE_METHOD_PARAM)), "POST", url,
                        alphaSortedMap);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                res.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
                return;
            }
        }

        if (!signature.equals(recalculatedSignature)) {
            res.sendError(HttpStatus.UNAUTHORIZED.value());
            return;
        }
    }

    fc.doFilter(req, res);
}

From source file:com.tripit.auth.OAuthCredential.java

public boolean validateSignature(URI requestUri)
        throws URISyntaxException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    List<NameValuePair> argList = URLEncodedUtils.parse(requestUri, "UTF-8");
    SortedMap<String, String> args = new TreeMap<String, String>();
    for (NameValuePair arg : argList) {
        args.put(arg.getName(), arg.getValue());
    }/* ww w  .  j  ava  2  s  . c o  m*/

    String signature = args.remove("oauth_signature");

    String baseUrl = new URI(requestUri.getScheme(), requestUri.getUserInfo(), requestUri.getAuthority(),
            requestUri.getPort(), requestUri.getPath(), null, requestUri.getFragment()).toString();

    return (signature != null && signature.equals(generateSignature(baseUrl, args)));
}

From source file:org.shept.util.FtpFileCopy.java

/**
 * Compare the source path and the destination path for filenames with the filePattern
 * e.g. *.bak, *tmp and copy these files to the destination dir if they are not present at the
 * destination or if they have changed (by modifactionDate).
 * Copying is done through a retrieve operation.
 * //from   w  w w  .  j a v  a  2s .co m
 * @param ftpSource
 * @param localDestPat
 * @param filePattern
 * @return the number of files being copied
 * @throws IOException 
 */
public Integer syncPull(FTPClient ftpSource, String localDestPat, String filePattern) throws IOException {
    // check for new files since the last check which need to be copied

    Integer number = 0;
    SortedMap<FileNameDate, File> destMap = FileUtils.fileMapByNameAndDate(localDestPat, filePattern);
    SortedMap<FileNameDate, FTPFile> sourceMap = fileMapByNameAndDate(ftpSource, filePattern);
    // identify the list of source files different from their destinations
    for (FileNameDate fk : destMap.keySet()) {
        sourceMap.remove(fk);
    }

    // copy the list of files from source to destination
    for (FTPFile file : sourceMap.values()) {
        logger.debug("Copying file " + file.getName() + ": " + file.getTimestamp());
        File copy = new File(localDestPat, file.getName());
        try {
            if (!copy.exists()) {
                // copy to tmp file first to avoid clashes during lengthy copy action
                File tmp = File.createTempFile("vrs", ".tmp", copy.getParentFile());
                FileOutputStream writeStream = new FileOutputStream(tmp);
                boolean rc = ftpSource.retrieveFile(file.getName(), writeStream);
                writeStream.close();
                if (rc) {
                    rc = tmp.renameTo(copy);
                    number++;
                }
                if (!rc) {
                    tmp.delete(); // cleanup if we fail
                }
            }
        } catch (IOException ex) {
            logger.error("Ftp FileCopy did not succeed (using " + file.getName() + ")" + " FTP reported error  "
                    + ftpSource.getReplyString(), ex);
        }
    }
    return number;
}

From source file:net.sourceforge.msscodefactory.cfcore.v1_11.GenKbRam.GenKbRamISOCurrencyTable.java

public void deleteISOCurrency(GenKbAuthorization Authorization, GenKbISOCurrencyBuff Buff) {
    final String S_ProcName = "GenKbRamISOCurrencyTable.deleteISOCurrency() ";
    GenKbISOCurrencyPKey pkey = schema.getFactoryISOCurrency().newPKey();

    pkey.setRequiredId(Buff.getRequiredId());
    GenKbISOCurrencyBuff existing = dictByPKey.get(pkey);
    if (existing == null) {
        throw CFLib.getDefaultExceptionFactory().newStaleCacheDetectedException(getClass(), "deleteISOCurrency",
                "Existing record not found", "ISOCurrency", pkey);
    }/*ww w . j a v a  2s.co  m*/
    if (existing.getRequiredRevision() != Buff.getRequiredRevision()) {
        throw CFLib.getDefaultExceptionFactory().newCollisionDetectedException(getClass(), "deleteISOCurrency",
                pkey);
    }
    GenKbISOCurrencyByCcyCdIdxKey keyCcyCdIdx = schema.getFactoryISOCurrency().newCcyCdIdxKey();
    keyCcyCdIdx.setRequiredISOCode(existing.getRequiredISOCode());

    // Validate reverse foreign keys

    // Delete is valid

    SortedMap<GenKbISOCurrencyPKey, GenKbISOCurrencyBuff> subdict;

    dictByPKey.remove(pkey);

    subdict = dictByCcyCdIdx.get(keyCcyCdIdx);
    subdict.remove(pkey);

}

From source file:com.cloudera.oryx.kmeans.computation.local.SamplingRun.java

@Override
public Collection<RealVector> call() throws Exception {
    SortedMap<Double, RealVector> reservoir = Maps.newTreeMap();
    for (RealVector v : vecs) {
        Distance d = index.getDistance(v, foldId, true);
        if (d.getSquaredDistance() > 0.0) {
            double score = Math.log(random.nextDouble()) / d.getSquaredDistance();
            if (reservoir.size() < sampleCount) {
                reservoir.put(score, v);
            } else if (score > reservoir.firstKey()) {
                reservoir.remove(reservoir.firstKey());
                reservoir.put(score, v);
            }//www.ja  v  a 2s  .  c om
        }
    }
    return reservoir.values();
}