Example usage for java.util LinkedHashMap get

List of usage examples for java.util LinkedHashMap get

Introduction

In this page you can find the example usage for java.util LinkedHashMap get.

Prototype

public V get(Object key) 

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:org.openmeetings.app.remote.OrganisationService.java

/**
 * adds or updates an Organisation//from   w ww.jav a 2s .  c o  m
 * 
 * @param SID
 * @param organisation_id
 * @param orgname
 * @return
 */
public Long saveOrUpdateOrganisation(String SID, Object regObjectObj) {
    try {
        Long users_id = sessionManagement.checkSession(SID);
        long user_level = userManagement.getUserLevelByID(users_id);
        @SuppressWarnings("rawtypes")
        LinkedHashMap<?, ?> argObjectMap = (LinkedHashMap) regObjectObj;
        long organisation_id = Long.valueOf(argObjectMap.get("organisation_id").toString()).longValue();
        if (organisation_id == 0) {
            return organisationmanagement.addOrganisation(user_level, argObjectMap.get("orgname").toString(),
                    users_id);
        } else {
            return organisationmanagement.updateOrganisation(user_level, organisation_id,
                    argObjectMap.get("orgname").toString(), users_id);
        }
    } catch (Exception err) {
        log.error("saveOrUpdateOrganisation", err);
    }
    return null;

}

