Example usage for java.util HashMap values

List of usage examples for java.util HashMap values

Introduction

In this page you can find the example usage for java.util HashMap values.

Prototype

public Collection<V> values() 

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:fr.efl.chaine.xslt.GauloisPipe.java

private XsltTransformer buildTransformer(Pipe pipe, File inputFile, String inputFileUri,
        HashMap<QName, ParameterValue> parameters, MessageListener listener, XdmNode documentTree,
        boolean... isFake) throws InvalidSyntaxException, URISyntaxException, MalformedURLException,
        SaxonApiException, FileNotFoundException, IOException {
    LOGGER.trace("in buildTransformer(Pipe,...)");
    XsltTransformer first = null;//w ww .  j a  v a  2s. c  om
    Iterator<ParametrableStep> it = pipe.getXslts();
    Object previousTransformer = null;
    while (it.hasNext()) {
        LOGGER.trace("...in buildTransformer.tee.while");
        ParametrableStep step = it.next();
        if (step instanceof Xslt) {
            Xslt xsl = (Xslt) step;
            XsltTransformer currentTransformer = getXsltTransformer(xsl.getHref(), parameters);
            Destination currentDestination = currentTransformer;
            if (xsl.isTraceToAdd()) {
                currentTransformer.setTraceListener(traceListener);
            }
            if (listener != null) {
                LOGGER.trace(xsl.getHref() + " setting messageListener " + listener);
                currentTransformer.setMessageListener(listener);
            }
            for (ParameterValue pv : xsl.getParams()) {
                // on substitue les paramtres globaux dans ceux de la XSL
                String value = ParametersMerger.processParametersReplacement(pv.getValue(), parameters);
                LOGGER.trace("Setting parameter (" + pv.getKey() + "," + value + ")");
                currentTransformer.setParameter(pv.getKey(), new XdmAtomicValue(value));
            }
            for (ParameterValue pv : parameters.values()) {
                // substitution has been before, in merge, but there is input-file relative parameters...
                currentTransformer.setParameter(pv.getKey(), new XdmAtomicValue(
                        ParametersMerger.processParametersReplacement(pv.getValue(), parameters)));
            }
            if (xsl.isDebug()) {
                File debugFile;
                if (debugDirectory != null) {
                    debugFile = new File(debugDirectory, xsl.getId() + "-" + inputFile.getName());
                } else {
                    debugFile = new File(xsl.getId() + "-" + inputFile.getName());
                }
                Serializer debug = processor.newSerializer(debugFile);
                // here currentTransformer==currentDestination
                currentTransformer.setDestination(currentDestination = new TeeDebugDestination(debug));
            }
            if (first == null) {
                first = currentTransformer;
            }
            if (previousTransformer != null) {
                assignStepToDestination(previousTransformer, currentDestination);
            }
            previousTransformer = currentDestination;
            LOGGER.trace(xsl.getHref() + " constructed and added to pipe");
        } else if (step instanceof ChooseStep) {
            ChooseStep cStep = (ChooseStep) step;
            XPathCompiler xpc = getXPathCompiler();
            if (documentTree == null) {
                // here, we are in a pre-compile xsl step, ignore the choose...
            } else {
                for (WhenEntry when : cStep.getConditions()) {
                    XPathSelector select = xpc.compile(when.getTest()).load();
                    select.setContextItem(documentTree);
                    XdmValue result = select.evaluate();
                    if (result.size() != 1) {
                        throw new InvalidSyntaxException(
                                when.getTest() + " does not produce a xs:boolean result");
                    }
                    if ("true".equals(result.itemAt(0).getStringValue())) {
                        // use this WHEN !
                        // on ne peut pas faire a, il n'y a pas de terminal step.
                        Pipe fakePipe = new Pipe();
                        for (ParametrableStep innerStep : when.getSteps()) {
                            fakePipe.addXslt(innerStep);
                        }
                        Destination currentDestination = buildTransformer(fakePipe, inputFile, inputFileUri,
                                parameters, listener, documentTree, true);
                        if (previousTransformer != null) {
                            assignStepToDestination(previousTransformer, currentDestination);
                        }
                        previousTransformer = currentDestination;
                        break;
                    }
                }
            }
        } else if (step instanceof JavaStep) {
            JavaStep javaStep = (JavaStep) step;
            LOGGER.debug("creating " + javaStep.getStepClass().getName());
            try {
                LOGGER.debug("[JAVA-STEP] Creating " + javaStep.getStepClass().getName());
                StepJava stepJava = javaStep.getStepClass().newInstance();
                for (ParameterValue pv : javaStep.getParams()) {
                    stepJava.setParameter(pv.getKey(), new XdmAtomicValue(
                            ParametersMerger.processParametersReplacement(pv.getValue(), parameters)));
                }
                for (ParameterValue pv : parameters.values()) {
                    // la substitution a t faite avant, dans le merge
                    stepJava.setParameter(pv.getKey(), new XdmAtomicValue(
                            ParametersMerger.processParametersReplacement(pv.getValue(), parameters)));
                }
                if (previousTransformer != null) {
                    assignStepToDestination(previousTransformer, stepJava);
                }
                previousTransformer = stepJava;
            } catch (InstantiationException | IllegalAccessException ex) {
                throw new InvalidSyntaxException(ex);
            }
        } else if (step instanceof Tee) {
            throw new InvalidSyntaxException("A tee can not be the root of a pipe");
        }
    }
    Destination nextStep = null;
    if (pipe.getTee() != null) {
        LOGGER.trace("after having construct xslts, build tee");
        nextStep = buildTransformer(pipe.getTee(), inputFile, inputFileUri, parameters, listener, documentTree);
    } else if (pipe.getOutput() != null) {
        LOGGER.trace("after having construct xslts, build output");
        nextStep = buildSerializer(pipe.getOutput(), inputFile, parameters);
    }
    if (nextStep != null) {
        assignStepToDestination(previousTransformer, nextStep);
    } else if (isFake.length == 0 || !isFake[0]) {
        throw new InvalidSyntaxException("Pipe " + pipe.toString() + " has no terminal Step.");
    }
    return first;
}

From source file:es.pode.buscar.negocio.buscar.servicios.SrvBuscarServiceImpl.java

