Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from   w ww  .j  a  v a 2s . co  m*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, File file) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(READ_OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            throw new ConnectionException("error", responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip, file, context);

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.apache.tika.parser.ner.NamedEntityParserTest.java

@Test
public void testParse() throws Exception {

    //test config is added to resources directory
    TikaConfig config = new TikaConfig(getClass().getResourceAsStream(CONFIG_FILE));
    Tika tika = new Tika(config);

    JSONParser parser = new JSONParser();
    String text = "";

    HashMap<Integer, String> hmap = new HashMap<Integer, String>();
    HashMap<String, HashMap<Integer, String>> outerhmap = new HashMap<String, HashMap<Integer, String>>();

    int index = 0;
    //Input Directory Path
    String inputDirPath = "/Users/AravindMac/Desktop/polardata_json_grobid/application_pdf";
    int count = 0;
    try {/*from  ww w. j  a  va 2s  . c o  m*/

        File root = new File(inputDirPath);
        File[] listDir = root.listFiles();
        for (File filename : listDir) {

            if (!filename.getName().equals(".DS_Store") && count < 3573) {
                count += 1;
                System.out.println(count);

                String absoluteFilename = filename.getAbsolutePath().toString();

                //   System.out.println(absoluteFilename);
                //Read the json file, parse and retrieve the text present in the content field.

                Object obj = parser.parse(new FileReader(absoluteFilename));

                BufferedWriter bw = new BufferedWriter(new FileWriter(new File(absoluteFilename)));

                JSONObject jsonObject = (JSONObject) obj;
                text = (String) jsonObject.get("content");

                Metadata md = new Metadata();
                tika.parse(new ByteArrayInputStream(text.getBytes()), md);

                //Parse the content and retrieve the values tagged as the NER entities
                HashSet<String> set = new HashSet<String>();
                set.addAll(Arrays.asList(md.getValues("X-Parsed-By")));

                // Store values tagged as NER_PERSON
                set.clear();
                set.addAll(Arrays.asList(md.getValues("NER_PERSON")));

                hmap = new HashMap<Integer, String>();
                index = 0;

                for (Iterator<String> i = set.iterator(); i.hasNext();) {
                    String f = i.next();
                    hmap.put(index, f);
                    index++;
                }

                if (!hmap.isEmpty()) {
                    outerhmap.put("PERSON", hmap);
                }

                // Store values tagged as NER_LOCATION
                set.clear();
                set.addAll(Arrays.asList(md.getValues("NER_LOCATION")));
                hmap = new HashMap<Integer, String>();
                index = 0;

                for (Iterator<String> i = set.iterator(); i.hasNext();) {
                    String f = i.next();
                    hmap.put(index, f);
                    index++;
                }

                if (!hmap.isEmpty()) {
                    outerhmap.put("LOCATION", hmap);
                }

                //Store values tagged as NER_ORGANIZATION
                set.clear();
                set.addAll(Arrays.asList(md.getValues("NER_ORGANIZATION")));

                hmap = new HashMap<Integer, String>();
                index = 0;

                for (Iterator<String> i = set.iterator(); i.hasNext();) {
                    String f = i.next();
                    hmap.put(index, f);
                    index++;
                }

                if (!hmap.isEmpty()) {
                    outerhmap.put("ORGANIZATION", hmap);
                }

                // Store values tagged as NER_DATE
                set.clear();
                set.addAll(Arrays.asList(md.getValues("NER_DATE")));

                hmap = new HashMap<Integer, String>();
                index = 0;

                for (Iterator<String> i = set.iterator(); i.hasNext();) {
                    String f = i.next();
                    hmap.put(index, f);
                    index++;
                }

                if (!hmap.isEmpty()) {
                    outerhmap.put("DATE", hmap);
                }

                JSONArray array = new JSONArray();
                array.put(outerhmap);
                if (!outerhmap.isEmpty()) {
                    jsonObject.put("OpenNLP", array); //Add the NER entities to the json under NER key as a JSON array.
                }

                System.out.println(jsonObject);

                bw.write(jsonObject.toJSONString()); //Stringify thr JSON and write it back to the file 
                bw.close();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.phicomm.account.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./* w w  w  .  j a va  2  s .c o  m*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    Thread.dumpStack();
    Log.i("ss", "NetworkConnectionImpl_____________________________________execute__urlValue:" + urlValue);
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (true) {
            Log.d(TAG, "Request url: " + urlValue);
            Log.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                Log.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    Log.d(TAG, message);
                }

                Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                Log.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                Log.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (true) {
            Log.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                Log.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

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

/**
 * Gives player the reward items. /*from   w  w  w  . j a  v a2 s.  co  m*/
 * @param player
 * @param itemRewards
 * @return List of ItemStacks that were given to the player or null if there was an error in the interpretation of the rewards
 */
private List<ItemStack> giveItems(Player player, String[] itemRewards) {
    List<ItemStack> rewardedItems = new ArrayList<ItemStack>();
    Material rewardItem;
    int rewardQty;
    // Build the item stack of rewards to give the player
    for (final String s : itemRewards) {
        final String[] element = s.split(":");
        if (element.length == 2) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[1]);
                ItemStack item = new ItemStack(rewardItem, rewardQty);
                rewardedItems.add(item);
                final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                        .addItem(new ItemStack[] { item });
                if (!leftOvers.isEmpty()) {
                    player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                }
                if (plugin.getServer().getVersion().contains("(MC: 1.8")
                        || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                    player.getWorld().playSound(player.getLocation(), Sound.valueOf("ITEM_PICKUP"), 1F, 1F);
                } else {
                    player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1F, 1F);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorRewardProblem);
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                String materialList = "";
                boolean hint = false;
                for (Material m : Material.values()) {
                    materialList += m.toString() + ",";
                    if (element[0].length() > 3) {
                        if (m.toString().startsWith(element[0].substring(0, 3))) {
                            plugin.getLogger().severe(
                                    "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                            hint = true;
                        }
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe(
                            "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                    plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                }
            }
        } else if (element.length == 3) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[2]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    givePotion(player, rewardedItems, element, rewardQty);
                } else {
                    ItemStack item = null;
                    // Normal item, not a potion, check if it is a Monster Egg
                    if (rewardItem.equals(Material.MONSTER_EGG)) {

                        try {
                            EntityType type = EntityType.valueOf(element[1].toUpperCase());
                            if (Bukkit.getServer().getVersion().contains("(MC: 1.8")
                                    || Bukkit.getServer().getVersion().contains("(MC: 1.7")) {
                                item = new SpawnEgg(type).toItemStack(rewardQty);
                            } else {
                                plugin.getLogger()
                                        .severe("Monster eggs not supported with this server version.");
                            }
                        } catch (Exception e) {
                            Bukkit.getLogger().severe(
                                    "Spawn eggs must be described by name. Try one of these (not all are possible):");
                            for (EntityType type : EntityType.values()) {
                                if (type.isSpawnable() && type.isAlive()) {
                                    plugin.getLogger().severe(type.toString());
                                }
                            }
                        }
                    } else {
                        int rewMod = Integer.parseInt(element[1]);
                        item = new ItemStack(rewardItem, rewardQty, (short) rewMod);
                    }
                    if (item != null) {
                        rewardedItems.add(item);
                        final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                                .addItem(new ItemStack[] { item });
                        if (!leftOvers.isEmpty()) {
                            player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                        }
                    }
                }
                if (plugin.getServer().getVersion().contains("(MC: 1.8")
                        || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                    player.getWorld().playSound(player.getLocation(), Sound.valueOf("ITEM_PICKUP"), 1F, 1F);
                } else {
                    player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1F, 1F);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                /*
                          if (element[0].equalsIgnoreCase("POTION")) {
                String potionList = "";
                boolean hint = false;
                for (PotionEffectType m : PotionEffectType.values()) {
                    potionList += m.toString() + ",";
                    if (element[1].length() > 3) {
                        if (m.toString().startsWith(element[1].substring(0, 3))) {
                            plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                            hint = true;
                        }
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe("Sorry, I have no idea what potion type " + element[1] + " is. Pick from one of these:");
                    plugin.getLogger().severe(potionList.substring(0, potionList.length() - 1));
                }
                        
                          } else {*/
                String materialList = "";
                boolean hint = false;
                for (Material m : Material.values()) {
                    materialList += m.toString() + ",";
                    if (m.toString().startsWith(element[0].substring(0, 3))) {
                        plugin.getLogger().severe(
                                "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                        hint = true;
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe(
                            "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                    plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                }
                //}
                return null;
            }
        } else if (element.length == 6) {
            //plugin.getLogger().info("DEBUG: 6 element reward");
            // Potion format = POTION:name:level:extended:splash:qty
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[5]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    givePotion(player, rewardedItems, element, rewardQty);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Problem with reward potion: " + s);
                plugin.getLogger().severe("Format POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY");
                plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional");
                plugin.getLogger().severe("LEVEL is a number");
                plugin.getLogger().severe("Examples:");
                plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1");
                plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1");
                plugin.getLogger().severe("POTION:WEAKNESS:::::1   -  any weakness potion");
                plugin.getLogger().severe("Available names are:");
                String potionNames = "";
                for (PotionType p : PotionType.values()) {
                    potionNames += p.toString() + ", ";
                }
                plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2));
                return null;
            }
        }
    }
    return rewardedItems;
}

From source file:org.sakaiproject.unboundid.UnboundidDirectoryProvider.java

/**
 * Similar to iterating over <code>users</code> passing
 * each element to {@link #getUser(UserEdit)}, removing the
 * {@link org.sakaiproject.user.api.UserEdit} if that method 
 * returns <code>false</code>. 
 * /*from   www .j av a 2  s  .co m*/
 * <p>Adds search retry capability if any one lookup fails 
 * with a directory error. Empties <code>users</code> and 
 * returns if a retry exits exceptionally
 * <p>
 */
public void getUsers(Collection<UserEdit> users) {
    log.debug("getUsers(): [Collection size = {}]", users.size());

    boolean abortiveSearch = false;
    int maxQuerySize = getMaxObjectsToQueryFor();
    UserEdit userEdit = null;

    HashMap<String, UserEdit> usersToSearchInLDAP = new HashMap<String, UserEdit>();
    List<UserEdit> usersToRemove = new ArrayList<UserEdit>();
    try {
        int cnt = 0;
        for (Iterator<UserEdit> userEdits = users.iterator(); userEdits.hasNext();) {
            userEdit = (UserEdit) userEdits.next();
            String eid = userEdit.getEid();

            if (!(isSearchableEid(eid))) {
                userEdits.remove();
                //proceed ahead with this (perhaps the final) iteration
                //usersToSearchInLDAP needs to be processed unless empty
            } else {
                usersToSearchInLDAP.put(eid, userEdit);
                cnt++;
            }

            // We need to make sure this query isn't larger than maxQuerySize
            if ((!userEdits.hasNext() || cnt == maxQuerySize) && !usersToSearchInLDAP.isEmpty()) {
                String filter = ldapAttributeMapper.getManyUsersInOneSearch(usersToSearchInLDAP.keySet());
                List<LdapUserData> ldapUsers = searchDirectory(filter, null, null, null, maxQuerySize);

                for (LdapUserData ldapUserData : ldapUsers) {
                    String ldapEid = ldapUserData.getEid();

                    if (StringUtils.isEmpty(ldapEid)) {
                        continue;
                    }
                    ldapEid = ldapEid.toLowerCase();

                    UserEdit ue = usersToSearchInLDAP.get(ldapEid);
                    mapUserDataOntoUserEdit(ldapUserData, ue);
                    usersToSearchInLDAP.remove(ldapEid);
                }

                // see if there are any users that we could not find in the LDAP query
                for (Map.Entry<String, UserEdit> entry : usersToSearchInLDAP.entrySet()) {
                    usersToRemove.add(entry.getValue());
                }

                // clear the HashMap and reset the counter
                usersToSearchInLDAP.clear();
                cnt = 0;
            }
        }

        // Finally clean up the original collection and remove and users we could not find
        for (UserEdit userRemove : usersToRemove) {
            log.debug("Unboundid getUsers could not find user: {}", userRemove.getEid());
            users.remove(userRemove);
        }

    } catch (LDAPException e) {
        abortiveSearch = true;
        throw new RuntimeException("getUsers(): LDAPException during search [eid = "
                + (userEdit == null ? null : userEdit.getEid()) + "][result code = " + e.errorCodeToString()
                + "][error message = " + e.getLDAPErrorMessage() + "]", e);
    } catch (Exception e) {
        abortiveSearch = true;
        throw new RuntimeException("getUsers(): RuntimeException during search eid = "
                + (userEdit == null ? null : userEdit.getEid()) + "]", e);
    } finally {
        // no sense in returning a partially complete search result
        if (abortiveSearch) {
            log.debug("getUsers(): abortive search, clearing received users collection");
            users.clear();
        }
    }

}

From source file:org.esa.s2tbx.dataio.s2.ortho.Sentinel2OrthoProductReader.java

@Override
protected Product getMosaicProduct(File metadataFile) throws IOException {
    Objects.requireNonNull(metadataFile);

    boolean isAGranule = S2OrthoGranuleMetadataFilename.isGranuleFilename(metadataFile.getName());

    if (isAGranule) {
        logger.fine("Reading a granule");
    }/* w w w . j  ava2s.  c o  m*/

    TimeProbe timeProbe = TimeProbe.start();
    // update the tile layout
    updateTileLayout(metadataFile.toPath(), isAGranule);
    SystemUtils.LOG.fine(
            String.format("[timeprobe] updateTileLayout : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));

    String filterTileId = null;
    File rootMetaDataFile = null;
    String granuleDirName = null;

    timeProbe.reset();
    // we need to recover parent metadata file if we have a granule
    if (isAGranule) {
        granuleDirName = metadataFile.getParentFile().getName();
        try {
            Objects.requireNonNull(metadataFile.getParentFile());
            Objects.requireNonNull(metadataFile.getParentFile().getParentFile());
            Objects.requireNonNull(metadataFile.getParentFile().getParentFile().getParentFile());
        } catch (NullPointerException npe) {
            throw new IOException(
                    String.format("Unable to retrieve the product associated to granule metadata file [%s]",
                            metadataFile.getName()));
        }

        File up2levels = metadataFile.getParentFile().getParentFile().getParentFile();
        File tileIdFilter = metadataFile.getParentFile();

        filterTileId = tileIdFilter.getName();

        File[] files = up2levels.listFiles();
        if (files != null) {
            for (File f : files) {
                if (S2ProductFilename.isProductFilename(f.getName())
                        && S2ProductFilename.isMetadataFilename(f.getName())) {
                    rootMetaDataFile = f;
                    break;
                }
            }
        }
        if (rootMetaDataFile == null) {
            throw new IOException(
                    String.format("Unable to retrieve the product associated to granule metadata file [%s]",
                            metadataFile.getName()));
        }
    } else {
        rootMetaDataFile = metadataFile;
    }

    final String aFilter = filterTileId;

    S2Metadata metadataHeader = parseHeader(rootMetaDataFile, granuleDirName, getConfig(), epsgCode);
    SystemUtils.LOG.fine(
            String.format("[timeprobe] metadata parsing : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));
    timeProbe.reset();

    S2OrthoSceneLayout sceneDescription = S2OrthoSceneLayout.create(metadataHeader);
    logger.fine("Scene Description: " + sceneDescription);

    File productDir = getProductDir(rootMetaDataFile);
    initCacheDir(productDir);

    S2Metadata.ProductCharacteristics productCharacteristics = metadataHeader.getProductCharacteristics();

    Product product = new Product(FileUtils.getFilenameWithoutExtension(rootMetaDataFile),
            "S2_MSI_" + productCharacteristics.getProcessingLevel(),
            sceneDescription.getSceneDimension(getProductResolution()).width,
            sceneDescription.getSceneDimension(getProductResolution()).height);

    for (MetadataElement metadataElement : metadataHeader.getMetadataElements()) {
        product.getMetadataRoot().addElement(metadataElement);
    }
    product.setFileLocation(metadataFile);

    try {
        product.setSceneGeoCoding(new CrsGeoCoding(CRS.decode(this.epsgCode), product.getSceneRasterWidth(),
                product.getSceneRasterHeight(), sceneDescription.getSceneOrigin()[0],
                sceneDescription.getSceneOrigin()[1], this.getProductResolution().resolution,
                this.getProductResolution().resolution, 0.0, 0.0));
    } catch (FactoryException e) {
        throw new IOException(e);
    } catch (TransformException e) {
        throw new IOException(e);
    }

    product.setPreferredTileSize(S2Config.DEFAULT_JAI_TILE_SIZE, S2Config.DEFAULT_JAI_TILE_SIZE);
    product.setNumResolutionsMax(getConfig().getTileLayout(S2SpatialResolution.R10M.resolution).numResolutions);
    product.setAutoGrouping("sun:view:quality");

    List<BandInfo> bandInfoList = new ArrayList<>();

    List<S2Metadata.Tile> tileList = metadataHeader.getTileList();
    if (isAGranule) {
        tileList = tileList.stream().filter(p -> p.getId().equalsIgnoreCase(aFilter))
                .collect(Collectors.toList());
    }

    // Verify access to granule image files, and store absolute location
    for (S2BandInformation bandInformation : productCharacteristics.getBandInformations()) {
        HashMap<String, File> tileFileMap = new HashMap<>();
        for (S2Metadata.Tile tile : tileList) {
            S2OrthoGranuleDirFilename gf = S2OrthoGranuleDirFilename.create(tile.getId());
            if (gf != null) {

                String imgFilename = String.format("GRANULE%s%s%s%s", File.separator, tile.getId(),
                        File.separator,
                        bandInformation.getImageFileTemplate().replace("{{MISSION_ID}}", gf.missionID)
                                .replace("{{SITECENTRE}}", gf.siteCentre)
                                .replace("{{CREATIONDATE}}", gf.creationDate)
                                .replace("{{ABSOLUTEORBIT}}", gf.absoluteOrbit)
                                .replace("{{TILENUMBER}}", gf.tileNumber).replace("{{RESOLUTION}}",
                                        String.format("%d", bandInformation.getResolution().resolution)));

                logger.finer("Adding file " + imgFilename + " to band: " + bandInformation.getPhysicalBand());

                File file = new File(productDir, imgFilename);
                if (file.exists()) {
                    tileFileMap.put(tile.getId(), file);
                } else {
                    logger.warning(String.format("Warning: missing file %s\n", file));
                }
            }
        }

        if (!tileFileMap.isEmpty()) {
            BandInfo bandInfo = createBandInfoFromHeaderInfo(bandInformation, tileFileMap);
            bandInfoList.add(bandInfo);
        } else {
            logger.warning(String.format("Warning: no image files found for band %s\n",
                    bandInformation.getPhysicalBand()));
        }
    }
    SystemUtils.LOG.fine(String.format("[timeprobe] product initialisation : %s ms",
            timeProbe.elapsed(TimeUnit.MILLISECONDS)));
    timeProbe.reset();

    if (!bandInfoList.isEmpty()) {
        addBands(product, bandInfoList, sceneDescription);
        SystemUtils.LOG
                .fine(String.format("[timeprobe] addBands : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));
        timeProbe.reset();

        scaleBands(product, bandInfoList);
        SystemUtils.LOG.fine(
                String.format("[timeprobe] scaleBands : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));
        timeProbe.reset();

        addVectorMasks(product, tileList, bandInfoList);
        SystemUtils.LOG.fine(
                String.format("[timeprobe] addVectorMasks : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));
        timeProbe.reset();

        addIndexMasks(product, bandInfoList);
        SystemUtils.LOG.fine(
                String.format("[timeprobe] addIndexMasks : %s ms", timeProbe.elapsed(TimeUnit.MILLISECONDS)));
        timeProbe.reset();
    }

    if (!"Brief".equalsIgnoreCase(productCharacteristics.getMetaDataLevel())) {
        addTiePointGridBand(product, metadataHeader, sceneDescription, "sun_zenith", SUN_ZENITH_GRID_INDEX,
                "Solar zenith angle", "");
        addTiePointGridBand(product, metadataHeader, sceneDescription, "sun_azimuth", SUN_AZIMUTH_GRID_INDEX,
                "Solar azimuth angle", "");
        addTiePointGridBand(product, metadataHeader, sceneDescription, "view_zenith", VIEW_ZENITH_GRID_INDEX,
                "Viewing incidence zenith angle", "");
        addTiePointGridBand(product, metadataHeader, sceneDescription, "view_azimuth", VIEW_AZIMUTH_GRID_INDEX,
                "Viewing incidence azimuth angle", "");
        SystemUtils.LOG.fine(String.format("[timeprobe] addTiePointGridBand : %s ms",
                timeProbe.elapsed(TimeUnit.MILLISECONDS)));
        timeProbe.reset();
    }

    return product;
}

From source file:org.encuestame.rest.api.v1.SettingsJsonController.java

/**
 * Upgrade profile settings./*from   w  w  w.j  a v a2s .  c  o  m*/
 * @param model
 * @return
 */
@PreAuthorize("hasRole('ENCUESTAME_USER')")
@RequestMapping(value = "/api/settings/profile/{type}/update.json", method = RequestMethod.POST)
public @ResponseBody ModelMap upgradeProfile(HttpServletRequest request, @PathVariable String type,
        @RequestParam(value = "data", required = false) String data, HttpServletResponse response)
        throws JsonGenerationException, JsonMappingException, IOException {

    log.debug("update profile type:" + type);
    log.debug("update profile data:" + data);
    try {
        final SecurityOperations security = getSecurityService();
        final ValidateOperations operations = new ValidateOperations(security);
        final HashMap<String, Object> listError = new HashMap<String, Object>();
        //filter data
        data = filterValue(data);
        type = type.toUpperCase();
        if (type.equals(Profile.EMAIL.toString())) {
            //TODO: review pattern email format validator.
            log.debug("update email");
            final UserAccount account = getSecurityService().getUserAccount(getUserPrincipalUsername());
            if (operations.validateUserEmail(data, account)) {
                security.updateAccountProfile(Profile.EMAIL, data);
                setSuccesResponse();
            } else {
                listError.put(type, getMessage("e_005", request, null));
            }
        } else if (type.equals(Profile.USERNAME.toString())) {
            log.debug("update username");
            final UserAccount account = getSecurityService().getUserAccount(getUserPrincipalUsername());
            if (operations.validateUsername(data, account)) {
                security.updateAccountProfile(Profile.USERNAME, data);
                setSuccesResponse(getMessage("settings_config_profile_success", request, null));
            } else {
                listError.put(type, getMessage("e_018", request, null));
            }
        } else if (type.equals(Profile.PICTURE.toString())) {
            log.debug("update PICTURE");
            security.updateAccountProfile(Profile.PICTURE, data);
            setSuccesResponse(getMessage("settings_config_picture_success", request, null));
        } else if (type.equals(Profile.WELCOME.toString())) {
            log.debug("update WELCOME");
            security.updateAccountProfile(Profile.WELCOME, data);
            setSuccesResponse(getMessage("settings_welcome", request, null));
        } else if (type.equals(Profile.PAGE_INFO.toString())) {
            log.debug("update PAGE_INFO");
            security.updateAccountProfile(Profile.PAGE_INFO, data);
            setSuccesResponse(getMessage("settings_page_info", request, null));
        } else {
            setError(getMessage("e_023", request, null), response);
        }
        if (!listError.isEmpty()) {
            log.debug("list errors " + listError.size());
            setError(listError, response);
        }
    } catch (Exception e) {
        log.error(e);
        //e.printStackTrace();
        setError(getMessage("e_023", request, null), response);
        //throw new JsonGenerationException(e.getMessage());
    }
    return returnData();
}

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

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

@SuppressWarnings("deprecation")
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);
                player.sendMessage(ChatColor.RED + getChallengeConfig()
                        .getString("challenges.challengeList." + challenge + ".description"));
                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();
                            // 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 or potions
                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";
                    }
                    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]);
                    int count = reqAmount;
                    // plugin.getLogger().info("DEBUG: 3 part " +
                    // reqItem.toString() + ":" + reqDurability + " x " +
                    // reqAmount);
                    ItemStack item = new ItemStack(reqItem);
                    // Check for potions
                    if (reqItem.equals(Material.POTION)) {
                        //Logger.logger(2,"DEBUG: Potion");
                        // Contains at least does not work for potions
                        ItemStack[] playerInv = player.getInventory().getContents();
                        for (ItemStack i : playerInv) {
                            if (i != null && i.getType().equals(Material.POTION)) {
                                // plugin.getLogger().info("DEBUG: Potion found, durability = "+
                                // i.getDurability());

                                // Potion type was given by number
                                // Only included for backward compatibility
                                if (i.getDurability() == reqDurability) {
                                    item = i.clone();
                                    if (item.getAmount() > reqAmount) {
                                        item.setAmount(reqAmount);
                                    }
                                    count = count - item.getAmount();
                                    // plugin.getLogger().info("Matched! count = "
                                    // + count);
                                    // If the item stack has more in it than
                                    // required, just take the minimum
                                    // plugin.getLogger().info("DEBUG: Found "
                                    // + item.toString() + ":" +
                                    // item.getDurability() + " x " +
                                    // item.getAmount());
                                    toBeRemoved.add(item);
                                }
                            }
                            if (count == 0) {
                                break;
                            }
                        }
                        if (count > 0) {
                            return false;
                        }
                        // They have enough
                    } else {
                        // Item
                        item.setDurability((short) reqDurability);
                        // plugin.getLogger().info("DEBUG: item with durability "
                        // + item.toString());
                        // item.setAmount(reqAmount);
                        /*
                         * if (!player.getInventory().containsAtLeast(item,
                         * reqAmount)) {
                         * plugin.getLogger().info(
                         * "DEBUG: item with durability not enough");
                         * return false;
                         * }
                         */
                        // 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.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);
                } catch (Exception e) {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    player.sendMessage(
                            ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                    if (part[0].equalsIgnoreCase("POTION")) {
                        plugin.getLogger()
                                .severe("Format POTION:TYPE:QTY where TYPE is the number of the following:");
                        for (PotionType p : PotionType.values()) {
                            plugin.getLogger().info(p.toString() + ":" + p.getDamageValue());
                        }
                    } else {
                        String materialList = "";
                        boolean hint = false;
                        for (Material m : Material.values()) {
                            materialList += m.toString() + ",";
                            if (m.toString().contains(s.substring(0, 3))) {
                                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;
                    }
                    return false;
                }
            } else if (part.length == 6) {
                //plugin.getLogger().info("DEBUG:6 part potion check!");
                // POTION:Name:Level:Extended:Splash:Qty
                try {
                    if (StringUtils.isNumeric(part[0])) {
                        reqItem = Material.getMaterial(Integer.parseInt(part[0]));
                    } else {
                        reqItem = Material.getMaterial(part[0].toUpperCase());
                    }
                    reqAmount = Integer.parseInt(part[5]);
                    ItemStack item = new ItemStack(reqItem);
                    int count = reqAmount;
                    // Compare
                    if (reqItem == Material.POTION) {
                        //plugin.getLogger().info("DEBUG: required item is a potion");
                        ItemStack[] playerInv = player.getInventory().getContents();
                        for (ItemStack i : playerInv) {
                            if (i != null && i.getType().equals(Material.POTION)) {
                                //plugin.getLogger().info("DEBUG: Item in inventory = " + i.toString());
                                Potion p = fromDamage(i.getDurability());
                                // Check type
                                //Potion p = Potion.fromItemStack(i);

                                //plugin.getLogger().info("DEBUG: " + p.getType() + ":" + p.getLevel() + ":" + p.hasExtendedDuration() + ":" + p.isSplash() );
                                // Check type
                                PotionType typeCheck = PotionType.valueOf(part[1].toUpperCase());
                                //plugin.getLogger().info("DEBUG: potion type is:" + p.getType().toString() + " desired is:" + part[1].toUpperCase());
                                //if (p.getType().toString().equalsIgnoreCase(part[1].toUpperCase())) {
                                if (p.getType().equals(typeCheck)) {
                                    //plugin.getLogger().info("DEBUG: potion type is the same");
                                    // Check level
                                    //plugin.getLogger().info("DEBUG: check level " + part[2] + " = " + p.getLevel());
                                    if (part[2].isEmpty() || p.getLevel() == Integer.valueOf(part[2])) {
                                        //plugin.getLogger().info("DEBUG: level is ok ");
                                        //plugin.getLogger().info("DEBUG: check splash = " + part[4] + " = " + p.isSplash());
                                        if (part[4].isEmpty()
                                                || (p.isSplash() && part[4].equalsIgnoreCase("SPLASH"))
                                                || (!p.isSplash() && part[4].equalsIgnoreCase("NOSPLASH"))) {
                                            //plugin.getLogger().info("DEBUG: splash is ok = " + part[4] + " = " + p.isSplash());
                                            //plugin.getLogger().info("DEBUG: check extended = " + part[4] + " = " + p.hasExtendedDuration());
                                            if (part[3].isEmpty()
                                                    || (p.hasExtendedDuration()
                                                            && part[3].equalsIgnoreCase("EXTENDED"))
                                                    || (!p.hasExtendedDuration()
                                                            && part[3].equalsIgnoreCase("NOTEXTENDED"))) {
                                                //plugin.getLogger().info("DEBUG: Everything is matching");
                                                item = i.clone();
                                                if (item.getAmount() > reqAmount) {
                                                    item.setAmount(reqAmount);
                                                }
                                                count = count - item.getAmount();
                                                toBeRemoved.add(item);
                                            }
                                        }
                                    }
                                }
                            }
                            if (count <= 0) {
                                break;
                            }
                        }
                        if (count > 0) {
                            return false;
                        }
                    } else {
                        plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    }
                } catch (Exception e) {
                    plugin.getLogger().severe("Problem with " + s + " in challenges.yml!");
                    //e.printStackTrace();
                    player.sendMessage(
                            ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady);
                    if (part[0].equalsIgnoreCase("POTION")) {
                        plugin.getLogger().severe(
                                "Format POTION:NAME:<LEVEL>:<EXTENDED/NOTEXTENDED>:<SPLASH/NOSPLASH>:QTY");
                        plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional");
                        plugin.getLogger().severe("LEVEL is a number");
                        plugin.getLogger().severe("Examples:");
                        plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1");
                        plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1");
                        plugin.getLogger().severe("POTION:WEAKNESS::::1   -  any weakness potion");
                        plugin.getLogger().severe("Available names are:");
                        String potionNames = "";
                        for (PotionType p : PotionType.values()) {
                            potionNames += p.toString() + ", ";
                        }
                        plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2));
                    }
                    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("island")) {
        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();
        for (int x = -10; x <= 10; x++) {
            for (int y = -10; y <= 10; y++) {
                for (int z = -10; z <= 10; 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(10, 10, 10)) {
                // 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.wasteofplastic.askyblock.commands.Challenges.java

/**
 * Gives player the reward items. /*from   w w w .j  ava  2 s.  c o  m*/
 * @param player
 * @param itemRewards
 * @return List of ItemStacks that were given to the player or null if there was an error in the interpretation of the rewards
 */
private List<ItemStack> giveItems(Player player, String[] itemRewards) {
    List<ItemStack> rewardedItems = new ArrayList<ItemStack>();
    Material rewardItem;
    int rewardQty;
    // Build the item stack of rewards to give the player
    for (final String s : itemRewards) {
        final String[] element = s.split(":");
        if (element.length == 2) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[1]);
                ItemStack item = new ItemStack(rewardItem, rewardQty);
                rewardedItems.add(item);
                final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                        .addItem(new ItemStack[] { item });
                if (!leftOvers.isEmpty()) {
                    player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                }
                if (plugin.getServer().getVersion().contains("(MC: 1.8")
                        || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                    player.getWorld().playSound(player.getLocation(), Sound.valueOf("ITEM_PICKUP"), 1F, 1F);
                } else {
                    player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1F, 1F);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorRewardProblem);
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                String materialList = "";
                boolean hint = false;
                for (Material m : Material.values()) {
                    materialList += m.toString() + ",";
                    if (element[0].length() > 3) {
                        if (m.toString().startsWith(element[0].substring(0, 3))) {
                            plugin.getLogger().severe(
                                    "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                            hint = true;
                        }
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe(
                            "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                    plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                }
            }
        } else if (element.length == 3) {
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[2]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    givePotion(player, rewardedItems, element, rewardQty);
                } else {
                    ItemStack item = null;
                    // Normal item, not a potion, check if it is a Monster Egg
                    if (rewardItem.equals(Material.MONSTER_EGG)) {

                        try {
                            EntityType type = EntityType.valueOf(element[1].toUpperCase());
                            if (Bukkit.getServer().getVersion().contains("(MC: 1.8")
                                    || Bukkit.getServer().getVersion().contains("(MC: 1.7")) {
                                item = new SpawnEgg(type).toItemStack(rewardQty);
                            } else {
                                try {
                                    item = new SpawnEgg1_9(type).toItemStack(rewardQty);
                                } catch (Exception ex) {
                                    item = new ItemStack(rewardItem);
                                    plugin.getLogger()
                                            .severe("Monster eggs not supported with this server version.");
                                }
                            }
                        } catch (Exception e) {
                            Bukkit.getLogger().severe(
                                    "Spawn eggs must be described by name. Try one of these (not all are possible):");
                            for (EntityType type : EntityType.values()) {
                                if (type.isSpawnable() && type.isAlive()) {
                                    plugin.getLogger().severe(type.toString());
                                }
                            }
                        }
                    } else {
                        int rewMod = Integer.parseInt(element[1]);
                        item = new ItemStack(rewardItem, rewardQty, (short) rewMod);
                    }
                    if (item != null) {
                        rewardedItems.add(item);
                        final HashMap<Integer, ItemStack> leftOvers = player.getInventory()
                                .addItem(new ItemStack[] { item });
                        if (!leftOvers.isEmpty()) {
                            player.getWorld().dropItemNaturally(player.getLocation(), leftOvers.get(0));
                        }
                    }
                }
                if (plugin.getServer().getVersion().contains("(MC: 1.8")
                        || plugin.getServer().getVersion().contains("(MC: 1.7")) {
                    player.getWorld().playSound(player.getLocation(), Sound.valueOf("ITEM_PICKUP"), 1F, 1F);
                } else {
                    player.getWorld().playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1F, 1F);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Could not give " + element[0] + ":" + element[1] + " to "
                        + player.getName() + " for challenge reward!");
                /*
                if (element[0].equalsIgnoreCase("POTION")) {
                String potionList = "";
                boolean hint = false;
                for (PotionEffectType m : PotionEffectType.values()) {
                    potionList += m.toString() + ",";
                    if (element[1].length() > 3) {
                        if (m.toString().startsWith(element[1].substring(0, 3))) {
                            plugin.getLogger().severe("Did you mean " + m.toString() + "?");
                            hint = true;
                        }
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe("Sorry, I have no idea what potion type " + element[1] + " is. Pick from one of these:");
                    plugin.getLogger().severe(potionList.substring(0, potionList.length() - 1));
                }
                        
                } else {*/
                String materialList = "";
                boolean hint = false;
                for (Material m : Material.values()) {
                    materialList += m.toString() + ",";
                    if (m.toString().startsWith(element[0].substring(0, 3))) {
                        plugin.getLogger().severe(
                                "Did you mean " + m.toString() + "? If so, put that in challenges.yml.");
                        hint = true;
                    }
                }
                if (!hint) {
                    plugin.getLogger().severe(
                            "Sorry, I have no idea what " + element[0] + " is. Pick from one of these:");
                    plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1));
                }
                //}
                return null;
            }
        } else if (element.length == 6) {
            //plugin.getLogger().info("DEBUG: 6 element reward");
            // Potion format = POTION:name:level:extended:splash:qty
            try {
                if (StringUtils.isNumeric(element[0])) {
                    rewardItem = Material.getMaterial(Integer.parseInt(element[0]));
                } else {
                    rewardItem = Material.getMaterial(element[0].toUpperCase());
                }
                rewardQty = Integer.parseInt(element[5]);
                // Check for POTION
                if (rewardItem.equals(Material.POTION)) {
                    givePotion(player, rewardedItems, element, rewardQty);
                }
            } catch (Exception e) {
                player.sendMessage(
                        ChatColor.RED + "There was a problem giving your reward. Ask Admin to check log!");
                plugin.getLogger().severe("Problem with reward potion: " + s);
                plugin.getLogger().severe("Format POTION:NAME:<LEVEL>:<EXTENDED>:<SPLASH/LINGER>:QTY");
                plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional");
                plugin.getLogger().severe("LEVEL is a number");
                plugin.getLogger().severe("Examples:");
                plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1");
                plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1");
                plugin.getLogger().severe("POTION:WEAKNESS:::::1   -  any weakness potion");
                plugin.getLogger().severe("Available names are:");
                String potionNames = "";
                for (PotionType p : PotionType.values()) {
                    potionNames += p.toString() + ", ";
                }
                plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2));
                return null;
            }
        }
    }
    return rewardedItems;
}