From source file:net.minecraftforge.registries.GameData.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Multimap<ResourceLocation, ResourceLocation> injectSnapshot(
        Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot, boolean injectFrozenData,
        boolean isLocalWorld) {
    FMLLog.log.info("Injecting existing registry data into this {} instance",
            FMLCommonHandler.instance().getEffectiveSide().isServer() ? "server" : "client");
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.validateContent(name));
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name));
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.resetDelegates());

    List<ResourceLocation> missingRegs = snapshot.keySet().stream()
            .filter(name -> !RegistryManager.ACTIVE.registries.containsKey(name)).collect(Collectors.toList());
    if (missingRegs.size() > 0) {
        String text = "Forge Mod Loader detected missing/unknown registrie(s).\n\n" + "There are "
                + missingRegs.size() + " missing registries in this save.\n"
                + "If you continue the missing registries will get removed.\n"
                + "This may cause issues, it is advised that you create a world backup before continuing.\n\n"
                + "Missing Registries:\n";

        for (ResourceLocation s : missingRegs)
            text += s.toString() + "\n";

        if (!StartupQuery.confirm(text))
            StartupQuery.abort();//from   w  ww.  jav a2 s .c o m
    }

    RegistryManager STAGING = new RegistryManager("STAGING");

    final Map<ResourceLocation, Map<ResourceLocation, Integer[]>> remaps = Maps.newHashMap();
    final LinkedHashMap<ResourceLocation, Map<ResourceLocation, Integer>> missing = Maps.newLinkedHashMap();
    // Load the snapshot into the "STAGING" registry
    snapshot.forEach((key, value) -> {
        final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(key);
        remaps.put(key, Maps.newLinkedHashMap());
        missing.put(key, Maps.newHashMap());
        loadPersistentDataToStagingRegistry(RegistryManager.ACTIVE, STAGING, remaps.get(key), missing.get(key),
                key, value, clazz);
    });

    snapshot.forEach((key, value) -> {
        value.dummied.forEach(dummy -> {
            Map<ResourceLocation, Integer> m = missing.get(key);
            ForgeRegistry<?> reg = STAGING.getRegistry(key);

            // Currently missing locally, we just inject and carry on
            if (m.containsKey(dummy)) {
                if (reg.markDummy(dummy, m.get(dummy)))
                    m.remove(dummy);
            } else if (isLocalWorld) {
                if (ForgeRegistry.DEBUG)
                    FMLLog.log.debug("Registry {}: Resuscitating dummy entry {}", key, dummy);
            } else {
                // The server believes this is a dummy block identity, but we seem to have one locally. This is likely a conflict
                // in mod setup - Mark this entry as a dummy
                int id = reg.getID(dummy);
                FMLLog.log.warn(
                        "Registry {}: The ID {} is currently locally mapped - it will be replaced with a dummy for this session",
                        key, id);
                reg.markDummy(dummy, id);
            }
        });
    });

    int count = missing.values().stream().mapToInt(Map::size).sum();
    if (count > 0) {
        FMLLog.log.debug("There are {} mappings missing - attempting a mod remap", count);
        Multimap<ResourceLocation, ResourceLocation> defaulted = ArrayListMultimap.create();
        Multimap<ResourceLocation, ResourceLocation> failed = ArrayListMultimap.create();

        missing.entrySet().stream().filter(e -> e.getValue().size() > 0).forEach(m -> {
            ResourceLocation name = m.getKey();
            ForgeRegistry<?> reg = STAGING.getRegistry(name);
            RegistryEvent.MissingMappings<?> event = reg.getMissingEvent(name, m.getValue());
            MinecraftForge.EVENT_BUS.post(event);

            List<MissingMappings.Mapping<?>> lst = event.getAllMappings().stream()
                    .filter(e -> e.getAction() == MissingMappings.Action.DEFAULT).collect(Collectors.toList());
            if (!lst.isEmpty()) {
                FMLLog.log.error("Unidentified mapping from registry {}", name);
                lst.forEach(map -> {
                    FMLLog.log.error("    {}: {}", map.key, map.id);
                    if (!isLocalWorld)
                        defaulted.put(name, map.key);
                });
            }
            event.getAllMappings().stream().filter(e -> e.getAction() == MissingMappings.Action.FAIL)
                    .forEach(fail -> failed.put(name, fail.key));

            final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name);
            processMissing(clazz, name, STAGING, event, m.getValue(), remaps.get(name), defaulted.get(name),
                    failed.get(name));
        });

        if (!defaulted.isEmpty() && !isLocalWorld)
            return defaulted;

        if (!defaulted.isEmpty()) {
            StringBuilder buf = new StringBuilder();
            buf.append("Forge Mod Loader detected missing registry entries.\n\n").append("There are ")
                    .append(defaulted.size()).append(" missing entries in this save.\n")
                    .append("If you continue the missing entries will get removed.\n")
                    .append("A world backup will be automatically created in your saves directory.\n\n");

            defaulted.asMap().forEach((name, entries) -> {
                buf.append("Missing ").append(name).append(":\n");
                entries.forEach(rl -> buf.append("    ").append(rl).append("\n"));
            });

            boolean confirmed = StartupQuery.confirm(buf.toString());
            if (!confirmed)
                StartupQuery.abort();

            try {
                String skip = System.getProperty("fml.doNotBackup");
                if (skip == null || !"true".equals(skip)) {
                    ZipperUtil.backupWorld();
                } else {
                    for (int x = 0; x < 10; x++)
                        FMLLog.log.error("!!!!!!!!!! UPDATING WORLD WITHOUT DOING BACKUP !!!!!!!!!!!!!!!!");
                }
            } catch (IOException e) {
                StartupQuery.notify("The world backup couldn't be created.\n\n" + e);
                StartupQuery.abort();
            }
        }

        if (!defaulted.isEmpty()) {
            if (isLocalWorld)
                FMLLog.log.error(
                        "There are unidentified mappings in this world - we are going to attempt to process anyway");
        }

    }

    if (injectFrozenData) {
        // If we're loading from disk, we can actually substitute air in the block map for anything that is otherwise "missing". This keeps the reference in the map, in case
        // the block comes back later
        missing.forEach((name, m) -> {
            ForgeRegistry<?> reg = STAGING.getRegistry(name);
            m.forEach((rl, id) -> reg.markDummy(rl, id));
        });

        // If we're loading up the world from disk, we want to add in the new data that might have been provisioned by mods
        // So we load it from the frozen persistent registry
        RegistryManager.ACTIVE.registries.forEach((name, reg) -> {
            final Class<? extends IForgeRegistryEntry> clazz = RegistryManager.ACTIVE.getSuperType(name);
            loadFrozenDataToStagingRegistry(STAGING, name, remaps.get(name), clazz);
        });
    }

    // Validate that all the STAGING data is good
    STAGING.registries.forEach((name, reg) -> reg.validateContent(name));

    // Load the STAGING registry into the ACTIVE registry
    for (Map.Entry<ResourceLocation, ForgeRegistry<? extends IForgeRegistryEntry<?>>> r : RegistryManager.ACTIVE.registries
            .entrySet()) {
        final Class<? extends IForgeRegistryEntry> registrySuperType = RegistryManager.ACTIVE
                .getSuperType(r.getKey());
        loadRegistry(r.getKey(), STAGING, RegistryManager.ACTIVE, registrySuperType, true);
    }

    // Dump the active registry
    RegistryManager.ACTIVE.registries.forEach((name, reg) -> reg.dump(name));

    // Tell mods that the ids have changed
    Loader.instance().fireRemapEvent(remaps, false);

    // The id map changed, ensure we apply object holders
    ObjectHolderRegistry.INSTANCE.applyObjectHolders();

    // Return an empty list, because we're good
    return ArrayListMultimap.create();
}