private DocumentosVO ordenarResultados(List documentos) throws NumberFormatException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException {
    if (logger.isDebugEnabled())
        logger.debug("SrvBuscarServiceImpl - ordenarResultados: Inicio.");
    int totalResultados = 0, numeroResultados = 0, numDocumentosIndice = 0;
    HashMap<String, DocVO> eliminarRepetidos = new HashMap<String, DocVO>();
    for (int i = 0; i < documentos.size(); i++) {
        DocumentosVO doc = (DocumentosVO) documentos.get(i);
        int resultadosRepetidos = 0;
        //if(documentos.size()==1 || (doc.getResultados()[0].getNodo()==null && resultadoMayor.getResultados()[0].getNodo()==null) || (doc.getResultados()[0].getNodo()==null && resultadoMayor.getResultados()[0].getNodo()!=null) || (doc.getResultados()[0].getNodo()!=null && resultadoMayor.getResultados()[0].getNodo()==null) || !doc.getResultados()[0].getNodo().equals(resultadoMayor.getResultados()[0].getNodo())){
        DocVO[] resultados = ((DocumentosVO) documentos.get(i)).getResultados();
        for (int j = 0; (j < resultados.length && resultados[j] != null); j++) {
            if (eliminarRepetidos.containsKey(resultados[j].getIdentificadorODE())) {
                resultadosRepetidos++;/* ww  w.jav  a 2 s. co m*/
                if (resultados[j].getNodo() == null)
                    eliminarRepetidos.put(resultados[j].getIdentificadorODE(), resultados[j]);
            } else
                eliminarRepetidos.put(resultados[j].getIdentificadorODE(), resultados[j]);
        }
        totalResultados = totalResultados + doc.getTotalResultados().intValue() - resultadosRepetidos;
        numeroResultados = numeroResultados + doc.getNumeroResultados().intValue() - resultadosRepetidos;
        numDocumentosIndice = numDocumentosIndice + doc.getNumDocumentosIndice();
    }
    List<DocVO> documentosOrdenados = new ArrayList<DocVO>(eliminarRepetidos.values());
    Collections.sort(documentosOrdenados, new DocRankingComparator());
    DocumentosVO documento = new DocumentosVO();
    documento.setResultados(documentosOrdenados.toArray(new DocVO[0]));
    documento.setNumeroResultados(numeroResultados);
    documento.setNumDocumentosIndice(numDocumentosIndice);
    documento.setTotalResultados(totalResultados);
    if (logger.isDebugEnabled())
        logger.debug("SrvBuscarServiceImpl - ordenarResultados: Resultados ordenados");
    return documento;
}

From source file:org.apache.hadoop.hbase.regionserver.TestColumnSeeking.java

@SuppressWarnings("unchecked")
@Test/*  w w w  . j av  a2  s  .  c o m*/
public void testReseeking() throws IOException {
    String family = "Family";
    byte[] familyBytes = Bytes.toBytes("Family");
    TableName table = TableName.valueOf(name.getMethodName());

    HTableDescriptor htd = new HTableDescriptor(table);
    HColumnDescriptor hcd = new HColumnDescriptor(family);
    hcd.setMaxVersions(3);
    htd.addFamily(hcd);

    HRegionInfo info = new HRegionInfo(table, null, null, false);
    HRegion region = TEST_UTIL.createLocalHRegion(info, htd);

    List<String> rows = generateRandomWords(10, "row");
    List<String> allColumns = generateRandomWords(100, "column");

    long maxTimestamp = 2;
    double selectPercent = 0.5;
    int numberOfTests = 5;
    double flushPercentage = 0.2;
    double minorPercentage = 0.2;
    double majorPercentage = 0.2;
    double putPercentage = 0.2;

    HashMap<String, KeyValue> allKVMap = new HashMap<String, KeyValue>();

    HashMap<String, KeyValue>[] kvMaps = new HashMap[numberOfTests];
    ArrayList<String>[] columnLists = new ArrayList[numberOfTests];
    String valueString = "Value";

    for (int i = 0; i < numberOfTests; i++) {
        kvMaps[i] = new HashMap<String, KeyValue>();
        columnLists[i] = new ArrayList<String>();
        for (String column : allColumns) {
            if (Math.random() < selectPercent) {
                columnLists[i].add(column);
            }
        }
    }

    for (String row : rows) {
        Put p = new Put(Bytes.toBytes(row));
        p.setDurability(Durability.SKIP_WAL);
        for (String column : allColumns) {
            for (long timestamp = 1; timestamp <= maxTimestamp; timestamp++) {
                KeyValue kv = KeyValueTestUtil.create(row, family, column, timestamp, valueString);
                if (Math.random() < putPercentage) {
                    p.add(kv);
                    allKVMap.put(kv.getKeyString(), kv);
                    for (int i = 0; i < numberOfTests; i++) {
                        if (columnLists[i].contains(column)) {
                            kvMaps[i].put(kv.getKeyString(), kv);
                        }
                    }
                }

            }
        }
        region.put(p);
        if (Math.random() < flushPercentage) {
            LOG.info("Flushing... ");
            region.flushcache();
        }

        if (Math.random() < minorPercentage) {
            LOG.info("Minor compacting... ");
            region.compactStores(false);
        }

        if (Math.random() < majorPercentage) {
            LOG.info("Major compacting... ");
            region.compactStores(true);
        }
    }

    for (int i = 0; i < numberOfTests + 1; i++) {
        Collection<KeyValue> kvSet;
        Scan scan = new Scan();
        scan.setMaxVersions();
        if (i < numberOfTests) {
            if (columnLists[i].size() == 0)
                continue; // HBASE-7700
            kvSet = kvMaps[i].values();
            for (String column : columnLists[i]) {
                scan.addColumn(familyBytes, Bytes.toBytes(column));
            }
            LOG.info("ExplicitColumns scanner");
            LOG.info("Columns: " + columnLists[i].size() + "  Keys: " + kvSet.size());
        } else {
            kvSet = allKVMap.values();
            LOG.info("Wildcard scanner");
            LOG.info("Columns: " + allColumns.size() + "  Keys: " + kvSet.size());

        }
        InternalScanner scanner = region.getScanner(scan);
        List<Cell> results = new ArrayList<Cell>();
        while (scanner.next(results))
            ;
        assertEquals(kvSet.size(), results.size());
        assertTrue(KeyValueTestUtil.containsIgnoreMvccVersion(results, kvSet));
    }

    HRegion.closeHRegion(region);
}

From source file:com.zenesis.qx.remote.ProxyTypeImpl.java

/**
 * Constructor, used for defining interfaces which are to be proxied
 * @param className//from   w ww  .j av a2  s .  co  m
 * @param methods
 */
public ProxyTypeImpl(ProxyType superType, Class clazz, Set<ProxyType> interfaces) {
    super();
    if (interfaces == null)
        interfaces = Collections.EMPTY_SET;
    this.superType = superType;
    this.interfaces = interfaces;
    this.clazz = clazz;

    MethodsCompiler methodsCompiler = new MethodsCompiler();

    // Get a complete list of methods from the interfaces that the new class has to 
    //   implement; we include methods marked as DoNotProxy so that we can check for 
    //   conflicting instructions
    if (!clazz.isInterface()) {
        // Get a full list of the interfaces which our class has to implement
        HashSet<ProxyType> allInterfaces = new HashSet<ProxyType>();
        getAllInterfaces(allInterfaces, interfaces);

        for (ProxyType ifcType : allInterfaces) {
            try {
                methodsCompiler.addMethods(Class.forName(ifcType.getClassName()), true);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Cannot find class " + ifcType.getClassName());
            }
        }
    }

    boolean defaultProxy = false;
    if (clazz.isInterface())
        defaultProxy = true;
    else {
        for (Class tmp = clazz; tmp != null; tmp = tmp.getSuperclass()) {
            if (factoryMethod == null) {
                for (Method method : tmp.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(FactoryMethod.class)) {
                        if (!Modifier.isStatic(method.getModifiers()))
                            throw new IllegalStateException("Cannot use method " + method
                                    + " as FactoryMethod because it is not static");
                        factoryMethod = method;
                        method.setAccessible(true);
                        break;
                    }
                }
            }
            if (tmp.isAnnotationPresent(AlwaysProxy.class)) {
                defaultProxy = true;
                break;
            } else if (tmp.isAnnotationPresent(ExplicitProxyOnly.class)) {
                break;
            }
        }
    }

    // If the class does not have any proxied interfaces or the class is marked with
    //   the AlwaysProxy annotation, then we take methods from the class definition
    methodsCompiler.addMethods(clazz, defaultProxy);

    methodsCompiler.checkValid();
    methodsCompiler.removeSuperTypeMethods();

    // Load properties
    HashMap<String, ProxyEvent> events = new HashMap<String, ProxyEvent>();
    HashMap<String, ProxyProperty> properties = new HashMap<String, ProxyProperty>();
    Properties annoProperties = (Properties) clazz.getAnnotation(Properties.class);
    if (annoProperties != null) {
        for (Property anno : annoProperties.value()) {
            ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }
    for (Field field : clazz.getDeclaredFields()) {
        Property anno = field.getAnnotation(Property.class);
        if (anno != null) {
            ProxyProperty property = new ProxyPropertyImpl(clazz,
                    anno.value().length() > 0 ? anno.value() : field.getName(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }

    for (Method method : clazz.getDeclaredMethods()) {
        String name = method.getName();
        if (name.length() < 4 || !name.startsWith("get") || !Character.isUpperCase(name.charAt(3)))
            continue;
        Property anno = method.getAnnotation(Property.class);
        if (anno == null)
            continue;

        name = Character.toLowerCase(name.charAt(3)) + name.substring(4);
        if (properties.containsKey(name))
            continue;

        ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : name,
                anno, annoProperties);
        properties.put(property.getName(), property);
        ProxyEvent event = property.getEvent();
        if (event != null)
            events.put(event.getName(), event);
    }

    // Classes need to have all inherited properties added
    if (!clazz.isInterface()) {
        for (ProxyType ifc : interfaces)
            addProperties((ProxyTypeImpl) ifc, properties);
    }

    // Remove property accessors
    for (ProxyProperty prop : properties.values())
        methodsCompiler.removePropertyAccessors((ProxyPropertyImpl) prop);

    // Load events
    if (clazz.isAnnotationPresent(Events.class)) {
        Events annoEvents = (Events) clazz.getAnnotation(Events.class);
        for (Event annoEvent : annoEvents.value()) {
            if (!events.containsKey(annoEvent.value()))
                events.put(annoEvent.value(), new ProxyEvent(annoEvent));
        }
    }

    // Classes need to have all inherited events added
    if (!clazz.isInterface()) {
        for (ProxyType type : interfaces)
            addEvents((ProxyTypeImpl) type, events);
    }

    // Save
    this.properties = properties.isEmpty() ? null : properties;
    this.events = events.isEmpty() ? null : events;
    this.methods = methodsCompiler.toArray();
}

From source file:com.blackducksoftware.tools.nrt.ProtexNoticeReportProcessor.java

/**
 * Gets protex elements//  w w  w  .jav a 2  s.co  m
 * 
 * @return
 * @throws Exception
 */
@Override
public HashMap<String, ComponentModel> processProject(String protexProjectName) throws Exception {
    Map<String, StringSearchPattern> patternMap = null;
    HashMap<String, ComponentModel> componentMappings = new HashMap<String, ComponentModel>();

    if (protexProjectName == null) {
        protexProjectName = nrtConfigManager.getProjectName();
    }

    ProjectPojo protexProject = protexWrapper.getProjectByName(protexProjectName);

    if (protexProject == null) {
        throw new Exception("Unable to find project with name: " + protexProjectName);
    }

    String projectId = protexProject.getProjectKey();

    HashMap<String, Set<String>> componentToPathMappings = new HashMap<String, Set<String>>();

    log.info("Getting Components by Project");

    List<ComponentModel> protexComponents = protexWrapper.getProjectManager()
            .getComponentsByProjectId(ComponentModel.class, projectId);

    if (nrtConfigManager.isShowFilePaths() || nrtConfigManager.isIncludeLicenseFilenamesInReport()) {
        componentToPathMappings = getMappings(protexProject);

        patternMap = buildPatternMap();
    }

    for (ComponentModel protexComp : protexComponents) {

        // Build name version pair key so that we can look up the component from the identified files report
        String versionName = protexComp.getVersion();
        if (versionName == null) {
            versionName = NRTConstants.DEFAULT_VERSION;
        }
        String nameVersionPair = protexComp.getName() + ":" + versionName;

        try {

            Set<String> paths = componentToPathMappings.get(nameVersionPair);
            if (paths == null) {
                // This should never happen.
                log.error("Unable to find paths for component, no copyright information will be available for: "
                        + nameVersionPair);
                continue;

            }

            // Convert common framework licenses to licensemodels
            getLicensesForComponent(projectId, protexComp);

            // Load all the file paths
            getFilesPathsForComponent(protexComp, paths);

            // Load all the copyrights
            getCopyrightsForComponent(projectId, protexComp, patternMap);

        } catch (Exception e) {
            log.warn("Unable to get component information for id: " + nameVersionPair);
        }

        componentMappings.put(nameVersionPair, protexComp);
    }

    // Look into this later This adds user provided licenses
    if (nrtConfigManager.isIncludeLicenseFilenamesInReport()) {
        for (ComponentModel model : componentMappings.values()) {
            for (String licenseFilename : nrtConfigManager.getLicenseFilenames()) {
                Set<String> paths = model.getPaths();
                if (paths != null) {
                    for (String path : paths) {
                        if (FilenameUtils.getName(path).endsWith(licenseFilename)) {
                            String fileText = getFileText(projectId, path);
                            if (fileText != null) {
                                LicenseModel licenseModel = new LicenseModel();
                                licenseModel.setName(licenseFilename);
                                licenseModel.setId("custom_included_+" + licenseFilename);
                                licenseModel.setText(fileText);

                                model.addNewLicense(licenseModel);
                            }
                        }
                    }
                } else {
                    log.info("No paths for component: " + model.getNameAndVersion());
                }
            }
        }
    }

    return componentMappings;
}

From source file:com.wasteofplastic.askygrid.commands.Challenges.java

/**
 * Checks if a player has enough for a challenge. Supports two types of
 * checks, inventory and collect. Removes items if required.
 * /*from   w ww . j  a va 2 s. c om*/
 * @param player
 * @param challenge
 * @param type
 * @return true if the player has everything required
 */

public boolean hasRequired(final Player player, final String challenge, final String type) {
    // Check money
    double moneyReq = 0D;
    if (Settings.useEconomy) {
        moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney",
                0D);
        if (moneyReq > 0D) {
            if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems);
                String desc = ChatColor.translateAlternateColorCodes('&',
                        getChallengeConfig().getString("challenges.challengeList." + challenge + ".description")
                                .replace("[label]", Settings.ISLANDCOMMAND));
                List<String> result = new ArrayList<String>();
                if (desc.contains("|")) {
                    result.addAll(Arrays.asList(desc.split("\\|")));
                } else {
                    result.add(desc);
                }
                for (String line : result) {
                    player.sendMessage(ChatColor.RED + line);
                }
                return false;
            }
        }
    }
    final String[] reqList = getChallengeConfig()
            .getString("challenges.challengeList." + challenge + ".requiredItems").split(" ");
    // The format of the requiredItems is as follows:
    // Material:Qty
    // or
    // Material:DamageModifier:Qty
    // This second one is so that items such as potions or variations on
    // standard items can be collected
    if (type.equalsIgnoreCase("inventory")) {
        List<ItemStack> toBeRemoved = new ArrayList<ItemStack>();
        Material reqItem;
        int reqAmount = 0;
        for (final String s : reqList) {
            final String[] part = s.split(":");
            // Material:Qty
            if (part.length == 2) {
                try {
                    // Correct some common mistakes
                    if (part[0].equalsIgnoreCase("potato")) {
                        part[0] = "POTATO_ITEM";
                    } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                        part[0] = "BREWING_STAND_ITEM";
                    } else if (part[0].equalsIgnoreCase("carrot")) {
                        part[0] = "CARROT_ITEM";
                    } else if (part[0].equalsIgnoreCase("cauldron")) {
                        part[0] = "CAULDRON_ITEM";
                    } else if (part[0].equalsIgnoreCase("skull")) {
                        part[0] = "SKULL_ITEM";
                    }
                    // TODO: add netherwart vs. netherstalk?
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[1]);
                    ItemStack item = new ItemStack(reqItem);
                    // plugin.getLogger().info("DEBUG: required item = " +
                    // reqItem.toString());
                    // plugin.getLogger().info("DEBUG: item amount = " +
                    // reqAmount);

                    if (!player.getInventory().contains(reqItem)) {
                        return false;
                    } else {
                        // check amount
                        int amount = 0;
                        // plugin.getLogger().info("DEBUG: Amount in inventory = "
                        // + player.getInventory().all(reqItem).size());
                        // Go through all the inventory and try to find
                        // enough required items
                        for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem)
                                .entrySet()) {
                            // Get the item
                            ItemStack i = en.getValue();
                            // If the item is enchanted, skip - it doesn't count
                            if (i.hasItemMeta()) {
                                continue;
                            }
                            // Map needs special handling because the
                            // durability increments every time a new one is
                            // made by the player
                            // TODO: if there are any other items that act
                            // in the same way, they need adding too...
                            if (i.getDurability() == 0
                                    || (reqItem == Material.MAP && i.getType() == Material.MAP)) {
                                // Clear any naming, or lore etc.
                                //i.setItemMeta(null);
                                //player.getInventory().setItem(en.getKey(), i);
                                // #1 item stack qty + amount is less than
                                // required items - take all i
                                // #2 item stack qty + amount = required
                                // item -
                                // take all
                                // #3 item stack qty + amount > req items -
                                // take
                                // portion of i
                                // amount += i.getAmount();
                                if ((amount + i.getAmount()) < reqAmount) {
                                    // Remove all of this item stack - clone
                                    // otherwise it will keep a reference to
                                    // the
                                    // original
                                    toBeRemoved.add(i.clone());
                                    amount += i.getAmount();
                                    // plugin.getLogger().info("DEBUG: amount is <= req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());
                                } else if ((amount + i.getAmount()) == reqAmount) {
                                    // plugin.getLogger().info("DEBUG: amount is = req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());
                                    toBeRemoved.add(i.clone());
                                    amount += i.getAmount();
                                    break;
                                } else {
                                    // Remove a portion of this item
                                    // plugin.getLogger().info("DEBUG: amount is > req Remove "
                                    // + i.toString() + ":" +
                                    // i.getDurability() + " x " +
                                    // i.getAmount());

                                    item.setAmount(reqAmount - amount);
                                    item.setDurability(i.getDurability());
                                    toBeRemoved.add(item);
                                    amount += i.getAmount();
                                    break;
                                }
                            }
                        }
                        // plugin.getLogger().info("DEBUG: amount "+
                        // amount);
                        if (amount < reqAmount) {
                            return false;
                        }
                    }
                } catch (Exception e) {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    player.sendMessage(
                            ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                    String materialList = "";
                    boolean hint = false;
                    for (Material m : Material.values()) {
                        materialList += m.toString() + ",";
                        if (m.toString().contains(s.substring(0, 3).toUpperCase())) {
                            plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                            hint = true;
                        }
                    }
                    if (!hint) {
                        plugin.getLogger()
                                .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:");
                        plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                    } else {
                        plugin.getLogger().severe("Correct challenges.yml with the correct material.");
                    }
                    return false;
                }
            } else if (part.length == 3) {
                // This handles items with durability
                // Correct some common mistakes
                if (part[0].equalsIgnoreCase("potato")) {
                    part[0] = "POTATO_ITEM";
                } else if (part[0].equalsIgnoreCase("brewing_stand")) {
                    part[0] = "BREWING_STAND_ITEM";
                } else if (part[0].equalsIgnoreCase("carrot")) {
                    part[0] = "CARROT_ITEM";
                } else if (part[0].equalsIgnoreCase("cauldron")) {
                    part[0] = "CAULDRON_ITEM";
                } else if (part[0].equalsIgnoreCase("skull")) {
                    part[0] = "SKULL_ITEM";
                }
                if (StringUtils.isNumeric(part[0])) {
                    reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                } else {
                    reqItem = Material.getMaterial(part[0].toUpperCase());
                }
                reqAmount = Integer.parseInt(part[2]);
                int reqDurability = Integer.parseInt(part[1]);
                ItemStack item = new ItemStack(reqItem);

                // Item
                item.setDurability((short) reqDurability);
                // check amount
                int amount = 0;
                // Go through all the inventory and try to find
                // enough required items
                for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem).entrySet()) {
                    // Get the item
                    ItemStack i = en.getValue();
                    if (i.hasItemMeta()) {
                        continue;
                    }
                    if (i.getDurability() == reqDurability) {
                        // Clear any naming, or lore etc.
                        //i.setItemMeta(null);
                        // player.getInventory().setItem(en.getKey(), i);
                        // #1 item stack qty + amount is less than
                        // required items - take all i
                        // #2 item stack qty + amount = required
                        // item -
                        // take all
                        // #3 item stack qty + amount > req items -
                        // take
                        // portion of i
                        // amount += i.getAmount();
                        if ((amount + i.getAmount()) < reqAmount) {
                            // Remove all of this item stack - clone
                            // otherwise it will keep a reference to
                            // the
                            // original
                            toBeRemoved.add(i.clone());
                            amount += i.getAmount();
                            // plugin.getLogger().info("DEBUG: amount is <= req Remove "
                            // + i.toString() + ":" +
                            // i.getDurability()
                            // + " x " + i.getAmount());
                        } else if ((amount + i.getAmount()) == reqAmount) {
                            toBeRemoved.add(i.clone());
                            amount += i.getAmount();
                            break;
                        } else {
                            // Remove a portion of this item
                            // plugin.getLogger().info("DEBUG: amount is > req Remove "
                            // + i.toString() + ":" +
                            // i.getDurability()
                            // + " x " + i.getAmount());

                            item.setAmount(reqAmount - amount);
                            item.setDurability(i.getDurability());
                            toBeRemoved.add(item);
                            amount += i.getAmount();
                            break;
                        }
                    }
                }
                // plugin.getLogger().info("DEBUG: amount is " +
                // amount);
                // plugin.getLogger().info("DEBUG: req amount is " +
                // reqAmount);
                if (amount < reqAmount) {
                    return false;
                }

                // plugin.getLogger().info("DEBUG: before set amount " +
                // item.toString() + ":" + item.getDurability() + " x "
                // + item.getAmount());
                // item.setAmount(reqAmount);
                // plugin.getLogger().info("DEBUG: after set amount " +
                // item.toString() + ":" + item.getDurability() + " x "
                // + item.getAmount());
                // toBeRemoved.add(item);

            } else if (part.length == 6 && part[0].contains("POTION")) {
                // Run through player's inventory for the item
                ItemStack[] playerInv = player.getInventory().getContents();
                try {
                    reqAmount = Integer.parseInt(part[5]);
                    //plugin.getLogger().info("DEBUG: required amount is " + reqAmount);
                } catch (Exception e) {
                    plugin.getLogger().severe("Could not parse the quantity of the potion item " + s);
                    return false;
                }
                int count = reqAmount;
                for (ItemStack i : playerInv) {
                    // Catches all POTION, LINGERING_POTION and SPLASH_POTION
                    if (i != null && i.getType().toString().contains("POTION")) {
                        //plugin.getLogger().info("DEBUG:6 part potion check!");
                        // POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY
                        if (plugin.getServer().getVersion().contains("(MC: 1.8")
                                || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                            // Test potion
                            Potion potion = Potion.fromItemStack(i);
                            PotionType potionType = potion.getType();
                            boolean match = true;
                            // plugin.getLogger().info("DEBUG: name check " + part[1]);
                            // Name check
                            if (!part[1].isEmpty()) {
                                // There is a name
                                if (PotionType.valueOf(part[1]) != null) {
                                    if (!potionType.name().equalsIgnoreCase(part[1])) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: name does not match");
                                    } else {
                                        // plugin.getLogger().info("DEBUG: name matches");
                                    }
                                } else {
                                    plugin.getLogger()
                                            .severe("Potion type is unknown. Please pick from the following:");
                                    for (PotionType pt : PotionType.values()) {
                                        plugin.getLogger().severe(pt.name());
                                    }
                                    match = false;
                                }
                            }
                            // Level check (upgraded)
                            // plugin.getLogger().info("DEBUG: level check " + part[2]);
                            if (!part[2].isEmpty()) {
                                // There is a level declared - check it
                                if (StringUtils.isNumeric(part[2])) {
                                    int level = Integer.valueOf(part[2]);
                                    if (level != potion.getLevel()) {
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                        match = false;
                                    }
                                }
                            }
                            // Extended check
                            // plugin.getLogger().info("DEBUG: extended check " + part[3]);
                            if (!part[3].isEmpty()) {
                                if (part[3].equalsIgnoreCase("EXTENDED") && !potion.hasExtendedDuration()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                                if (part[3].equalsIgnoreCase("NOTEXTENDED") && potion.hasExtendedDuration()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                            }
                            // Splash check
                            // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                            if (!part[4].isEmpty()) {
                                if (part[4].equalsIgnoreCase("SPLASH") && !potion.isSplash()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not splash");
                                }
                                if (part[4].equalsIgnoreCase("NOSPLASH") && potion.isSplash()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no splash");
                                }
                            }
                            // Quantity check
                            if (match) {
                                // plugin.getLogger().info("DEBUG: potion matches!");
                                ItemStack removeItem = i.clone();
                                if (removeItem.getAmount() > reqAmount) {
                                    // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                    removeItem.setAmount(reqAmount);
                                }
                                count = count - removeItem.getAmount();
                                // plugin.getLogger().info("DEBUG: " + count + " left");
                                toBeRemoved.add(removeItem);
                            }
                        } else {
                            // V1.9 and above
                            PotionMeta potionMeta = (PotionMeta) i.getItemMeta();
                            // If any of the settings above are missing, then any is okay
                            boolean match = true;
                            // plugin.getLogger().info("DEBUG: name check " + part[1]);
                            // Name check
                            if (!part[1].isEmpty()) {
                                // There is a name
                                if (PotionType.valueOf(part[1]) != null) {
                                    if (!potionMeta.getBasePotionData().getType().name()
                                            .equalsIgnoreCase(part[1])) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: name does not match");
                                    } else {
                                        // plugin.getLogger().info("DEBUG: name matches");
                                    }
                                } else {
                                    plugin.getLogger()
                                            .severe("Potion type is unknown. Please pick from the following:");
                                    for (PotionType pt : PotionType.values()) {
                                        plugin.getLogger().severe(pt.name());
                                    }
                                    match = false;
                                }
                            }
                            // Level check (upgraded)
                            // plugin.getLogger().info("DEBUG: level check " + part[2]);
                            if (!part[2].isEmpty()) {
                                // There is a level declared - check it
                                if (StringUtils.isNumeric(part[2])) {
                                    int level = Integer.valueOf(part[2]);
                                    if (level == 1 && potionMeta.getBasePotionData().isUpgraded()) {
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                        match = false;
                                    }
                                    if (level != 1 && !potionMeta.getBasePotionData().isUpgraded()) {
                                        match = false;
                                        // plugin.getLogger().info("DEBUG: level does not match");
                                    }
                                }
                            }
                            // Extended check
                            // plugin.getLogger().info("DEBUG: extended check " + part[3]);
                            if (!part[3].isEmpty()) {
                                if (part[3].equalsIgnoreCase("EXTENDED")
                                        && !potionMeta.getBasePotionData().isExtended()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                                if (part[3].equalsIgnoreCase("NOTEXTENDED")
                                        && potionMeta.getBasePotionData().isExtended()) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: extended does not match");
                                }
                            }
                            // Splash or Linger check
                            // plugin.getLogger().info("DEBUG: splash/linger check " + part[4]);
                            if (!part[4].isEmpty()) {
                                if (part[4].equalsIgnoreCase("SPLASH")
                                        && !i.getType().equals(Material.SPLASH_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not splash");
                                }
                                if (part[4].equalsIgnoreCase("NOSPLASH")
                                        && i.getType().equals(Material.SPLASH_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no splash");
                                }
                                if (part[4].equalsIgnoreCase("LINGER")
                                        && !i.getType().equals(Material.LINGERING_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not linger");
                                }
                                if (part[4].equalsIgnoreCase("NOLINGER")
                                        && i.getType().equals(Material.LINGERING_POTION)) {
                                    match = false;
                                    // plugin.getLogger().info("DEBUG: not no linger");
                                }
                            }
                            // Quantity check
                            if (match) {
                                // plugin.getLogger().info("DEBUG: potion matches!");
                                ItemStack removeItem = i.clone();
                                if (removeItem.getAmount() > reqAmount) {
                                    // plugin.getLogger().info("DEBUG: found " + removeItem.getAmount() + " qty in inv");
                                    removeItem.setAmount(reqAmount);
                                }
                                count = count - removeItem.getAmount();
                                // plugin.getLogger().info("DEBUG: " + count + " left");
                                toBeRemoved.add(removeItem);
                            }
                        }
                    }
                    if (count <= 0) {
                        // plugin.getLogger().info("DEBUG: Player has enough");
                        break;
                    }
                    // plugin.getLogger().info("DEBUG: still need " + count + " to complete");
                }
                if (count > 0) {
                    // plugin.getLogger().info("DEBUG: Player does not have enough");
                    return false;
                }

            } else {
                plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                return false;
            }
        }
        // Build up the items in the inventory and remove them if they are
        // all there.

        if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) {
            // checkChallengeItems(player, challenge);
            // int qty = 0;
            // plugin.getLogger().info("DEBUG: Removing items");
            for (ItemStack i : toBeRemoved) {
                // qty += i.getAmount();
                // plugin.getLogger().info("DEBUG: Remove " + i.toString() +
                // "::" + i.getDurability() + " x " + i.getAmount());
                HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i);
                if (!leftOver.isEmpty()) {
                    plugin.getLogger().warning("Exploit? Could not remove the following in challenge "
                            + challenge + " for player " + player.getName() + ":");
                    for (ItemStack left : leftOver.values()) {
                        plugin.getLogger().info(left.toString());
                    }
                    return false;
                }
            }
            // Remove money
            if (moneyReq > 0D) {
                EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq);
                if (!er.transactionSuccess()) {
                    plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq)
                            + " from " + player.getName() + " in challenge " + challenge);
                    plugin.getLogger().warning("Player's balance is "
                            + VaultHelper.econ.format(VaultHelper.econ.getBalance(player)));
                }
            }
            // plugin.getLogger().info("DEBUG: total = " + qty);
        }
        return true;
    }
    if (type.equalsIgnoreCase("collect")) {
        final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>();
        final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>();
        for (int i = 0; i < reqList.length; i++) {
            final String[] sPart = reqList[i].split(":");
            // Parse the qty required first
            try {
                final int qty = Integer.parseInt(sPart[1]);
                // Find out if the needed item is a Material or an Entity
                boolean isEntity = false;
                for (EntityType entityType : EntityType.values()) {
                    if (entityType.toString().equalsIgnoreCase(sPart[0])) {
                        isEntity = true;
                        break;
                    }
                }
                if (isEntity) {
                    // plugin.getLogger().info("DEBUG: Item " +
                    // sPart[0].toUpperCase() + " is an entity");
                    EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase());
                    if (entityType != null) {
                        neededEntities.put(entityType, qty);
                        // plugin.getLogger().info("DEBUG: Needed entity is "
                        // + Integer.parseInt(sPart[1]) + " x " +
                        // EntityType.valueOf(sPart[0].toUpperCase()).toString());
                    }
                } else {
                    Material item;
                    if (StringUtils.isNumeric(sPart[0])) {
                        item = Material.getMaterial(Integer.parseInt(sPart[0]));
                    } else {
                        item = Material.getMaterial(sPart[0].toUpperCase());
                    }
                    if (item != null) {
                        neededItem.put(item, qty);
                        // plugin.getLogger().info("DEBUG: Needed item is "
                        // + Integer.parseInt(sPart[1]) + " x " +
                        // Material.getMaterial(sPart[0]).toString());

                    } else {
                        plugin.getLogger().warning("Problem parsing required item for challenge " + challenge
                                + " in challenges.yml!");
                        return false;
                    }
                }
            } catch (Exception intEx) {
                plugin.getLogger().warning("Problem parsing required items for challenge " + challenge
                        + " in challenges.yml - skipping");
                return false;
            }

        }
        // We now have two sets of required items or entities
        // Check the items first
        final Location l = player.getLocation();
        // if (!neededItem.isEmpty()) {
        final int px = l.getBlockX();
        final int py = l.getBlockY();
        final int pz = l.getBlockZ();
        // Get search radius - min is 10, max is 50
        int searchRadius = getChallengeConfig()
                .getInt("challenges.challengeList." + challenge + ".searchRadius", 10);
        if (searchRadius < 10) {
            searchRadius = 10;
        } else if (searchRadius > 50) {
            searchRadius = 50;
        }
        for (int x = -searchRadius; x <= searchRadius; x++) {
            for (int y = -searchRadius; y <= searchRadius; y++) {
                for (int z = -searchRadius; z <= searchRadius; z++) {
                    final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType();
                    if (neededItem.containsKey(b)) {
                        if (neededItem.get(b) == 1) {
                            neededItem.remove(b);
                        } else {
                            // Reduce the require amount by 1
                            neededItem.put(b, neededItem.get(b) - 1);
                        }
                    }
                }
            }
        }
        // }
        // Check if all the needed items have been amassed
        if (!neededItem.isEmpty()) {
            // plugin.getLogger().info("DEBUG: Insufficient items around");
            for (Material missing : neededItem.keySet()) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                                + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString()));
            }
            return false;
        } else {
            // plugin.getLogger().info("DEBUG: Items are there");
            // Check for needed entities
            for (Entity entity : player.getNearbyEntities(searchRadius, searchRadius, searchRadius)) {
                // plugin.getLogger().info("DEBUG: Entity found:" +
                // entity.getType().toString());
                if (neededEntities.containsKey(entity.getType())) {
                    // plugin.getLogger().info("DEBUG: Entity in list");
                    if (neededEntities.get(entity.getType()) == 1) {
                        neededEntities.remove(entity.getType());
                        // plugin.getLogger().info("DEBUG: Entity qty satisfied");
                    } else {
                        neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1);
                        // plugin.getLogger().info("DEBUG: Entity qty reduced by 1");
                    }
                } else {
                    // plugin.getLogger().info("DEBUG: Entity not in list");
                }
            }
            if (neededEntities.isEmpty()) {
                return true;
            } else {
                for (EntityType missing : neededEntities.keySet()) {
                    player.sendMessage(ChatColor.RED
                            + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " "
                            + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString()));
                }
                return false;
            }
        }
    }

    return true;
}