From source file:com.fortify.processrunner.tfs.processor.ProcessorTFSSubmitIssueForVulnerabilities.java

@Override
protected SubmittedIssue submitIssue(Context context, LinkedHashMap<String, Object> issueData) {
    IContextTFS contextTFS = context.as(IContextTFS.class);
    TFSRestConnection conn = TFSConnectionFactory.getConnection(context);
    issueData.put("System.Title", StringUtils.abbreviate((String) issueData.get("System.Title"), 254));
    String workItemType = getWorkItemType(contextTFS);
    fieldRenamer.renameFields(workItemType, issueData);
    return conn.submitIssue(contextTFS.getTFSCollection(), contextTFS.getTFSProject(), workItemType, issueData);
}

From source file:com.opengamma.analytics.financial.provider.sensitivity.multicurve.SimpleParameterSensitivity.java

/**
 * Create a copy of the sensitivity and add a given named sensitivity to it. If the name / currency pair is in the map, the two sensitivity matrices are added.
 * Otherwise, a new entry is put into the map
 * @param name The name. Not null./*w w w.ja v a 2  s  .c  om*/
 * @param sensitivity The sensitivity to add, not null
 * @return The total sensitivity.
 */
public SimpleParameterSensitivity plus(final String name, final DoubleMatrix1D sensitivity) {
    ArgumentChecker.notNull(name, "Name");
    ArgumentChecker.notNull(sensitivity, "Matrix");
    final MatrixAlgebra algebra = MatrixAlgebraFactory.COMMONS_ALGEBRA;
    final LinkedHashMap<String, DoubleMatrix1D> result = new LinkedHashMap<>();
    result.putAll(_sensitivity);
    if (result.containsKey(name)) {
        result.put(name, (DoubleMatrix1D) algebra.add(result.get(name), sensitivity));
    } else {
        result.put(name, sensitivity);
    }
    return new SimpleParameterSensitivity(result);
}

From source file:com.vikingbrain.nmt.controller.impl.RemoteHttpServiceImpl.java

/**
 * It uses the parameters to build the http arguments with name and value.
 * @param params all the parameters with name and value
 * @return the stringbuffer with the http arguments ready to be added to a http request
 *//*from w  w  w  . jav a 2s .c om*/
private StringBuffer buildEncodedParameters(LinkedHashMap<String, String> params) {
    StringBuffer parametersUrlGet = new StringBuffer("");

    if (null != params) {
        for (String key : params.keySet()) {

            String value = params.get(key);
            String encodedParameter = encodeHttpParameter(value);

            // It builds something like
            // "&param1=file%20name%26blues for entry "param1","file name&blues"
            parametersUrlGet.append("&").append(key).append("=").append(encodedParameter);
        }
    }
    return parametersUrlGet;
}

From source file:com.redhat.topicindex.security.FedoraAccountSystem.java