From source file:com.samples.platform.core.security.UserProvider.java

/**
 * Read the user definitions out of the properties and put the into the map
 * {@link UserProvider#userMap}.//from   w ww . j a  v a 2s .c o m
 */
public void createUsers() {
    this.logger.trace("+createUsers");
    /* Create an _sorted_ map containing all user definition properties. */
    TreeMap<String, String> userDefinitionProperties = new TreeMap<String, String>();
    for (Map.Entry<String, String> entry : this.properties.getProperties().entrySet()) {
        if (entry.getKey() != null && entry.getKey().startsWith(BUS_PROPERTY_NAME_START)) {
            userDefinitionProperties.put(entry.getKey(), entry.getValue());
        }
    }

    /* Create a map of UserDefinitions parsed out of the properties. */
    HashMap<String, UserDefinition> parsedUserDefinitions = new HashMap<String, UserProvider.UserDefinition>();
    UserDefinition userDefinition = null;
    String userKey = null;
    for (Map.Entry<String, String> userDefinitionProperty : userDefinitionProperties.entrySet()) {
        /* Get the user key out of the property name. */
        userKey = extractUser(userDefinitionProperty.getKey());
        if (userDefinition == null || !userDefinition.getKey().equals(userKey)) {
            /* New user key extracted out of the property name. */
            if (userDefinition != null) {
                /* Previous UserDefinition finished. Put it into the map. */
                parsedUserDefinitions.put(userDefinition.getName(), userDefinition);
            }
            /* Create the actual UserDefinition with the user key. */
            userDefinition = new UserDefinition(userKey);
        }
        /* Setup the content of the property into the UserDefinition. */
        if (userDefinitionProperty.getKey().endsWith("userName")) {
            userDefinition.setName(userDefinitionProperty.getValue());
        } else if (userDefinitionProperty.getKey().endsWith("password")) {
            userDefinition.setPassword(userDefinitionProperty.getValue());
        } else if (userDefinitionProperty.getKey().contains(".role.")) {
            if (userDefinitionProperty.getValue() != null
                    && !userDefinitionProperty.getValue().equals(ROLE_ANONYMOUS)) {
                userDefinition.addRolename(userDefinitionProperty.getValue());
            }
        }
    }
    /* Put the last UserDefinition to the map of parsedUserDefinitions. */
    if (userDefinition != null && userDefinition.getName() != null) {
        parsedUserDefinitions.put(userDefinition.getName(), userDefinition);
    }

    /*
     * Update the userMap. If the userName of the userMap is not part of the
     * parsedUserDefinitions any more, the user is removed out of the
     * userMap.
     */
    List<String> keyList = new ArrayList<String>(this.userMap.size());
    Collections.addAll(keyList, this.userMap.keySet().toArray(new String[this.userMap.keySet().size()]));
    for (String userName : keyList) {
        userDefinition = parsedUserDefinitions.get(userName);
        if (!parsedUserDefinitions.containsKey(userName)) {
            this.userMap.remove(userName);
        }
    }
    /*
     * All UserDefinitions out of the parsedUserDefinitions are mapped to a
     * User and put into the userMap.
     */
    for (UserDefinition ud : parsedUserDefinitions.values()) {
        this.userMap.put(ud.getName(), this.getUser(ud));
    }
    this.logger.trace("-createUsers");
}