private boolean checkCLAAgreement(LinkedList<LinkedHashMap> groups) {
    for (LinkedHashMap group : groups) {
        if (group.containsKey("name")) {
            if (group.get("name").equals("cla_done")) {
                return true;
            }// w ww. j a  v  a 2s .c o  m
        }
    }
    return false;
}

From source file:edu.usu.sdl.opencatalog.api.impl.LookupServiceImpl.java

@Override
public <T extends BaseEntity> List<T> findLookup(Class<T> lookTableClass, boolean all) {
    List<T> correctedList = new ArrayList<>();

    //Route request
    WebTarget target = getRestTarget(SERVICE + "/" + lookTableClass.getSimpleName());
    Response response = target.queryParam("all", all).request(MediaType.APPLICATION_JSON).get();

    //TODO: handle failed case (Look at status to provide meaningful errors

    //String rawData = response.readEntity(String.class);

    //      try//  w w w. j  a  v a2s .c  om
    //      {
    //         ObjectMapper objectMapper = new ObjectMapper();
    //         correctedList = objectMapper.readValue(rawData, new TypeReference<List<T>>() {});
    //      } catch (IOException ex)
    //      {
    //         throw new RuntimeException(ex);
    //      }

    List<LinkedHashMap<String, String>> linkedMap = response.readEntity(new GenericType<List>() {
    });

    if (linkedMap.isEmpty() == false) {
        for (LinkedHashMap<String, String> map : linkedMap) {
            try {
                T dataObject = lookTableClass.newInstance();
                for (String key : map.keySet()) {
                    BeanUtils.setProperty(dataObject, key, map.get(key));
                }
                correctedList.add(dataObject);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
                log.log(Level.SEVERE, null, ex);
            }
        }
    }

    return correctedList;
}

From source file:org.raxa.module.raxacore.web.v1_0.controller.RaxaAlertControllerTest.java

/**
 * @see RaxaAlertController#searchByProviderRecipient(String, HttpServeletRequest, HttpServletResponse)
 * @throws Exception/*  www .  j a  v a 2  s  . co m*/
 */
@Test
public void searchByProviderRecipient_shouldGetAlertsByProvider() throws Exception {
    String results = controller.searchByProviderRecipient("68547121-1b70-465e-99ee-c9df45jf9j32", request);
    LinkedHashMap raxaAlert = (LinkedHashMap) ((ArrayList) SimpleObject.parseJson(results).get("results"))
            .get(0);
    System.out.println(Context.getProviderService().getProvider(1).getUuid());
    Assert.assertEquals("TestAlert1", raxaAlert.get("name"));
}

From source file:edumsg.edumsg_android_app.MainActivityFragment.java