From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java

/**
 * Read XML from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write.//from  w  w w .j a  va  2s .  c  o m
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException,
        XmlPullParserException, RemoteException, OperationApplicationException, ParseException {

    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as Atom feed");
    final List<Transformer> entries = null;
    /*=this.parseTransformersResponse(stream)*/;
    ;
    Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries");

    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Build hash table of incoming entries
    HashMap<String, Transformer> entryMap = new HashMap<String, Transformer>();
    for (Transformer e : entries) {
        entryMap.put(e.transformerID, e);
    }
    Cursor c = null;

    try {

        // Get list of all items
        Log.i(TAG, "Fetching local entries for merge");
        Uri uri = Transformer.CONTENT_URI; // Get all entries
        c = contentResolver.query(uri, null, null, null, null);
        assert c != null;
        Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");
    }

    catch (Exception ex) {

    }
    // Find stale data
    String id;
    String name;
    String location;

    while (c.moveToNext()) {
        syncResult.stats.numEntries++;

        id = c.getColumnName(COLUMN_ID);
        name = c.getString(COLUMN_ENTRY_ID);
        location = c.getString(COLUMN_TITLE);

        Transformer match = entryMap.get(id);
        if (match != null) {
            // Entry exists. Remove from entry map to prevent insert later.
            entryMap.remove(id);
            // Check to see if the entry needs to be updated
            Uri existingUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build();
            if ((match.trsName != null && !match.trsLocation.equals(name))) {
                // Update existing record
                Log.i(TAG, "Scheduling update: " + existingUri);
                batch.add(ContentProviderOperation.newUpdate(existingUri).withValue(Transformer.KEY_NAME, name)
                        .withValue(Transformer.KEY_LOCATION, location)

                        .build());
                syncResult.stats.numUpdates++;
            } else {
                Log.i(TAG, "No action: " + existingUri);
            }
        } else {
            // Entry doesn't exist. Remove it from the database.
            Uri deleteUri = Transformer.CONTENT_URI.buildUpon().appendPath(id).build();
            Log.i(TAG, "Scheduling delete: " + deleteUri);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            syncResult.stats.numDeletes++;
        }
    }
    c.close();

    // Add new items
    for (Transformer e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.transformerID);
        batch.add(ContentProviderOperation.newInsert(Transformer.CONTENT_URI)
                .withValue(Transformer.KEY_TRANSFORMER_ID, e.transformerID)
                .withValue(Transformer.KEY_NAME, e.trsName).withValue(Transformer.KEY_LOCATION, e.trsLocation)
                .withValue(Transformer.KEY_CURRENT_TEMP, e.trsCurrentTemp)
                .withValue(Transformer.KEY_LAST_SERVER_SYNC_DATE, e.lastServerSyncDate)
                .withValue(Transformer.KEY_LAST_UPDATED_TIME, e.lastServerSyncDate)
                .withValue(Transformer.KEY_SYNC_STATUS, 0).withValue(Transformer.KEY_MAKE, e.trsMake)
                .withValue(Transformer.KEY_WINDING_MAKE, e.trsWindingMake)
                .withValue(Transformer.KEY_WINDING_COUNT, e.trsWindingCount)
                .withValue(Transformer.KEY_OIL_LEVEL, e.trsOilLevel)
                .withValue(Transformer.KEY_OPERATING_POWER, e.trsOperatingPower)
                .withValue(Transformer.KEY_TYPE, e.trsType)

                .build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(Transformer.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(Transformer.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

From source file:org.apache.stratos.usage.api.TenantUsageRetriever.java

public BandwidthStatistics[][] getBandwidthStatistics(int tenantId, Calendar startDate, Calendar endDate,
        boolean currentMonth) throws Exception {
    //return the bandwidth usage of a user for a given period
    BandwidthStatistics[] stats;//from  www  .  j a  v  a 2 s  .c  om
    if (currentMonth) {
        //get from daily usage stats
        List<BandwidthStatistics> bwsList = new ArrayList<BandwidthStatistics>();
        bwsList = dao.getDailyBandwidthStats(tenantId, startDate, endDate);

        //next we'll get from the houlry stats to get the stats which are not yet
        //summarized to the daily stats table
        Calendar startHour = Calendar.getInstance();
        startHour.set(Calendar.HOUR, 0);
        startHour.set(Calendar.MINUTE, 0);
        startHour.set(Calendar.SECOND, 0);

        Calendar endHour = Calendar.getInstance();

        bwsList.addAll(dao.getHourlyBandwidthStats(tenantId, startHour, endHour));
        stats = convertBWListToArray(bwsList);

    } else {
        //get from monthly usage stats
        Calendar monthCal = (Calendar) endDate.clone();
        monthCal.set(Calendar.DATE, 0);
        monthCal.set(Calendar.HOUR, 0);
        monthCal.set(Calendar.MINUTE, 0);
        monthCal.set(Calendar.SECOND, 0);

        stats = convertBWListToArray(dao.getMonthlyBandwidthStats(tenantId, monthCal));
    }

    // store the statistics in a temporary map. This is because, we are getting the server name
    // from the URL and there might be two distinct URL gives same server name.
    // For example, http://esb.a.b/ and http://esb.c.d/ both will give the server name as "esb"
    // Hence, the value should be accumulated value
    HashMap<String, BandwidthStatistics> regBwMap = new HashMap<String, BandwidthStatistics>();
    HashMap<String, BandwidthStatistics> svcBwMap = new HashMap<String, BandwidthStatistics>();
    HashMap<String, BandwidthStatistics> webappBwMap = new HashMap<String, BandwidthStatistics>();

    if (stats != null) {
        for (BandwidthStatistics stat : stats) {
            //Proceed only if incoming bandwidth or outgoing bandwidth is not zero
            if (stat.getIncomingBandwidth() == 0 && stat.getOutgoingBandwidth() == 0) {
                continue;
            }

            //TODO: fix the extractServiceUrl method properly
            String serverName = extractServiceNameFromUrl(stat.getServerUrl());
            String bandwidthName = stat.getKey();

            HashMap<String, BandwidthStatistics> bwMap;
            if (bandwidthName.equals(UsageConstants.REGISTRY_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.REGISTRY_OUTGOING_BW)) {
                bwMap = regBwMap;
            } else if (bandwidthName.equals(UsageConstants.SERVICE_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.SERVICE_OUTGOING_BW)) {
                bwMap = svcBwMap;
            } else if (bandwidthName.equals(UsageConstants.WEBAPP_INCOMING_BW)
                    || bandwidthName.equals(UsageConstants.WEBAPP_OUTGOING_BW)) {
                bwMap = webappBwMap;
            } else {
                log.warn("Unable to identify bandwidth name " + bandwidthName);
                continue;
            }

            //find whether the map already has this key; If not, insert a new one
            BandwidthStatistics reqStat = bwMap.get(serverName);
            if (reqStat == null) {
                reqStat = new BandwidthStatistics(serverName);
                bwMap.put(serverName, reqStat);
            }

            // Update the service specific statistics
            reqStat.setIncomingBandwidth(reqStat.getIncomingBandwidth() + stat.getIncomingBandwidth());
            reqStat.setOutgoingBandwidth(reqStat.getOutgoingBandwidth() + stat.getOutgoingBandwidth());
        }
    }

    //Convert to array and return it
    BandwidthStatistics[][] returnValue = new BandwidthStatistics[3][];
    Collection<BandwidthStatistics> values = regBwMap.values();
    returnValue[REG_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);
    values = svcBwMap.values();
    returnValue[SVC_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);
    values = webappBwMap.values();
    returnValue[WEBAPP_BANDWIDTH_INDEX] = values.toArray(new BandwidthStatistics[values.size()]);

    return returnValue;
}

From source file:servlets.Samples_servlets.java

private void send_biocondition_template_document_handler(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    try {//from   w  ww  .  ja v  a 2s.c om

        ArrayList<String> BLOCKED_IDs = new ArrayList<String>();
        boolean ROLLBACK_NEEDED = false;
        DAO dao_instance = null;

        try {
            if (!ServletFileUpload.isMultipartContent(request)) {
                throw new Exception("Erroneus request.");
            }

            String user_id = "";
            String sessionToken = "";
            File xls_file = null;

            /**
             * *******************************************************
             * STEP 1 Get the request params: read the params and the XLS
             * file. IF ERROR --> throws SQL Exception, GO TO STEP ? ELSE
             * --> GO TO STEP 9
             * *******************************************************
             */
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("text/html");

            //Get the data as a JSON format string
            final String CACHE_PATH = "/tmp/";
            final int CACHE_SIZE = 100 * (int) Math.pow(10, 6);
            final int MAX_REQUEST_SIZE = 20 * (int) Math.pow(10, 6);
            final int MAX_FILE_SIZE = 20 * (int) Math.pow(10, 6);

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // Set factory constraints
            factory.setRepository(new File(CACHE_PATH));
            factory.setSizeThreshold(CACHE_SIZE);

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // Set overall request size constraint
            upload.setSizeMax(MAX_REQUEST_SIZE);
            upload.setFileSizeMax(MAX_FILE_SIZE);

            // Parse the request
            List<FileItem> items = upload.parseRequest(request);

            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if (!item.getName().equals("")) {
                        //First check if the file already exists -> error, probably a previous treatmente exists with the same treatment_id
                        xls_file = new File(CACHE_PATH + "tmp.xls");
                        item.write(xls_file);
                    }
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if ("loggedUser".equals(name)) {
                        user_id = value;
                    } else if ("sessionToken".equals(name)) {
                        sessionToken = value;
                    }
                }
            }

            /**
             * *******************************************************
             * STEP 2 CHECK IF THE USER IS LOGGED CORRECTLY IN THE APP AND
             * IF FILE IS CORRECTLY UPDATED. IF ERROR --> throws exception
             * if not valid session, GO TO STEP 6b ELSE --> GO TO STEP 3
             * *******************************************************
             */
            if (!checkAccessPermissions(user_id, sessionToken)) {
                throw new AccessControlException("Your session is invalid. User or session token not allowed.");
            }
            if (xls_file == null) {
                throw new Exception("XLS file was not uploaded correctly.");
            }

            /**
             * *******************************************************
             * STEP 2 Parse the XLS file and get the information. IF ERROR
             * --> throws Exception, GO TO STEP ? ELSE --> GO TO STEP 3
             * *******************************************************
             */
            Object[] parsingResult = BioCondition_XLS_parser.parseXLSfile(xls_file, user_id);

            ArrayList<BioCondition> biocondition_list = (ArrayList<BioCondition>) parsingResult[0];
            HashMap<String, Batch> batchesTable = (HashMap<String, Batch>) parsingResult[1];
            HashMap<String, Protocol> protocolsTable = (HashMap<String, Protocol>) parsingResult[2];

            /**
             * *******************************************************
             * STEP 3 IF FILE WAS PARSED CORRECTLY ADD THE INFORMATION TO
             * DATABASE. IF ERROR --> throws SQLException, GO TO STEP ? ELSE
             * --> GO TO STEP 4
             * *******************************************************
             */
            dao_instance = DAOProvider.getDAOByName("Batch");
            dao_instance.disableAutocommit();
            ROLLBACK_NEEDED = true;

            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Batch batch : batchesTable.values()) {
                String batch_id = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(batch_id);
                batch.setBatchID(batch_id);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(batch);
            }

            dao_instance = DAOProvider.getDAOByName("Protocol");
            //IF WE ARE HERE IT MEANS THAT APARENTLY EVERTHING WAS OK
            //therefore WE SHOULD START ADDING THE INFORMATION INTO THE DB
            for (Protocol protocol : protocolsTable.values()) {
                String protocolID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(protocolID);
                protocol.setProtocolID(protocolID);
                //THE BATCH ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES (BECAUSE IS THE SAME OBJECT)
                dao_instance.insert(protocol);
            }

            dao_instance = DAOProvider.getDAOByName("BioCondition");

            for (BioCondition biocondition : biocondition_list) {
                String newID = dao_instance.getNextObjectID(null);
                BLOCKED_IDs.add(newID);
                biocondition.setBioConditionID(newID);
                //THE biocondition ID SHOULD BE UPDATED IN ALL THE BIOREPLICATES
                dao_instance.insert(biocondition);
            }

            /**
             * *******************************************************
             * STEP 4 COMMIT CHANGES TO DATABASE. throws SQLException IF
             * ERROR --> throws SQL Exception, GO TO STEP 5b ELSE --> GO TO
             * STEP 5
             * *******************************************************
             */
            dao_instance.doCommit();

        } catch (Exception e) {
            ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                    "send_biocondition_template_document_handler", e.getMessage());
        } finally {
            /**
             * *******************************************************
             * STEP 5b CATCH ERROR, CLEAN CHANGES. throws SQLException
             * *******************************************************
             */
            if (ServerErrorManager.errorStatus()) {
                response.setStatus(400);
                response.getWriter().print(ServerErrorManager.getErrorResponse());

                if (ROLLBACK_NEEDED) {
                    dao_instance.doRollback();
                }
            } else {
                response.getWriter().print("{success: " + true + "}");
            }

            for (String blocked_id : BLOCKED_IDs) {
                BlockedElementsManager.getBlockedElementsManager().unlockID(blocked_id);
            }

            /**
             * *******************************************************
             * STEP 6 Close connection.
             * ********************************************************
             */
            if (dao_instance != null) {
                dao_instance.closeConnection();
            }
        }
        //CATCH IF THE ERROR OCCURRED IN ROLL BACK OR CONNECTION CLOSE 
    } catch (Exception e) {
        ServerErrorManager.handleException(e, Samples_servlets.class.getName(),
                "send_xls_creation_document_handler", e.getMessage());
        response.setStatus(400);
        response.getWriter().print(ServerErrorManager.getErrorResponse());
    }
}