private void populateRV() {
    final MainActivity main = (MainActivity) getActivity();
    final LoadToast loadToast = new LoadToast(getContext());
    final float scale = getContext().getResources().getDisplayMetrics().density;
    int pixels = (int) (56 * scale + 0.5f);
    loadToast.setTranslationY(pixels);/*from  w w w. j av  a  2 s .  c o m*/
    final ObjectMapper mapper = new ObjectMapper();
    Map<String, String> jsonParams = new HashMap<>();
    jsonParams.put("queue", "TWEET");
    jsonParams.put("method", "get_replies");
    jsonParams.put("tweet_id", tweetId + "");
    jsonParams.put("session_id", MyAppCompatActivity.sessionId);
    JSONObject jsonRequest = new JSONObject(jsonParams);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, MainActivity.requestUrl,
            jsonRequest, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Map<String, Object> responseMap = mapper.readValue(response.toString(),
                                new TypeReference<HashMap<String, Object>>() {
                                });
                        if (responseMap.get("code").equals("200")) {
                            loadToast.success();
                            ArrayList retweets = main.getRetweets();
                            ArrayList favorites = main.getFavorites();
                            ArrayList tweetsArray = (ArrayList) responseMap.get("replies");
                            final Iterator iterator = tweetsArray.iterator();
                            while (iterator.hasNext()) {
                                final Map<String, Object> tweetJsonObj = mapper.readValue(
                                        mapper.writeValueAsString(iterator.next()),
                                        new TypeReference<HashMap<String, Object>>() {
                                        });
                                final int tweetId = (int) tweetJsonObj.get("id");
                                final LinkedHashMap creatorMap = (LinkedHashMap) tweetJsonObj.get("creator");
                                final int creatorId = (int) creatorMap.get("id");
                                String tweetText = (String) tweetJsonObj.get("tweet_text");
                                String avatarUrl = (String) creatorMap.get("avatar_url");
                                User creator = new User();
                                creator.setId(creatorId);
                                creator.setName((String) creatorMap.get("name"));
                                creator.setUsername((String) creatorMap.get("username"));
                                creator.setAvatar_url(avatarUrl);
                                final Tweet tweetObject = new Tweet(tweetId, creator, tweetText);
                                if (avatarUrl != null && !avatarUrl.equals("")) {
                                    tweetObject.setImgUrl(avatarUrl);
                                }
                                if (retweets != null && retweets.contains(Integer.valueOf(tweetId))) {
                                    tweetObject.setIsRetweeted(true);
                                }
                                Iterator favIter = favorites.iterator();
                                while (favIter.hasNext()) {
                                    Map<String, Object> tweetJsonObj2 = mapper.readValue(
                                            mapper.writeValueAsString(favIter.next()),
                                            new TypeReference<HashMap<String, Object>>() {
                                            });
                                    if (tweetId == (int) tweetJsonObj2.get("id")) {
                                        tweetObject.setIsFavorited(true);
                                        break;
                                    }
                                }
                                replies.add(tweetObject);
                            }
                            rvAdapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        //                    e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loadToast.error();
                    //                error.printStackTrace();
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            //headers.put("User-agent", System.getProperty("http.agent"));
            return headers;
        };
    };
    jsonObjectRequest.setTag("Request");
    main.getVolleyRequestQueue().add(jsonObjectRequest);
}

From source file:com.company.eleave.leave.rest.ITTakenLeaveController.java

@Test
public void testGetTakenLeavesForEmployeeSuccessfuly() throws Exception {
    final String contentAsString = mockMvc.perform(get(request(RestURI.TAKEN_LEAVES_BY_EMPLOYEE, EMPLOYEE_ID)))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

    List<LinkedHashMap> result = new ObjectMapper().readValue(contentAsString, List.class);
    Assert.assertEquals(4, result.size());

    final LinkedHashMap standardAnnualBalanceLeave = result.stream().filter(map -> ((int) map.get("id") == 1))
            .findAny().get();/*  w  ww .  jav a  2s . com*/
    Assert.assertEquals(5, (int) standardAnnualBalanceLeave.get("approverId"));
    Assert.assertEquals("john doe5Approver", standardAnnualBalanceLeave.get("approverName"));
    Assert.assertEquals(1, (int) standardAnnualBalanceLeave.get("leaveDaysTaken"));
    Assert.assertEquals("2016-01-01", standardAnnualBalanceLeave.get("leaveFrom"));
    Assert.assertEquals("2016-01-01", standardAnnualBalanceLeave.get("leaveTo"));
    Assert.assertEquals("Standard holiday", standardAnnualBalanceLeave.get("leaveType"));

    final LinkedHashMap bloodDonationAnnualBalanceLeave = result.stream()
            .filter(map -> ((int) map.get("id") == 4)).findAny().get();
    Assert.assertEquals(10, (int) bloodDonationAnnualBalanceLeave.get("approverId"));
    Assert.assertEquals("john doeApprover10", bloodDonationAnnualBalanceLeave.get("approverName"));
    Assert.assertEquals(1, (int) bloodDonationAnnualBalanceLeave.get("leaveDaysTaken"));
    Assert.assertEquals("2016-02-02", bloodDonationAnnualBalanceLeave.get("leaveFrom"));
    Assert.assertEquals("2016-02-02", bloodDonationAnnualBalanceLeave.get("leaveTo"));
    Assert.assertEquals("Blood donation", bloodDonationAnnualBalanceLeave.get("leaveType"));
}