Java Examples for java.util.Map

The following java examples will help you to understand the usage of java.util.Map. These source code samples are taken from different open source projects.

Example 1
Project: RoboBuggy-master  File: IsMapContaining.java View source code
@Override
public boolean matchesSafely(Map<? extends K, ? extends V> map) {
    for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
        if (keyMatcher.matches(entry.getKey()) && valueMatcher.matches(entry.getValue())) {
            return true;
        }
    }
    return false;
}
Example 2
Project: hibernate-core-ogm-master  File: CollectionSecondPass.java View source code
public void doSecondPass(java.util.Map persistentClasses) throws MappingException {
    LOG.debugf("Second pass for collection: %s", collection.getRole());
    // using local since the inheritedMetas at this point is not the correct map since it is always the empty map
    secondPass(persistentClasses, localInheritedMetas);
    collection.createAllKeys();
    if (LOG.isDebugEnabled()) {
        String msg = "Mapped collection key: " + columns(collection.getKey());
        if (collection.isIndexed())
            msg += ", index: " + columns(((IndexedCollection) collection).getIndex());
        if (collection.isOneToMany()) {
            msg += ", one-to-many: " + ((OneToMany) collection.getElement()).getReferencedEntityName();
        } else {
            msg += ", element: " + columns(collection.getElement());
        }
        LOG.debugf(msg);
    }
}
Example 3
Project: eclipselink.runtime-master  File: ClassToolsTests.java View source code
public void testClassNamedIsTopLevel() throws Exception {
    // top-level
    assertTrue(ClassTools.classNamedIsTopLevel(java.util.Map.class.getName()));
    // member
    assertFalse(ClassTools.classNamedIsTopLevel(java.util.Map.Entry.class.getName()));
    // local
    assertFalse(ClassTools.classNamedIsTopLevel(Class.forName(munge(this.getClass().getName() + "$1$LocalClass")).getName()));
    // anonymous
    assertFalse(ClassTools.classNamedIsTopLevel(Class.forName("java.util.Vector$1").getName()));
    // top-level
    Object[] array = new java.util.Map[0];
    assertFalse(ClassTools.classNamedIsTopLevel(array.getClass().getName()));
    // member
    array = new java.util.Map.Entry[0];
    assertFalse(ClassTools.classNamedIsTopLevel(array.getClass().getName()));
    // local
    Class localClass = Class.forName(munge(this.getClass().getName() + "$1$LocalClass"));
    array = (Object[]) Array.newInstance(localClass, 0);
    assertFalse(ClassTools.classNamedIsTopLevel(array.getClass().getName()));
    // local
    Class anonClass = Class.forName("java.util.Vector$1");
    array = (Object[]) Array.newInstance(anonClass, 0);
    assertFalse(ClassTools.classNamedIsTopLevel(array.getClass().getName()));
}
Example 4
Project: eclipse.jdt.core-master  File: InnerEmulationTest_1_5.java View source code
//https://bugs.eclipse.org/bugs/show_bug.cgi?id=275381
public void test1() throws Exception {
    this.runConformTest(new String[] { "X.java", "import java.util.Collection;\n" + "import java.util.Map;\n" + "public class X {\n" + "	public void foo(Collection<? extends Map.Entry> args) { /* dummy */ }\n" + "}" });
    String expectedOutput = "  Inner classes:\n" + "    [inner class info: #25 java/util/Map$Entry, outer class info: #27 java/util/Map\n" + "     inner name: #29 Entry, accessflags: 1545 public abstract static]\n";
    checkDisassembledClassFile(OUTPUT_DIR + File.separator + "X.class", "X", expectedOutput);
}
Example 5
Project: ecms-develop-master  File: CanEditDocFilter.java View source code
/* (non-Javadoc)
   * @see org.exoplatform.webui.ext.filter.UIExtensionFilter#accept(java.util.Map)
   */
@Override
public boolean accept(Map<String, Object> context) throws Exception {
    if (context == null)
        return true;
    Node currentNode = (Node) context.get(Node.class.getName());
    if (!WCMCoreUtils.canAccessParentNode(currentNode))
        return false;
    return PermissionUtil.canAddNode(currentNode.getParent());
}
Example 6
Project: jdroid-master  File: DeviceMarshaller.java View source code
@Override
public JsonMap marshall(Device device, MarshallerMode mode, Map<String, String> extras) {
    JsonMap jsonMap = new JsonMap(mode, extras);
    jsonMap.put("deviceGroupId", device.getDeviceGroupId());
    jsonMap.put("registrationToken", device.getRegistrationToken());
    jsonMap.put("deviceBrandName", device.getDeviceBrandName());
    jsonMap.put("deviceModelName", device.getDeviceModelName());
    jsonMap.put("deviceOsVersion", device.getDeviceOsVersion());
    jsonMap.put("appVersionCode", device.getAppVersionCode());
    return jsonMap;
}
Example 7
Project: liferay-apps-content-targeting-master  File: CampaignServiceClpInvoker.java View source code
public Object invokeMethod(String name, String[] parameterTypes, Object[] arguments) throws Throwable {
    if (_methodName48.equals(name) && Arrays.deepEquals(_methodParameterTypes48, parameterTypes)) {
        return CampaignServiceUtil.getBeanIdentifier();
    }
    if (_methodName49.equals(name) && Arrays.deepEquals(_methodParameterTypes49, parameterTypes)) {
        CampaignServiceUtil.setBeanIdentifier((java.lang.String) arguments[0]);
        return null;
    }
    if (_methodName54.equals(name) && Arrays.deepEquals(_methodParameterTypes54, parameterTypes)) {
        return CampaignServiceUtil.addCampaign(((Long) arguments[0]).longValue(), (java.util.Map<java.util.Locale, java.lang.String>) arguments[1], (java.util.Map<java.util.Locale, java.lang.String>) arguments[2], (java.util.Date) arguments[3], (java.util.Date) arguments[4], ((Integer) arguments[5]).intValue(), ((Boolean) arguments[6]).booleanValue(), (long[]) arguments[7], (com.liferay.portal.service.ServiceContext) arguments[8]);
    }
    if (_methodName55.equals(name) && Arrays.deepEquals(_methodParameterTypes55, parameterTypes)) {
        return CampaignServiceUtil.deleteCampaign(((Long) arguments[0]).longValue());
    }
    if (_methodName56.equals(name) && Arrays.deepEquals(_methodParameterTypes56, parameterTypes)) {
        return CampaignServiceUtil.fetchCurrentMaxPriorityCampaign((long[]) arguments[0], (long[]) arguments[1]);
    }
    if (_methodName57.equals(name) && Arrays.deepEquals(_methodParameterTypes57, parameterTypes)) {
        return CampaignServiceUtil.getCampaigns(((Long) arguments[0]).longValue());
    }
    if (_methodName58.equals(name) && Arrays.deepEquals(_methodParameterTypes58, parameterTypes)) {
        return CampaignServiceUtil.getCampaignsCount(((Long) arguments[0]).longValue());
    }
    if (_methodName59.equals(name) && Arrays.deepEquals(_methodParameterTypes59, parameterTypes)) {
        return CampaignServiceUtil.updateCampaign(((Long) arguments[0]).longValue(), (java.util.Map<java.util.Locale, java.lang.String>) arguments[1], (java.util.Map<java.util.Locale, java.lang.String>) arguments[2], (java.util.Date) arguments[3], (java.util.Date) arguments[4], ((Integer) arguments[5]).intValue(), ((Boolean) arguments[6]).booleanValue(), (long[]) arguments[7], (com.liferay.portal.service.ServiceContext) arguments[8]);
    }
    throw new UnsupportedOperationException();
}
Example 8
Project: aws-sdk-android-master  File: ReEncryptRequestMarshaller.java View source code
public Request<ReEncryptRequest> marshall(ReEncryptRequest reEncryptRequest) {
    if (reEncryptRequest == null) {
        throw new AmazonClientException("Invalid argument passed to marshall(ReEncryptRequest)");
    }
    Request<ReEncryptRequest> request = new DefaultRequest<ReEncryptRequest>(reEncryptRequest, "AWSKMS");
    String target = "TrentService.ReEncrypt";
    request.addHeader("X-Amz-Target", target);
    request.setHttpMethod(HttpMethodName.POST);
    String uriResourcePath = "/";
    request.setResourcePath(uriResourcePath);
    try {
        StringWriter stringWriter = new StringWriter();
        AwsJsonWriter jsonWriter = JsonUtils.getJsonWriter(stringWriter);
        jsonWriter.beginObject();
        if (reEncryptRequest.getCiphertextBlob() != null) {
            java.nio.ByteBuffer ciphertextBlob = reEncryptRequest.getCiphertextBlob();
            jsonWriter.name("CiphertextBlob");
            jsonWriter.value(ciphertextBlob);
        }
        if (reEncryptRequest.getSourceEncryptionContext() != null) {
            java.util.Map<String, String> sourceEncryptionContext = reEncryptRequest.getSourceEncryptionContext();
            jsonWriter.name("SourceEncryptionContext");
            jsonWriter.beginObject();
            for (java.util.Map.Entry<String, String> sourceEncryptionContextEntry : sourceEncryptionContext.entrySet()) {
                String sourceEncryptionContextValue = sourceEncryptionContextEntry.getValue();
                if (sourceEncryptionContextValue != null) {
                    jsonWriter.name(sourceEncryptionContextEntry.getKey());
                    jsonWriter.value(sourceEncryptionContextValue);
                }
            }
            jsonWriter.endObject();
        }
        if (reEncryptRequest.getDestinationKeyId() != null) {
            String destinationKeyId = reEncryptRequest.getDestinationKeyId();
            jsonWriter.name("DestinationKeyId");
            jsonWriter.value(destinationKeyId);
        }
        if (reEncryptRequest.getDestinationEncryptionContext() != null) {
            java.util.Map<String, String> destinationEncryptionContext = reEncryptRequest.getDestinationEncryptionContext();
            jsonWriter.name("DestinationEncryptionContext");
            jsonWriter.beginObject();
            for (java.util.Map.Entry<String, String> destinationEncryptionContextEntry : destinationEncryptionContext.entrySet()) {
                String destinationEncryptionContextValue = destinationEncryptionContextEntry.getValue();
                if (destinationEncryptionContextValue != null) {
                    jsonWriter.name(destinationEncryptionContextEntry.getKey());
                    jsonWriter.value(destinationEncryptionContextValue);
                }
            }
            jsonWriter.endObject();
        }
        if (reEncryptRequest.getGrantTokens() != null) {
            java.util.List<String> grantTokens = reEncryptRequest.getGrantTokens();
            jsonWriter.name("GrantTokens");
            jsonWriter.beginArray();
            for (String grantTokensItem : grantTokens) {
                if (grantTokensItem != null) {
                    jsonWriter.value(grantTokensItem);
                }
            }
            jsonWriter.endArray();
        }
        jsonWriter.endObject();
        jsonWriter.close();
        String snippet = stringWriter.toString();
        byte[] content = snippet.getBytes(UTF8);
        request.setContent(new StringInputStream(snippet));
        request.addHeader("Content-Length", Integer.toString(content.length));
    } catch (Throwable t) {
        throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t);
    }
    if (!request.getHeaders().containsKey("Content-Type")) {
        request.addHeader("Content-Type", "application/x-amz-json-1.1");
    }
    return request;
}
Example 9
Project: dcache-master  File: NamedCellUtil.java View source code
public static String findDomainOfUniqueCell(Map<String, List<String>> domains, String cell) {
    String domain = "";
    for (Map.Entry<String, List<String>> entry : domains.entrySet()) {
        if (entry.getValue().contains(cell)) {
            domain = entry.getKey();
            break;
        }
    }
    return domain;
}
Example 10
Project: extFM-Tooling-master  File: MtextMapUtil.java View source code
public static java.util.Map<Object, Object> copySafelyToObjectToObjectMap(java.util.Map<?, ?> map) {
    java.util.Map<Object, Object> castedCopy = new java.util.LinkedHashMap<Object, Object>();
    if (map == null) {
        return castedCopy;
    }
    java.util.Iterator<?> it = map.keySet().iterator();
    while (it.hasNext()) {
        Object nextKey = it.next();
        castedCopy.put(nextKey, map.get(nextKey));
    }
    return castedCopy;
}
Example 11
Project: xapi-master  File: TestsFailed.java View source code
private static String serialize(Map<Method, Throwable> result) {
    StringBuilder pass = new StringBuilder();
    StringBuilder fail = new StringBuilder("\n");
    for (Entry<Method, Throwable> e : result.entrySet()) {
        if (e.getValue() == null) {
            pass.append(e.getKey().getName()).append("\n (pass)");
        } else {
            fail.append(e.getKey().getName()).append("\n (FAIL):");
            print(fail, e.getValue());
        }
    }
    return fail.append(pass).toString();
}
Example 12
Project: sosies-generator-master  File: DefaultMapJsonSerializerTest.java View source code
public void testEmptyMapNoTypeSerialization() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testEmptyMapNoTypeSerialization");
    Map<java.lang.String, java.lang.String> emptyMap = new HashMap<java.lang.String, java.lang.String>();
    JsonElement element = gson.toJsonTree(emptyMap, emptyMap.getClass());
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2671, (element instanceof com.google.gson.JsonObject));
    JsonObject emptyMapJsonObject = ((JsonObject) (element));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 2673, emptyMapJsonObject.entrySet(), 2672, emptyMapJsonObject.entrySet().isEmpty());
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 13
Project: gatein-portal-master  File: AttributesState.java View source code
public AttributesState.Builder attributes(Map<? extends String, ? extends String> attributes) {
    if (attributes != null) {
        if (attributes.size() > 0) {
            if (map == null) {
                int attributesSize = attributes.size();
                map = new HashMap<String, String>(attributesSize + attributesSize / 2);
            }
            for (Map.Entry<? extends String, ? extends String> en : attributes.entrySet()) {
                if (en.getValue() == null) {
                    /* here we follow what is in SimpleAttributes */
                    map.remove(en.getKey());
                } else {
                    map.put(en.getKey(), en.getValue());
                }
            }
        }
    }
    return this;
}
Example 14
Project: google-web-toolkit-svnmirror-master  File: TreeMapTest.java View source code
/**
   * Verify that two Maps are deeply equivalent.
   * 
   * @param expected
   * @param actual
   */
private static <K, V> void _assertEquals(Map<K, V> expected, Map<K, V> actual) {
    assertEquals(expected.isEmpty(), actual.isEmpty());
    assertEquals(expected.size(), actual.size());
    _assertEquals(expected.keySet(), actual.keySet());
    _assertEquals(expected.entrySet(), actual.entrySet());
    // One might think that the following would true:
    // assertEquals(expected.values(), actual.values());
    // The following verifies what i would perceive as a bug in the jre
    // (rlo). The implementation of the Collection returned by the values method
    // does not implement equals sensibly.
    assertFalse(expected.values().equals(actual.values()));
    _assertEquals(expected.values(), actual.values());
}
Example 15
Project: DrakkarKeel-master  File: _ConfigurationDelD.java View source code
public void sendSAMI(final byte[] request, java.util.Map<String, String> __ctx) throws IceInternal.LocalExceptionWrapper, drakkar.oar.slice.error.RequestException {
    final Ice.Current __current = new Ice.Current();
    __initCurrent(__current, "sendSAMI", Ice.OperationMode.Normal, __ctx);
    IceInternal.Direct __direct = null;
    try {
        __direct = new IceInternal.Direct(__current) {

            public Ice.DispatchStatus run(Ice.Object __obj) {
                Configuration __servant = null;
                try {
                    __servant = (Configuration) __obj;
                } catch (ClassCastException __ex) {
                    throw new Ice.OperationNotExistException(__current.id, __current.facet, __current.operation);
                }
                try {
                    __servant.sendSAMI(request, __current);
                    return Ice.DispatchStatus.DispatchOK;
                } catch (Ice.UserException __ex) {
                    setUserException(__ex);
                    return Ice.DispatchStatus.DispatchUserException;
                }
            }
        };
        try {
            Ice.DispatchStatus __status = __direct.servant().__collocDispatch(__direct);
            if (__status == Ice.DispatchStatus.DispatchUserException) {
                __direct.throwUserException();
            }
            assert __status == Ice.DispatchStatus.DispatchOK;
        } finally {
            __direct.destroy();
        }
    } catch (drakkar.oar.slice.error.RequestExceptionIce.SystemException |  __ex) {
        throw __ex;
    } catch (java.lang.Throwable __ex) {
        IceInternal.LocalExceptionWrapper.throwWrapper(__ex);
    }
}
Example 16
Project: Magnolia-master  File: NodeMapWrapper.java View source code
/**
     * @see java.util.Map#entrySet()
     */
@Override
public Set entrySet() {
    Collection<NodeData> nodeDataCollection = getWrappedContent().getNodeDataCollection();
    Set<Map.Entry> keys = new HashSet<Map.Entry>();
    for (Iterator<NodeData> iter = nodeDataCollection.iterator(); iter.hasNext(); ) {
        NodeData nd = iter.next();
        final String key = nd.getName();
        final String value = nd.getString();
        keys.add(new Map.Entry() {

            @Override
            public Object getKey() {
                return key;
            }

            @Override
            public Object getValue() {
                return value;
            }

            @Override
            public Object setValue(Object value) {
                return value;
            }
        });
    }
    return keys;
}
Example 17
Project: tdq-studio-se-master  File: DBMap.java View source code
/*
     * (non-Javadoc)
     * 
     * @see org.talend.dataquality.indicators.mapdb.AbstractDB#subList(long, long, java.util.Map,
     * org.talend.cwm.indicator.DataValidation)
     */
@Override
public List<Object[]> subList(long fromIndex, long toIndex, Map<Long, K> indexMap, DataValidation dataValiator) {
    boolean stratToRecord = false;
    List<Object[]> returnList = new ArrayList<Object[]>();
    if (!checkIndex(fromIndex, toIndex)) {
        return returnList;
    }
    K fromKey = null;
    K toKey = null;
    if (indexMap != null) {
        fromKey = indexMap.get(fromIndex);
        toKey = indexMap.get(toIndex);
    }
    Iterator<K> iterator = null;
    long index = 0l;
    if (fromKey == null) {
        iterator = this.iterator();
    } else if (toKey == null) {
        NavigableSet<K> tailSet = tailSet(fromKey, true);
        index = fromIndex;
        iterator = tailSet.iterator();
    } else {
        NavigableSet<K> tailSet = subSet(fromKey, toKey);
        index = fromIndex;
        iterator = tailSet.iterator();
    }
    while (iterator.hasNext()) {
        K next = iterator.next();
        if (dataValiator != null) {
            V v = this.get(next);
            if (!dataValiator.isValid(v)) {
                continue;
            }
        }
        if (index == 0 && fromKey == null && indexMap != null) {
            indexMap.put(0l, next);
        }
        if (index == fromIndex) {
            stratToRecord = true;
        }
        if (index == toIndex) {
            if (toKey == null && indexMap != null) {
                indexMap.put(toIndex, next);
            }
            break;
        }
        if (stratToRecord == true) {
            V v = this.get(next);
            if (v.getClass().isArray()) {
                returnList.add((Object[]) v);
            } else if (List.class.isInstance(v)) {
                returnList.add(((List<?>) v).toArray());
            } else {
                returnList.add(new Object[] { v });
            }
        }
        index++;
    }
    return returnList;
}
Example 18
Project: WS171-development-master  File: ClassSourcerTest.java View source code
@Test
public void testTemplateClassSource() throws Exception {
    StringWriter sw = new StringWriter();
    ClassReader cr = new ClassReader("data/TestTemplateClass");
    ClassSourcer jw = new ClassSourcer(new Output(sw));
    cr.accept(jw, 0);
    assertSourceEquals("package data;\n" + "public class TestTemplateClass<T extends java.io.InputStream, U extends java.lang.Object> extends java.lang.Object {\n" + "    private final java.util.Map<T, U> mMap_T_U;\n" + "    public java.util.Map<java.util.ArrayList<T>, java.util.Map<java.lang.String, java.util.ArrayList<U>>> mMap_T_S_U;\n" + "    public TestTemplateClass() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public java.util.Map<T, U> getMap_T_U() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public java.util.Map<java.util.ArrayList<T>, java.util.Map<java.lang.String, java.util.ArrayList<U>>> getMap_T_S_U() {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public void draw(java.util.List<? extends org.w3c.dom.css.Rect> arg0) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public static <T extends java.lang.Comparable<? super T>> void sort(java.util.List<T> arg0) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "    public <X extends T, Y extends java.lang.Object> void getMap(java.util.List<T> arg0, java.util.Map<T, U> arg1, java.util.Map<X, java.util.Set<? super Y>> arg2) {\n" + "        throw new RuntimeException(\"Stub\");\n" + "    }\n" + "}", sw.toString());
}
Example 19
Project: Restlib-master  File: JSONRestRequest.java View source code
@Override
public boolean setContent(HashMap<String, Object> data) {
    if (this.getMethod() == RestRequest.GET_METHOD)
        buildGetURI(data);
    try {
        JSONStringer holder = new JSONStringer().object();
        Iterator<Entry<String, Object>> it = data.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> e = it.next();
            holder.key(e.getKey().toString()).value(e.getValue());
        }
        holder.endObject();
        content = holder.toString();
    } catch (Exception e) {
        return false;
    }
    return true;
}
Example 20
Project: dk-master  File: IInvestServiceTest.java View source code
@Test
public void testSelectSuccessRecordPage() {
    PageDo page = new PageDo();
    Map<String, Object> parameterMap = new HashMap<String, Object>();
    //parameterMap.put("number", number);
    //parameterMap.put("publishTimeStart", publishTimeStart);
    //parameterMap.put("endTime", endTime);
    //parameterMap.put("investor", user.getId());
    //parameterMap.put("userName", userName);
    //新旧page类不同,需要转换
    page.setPageNum(1);
    page.setPageSize(10);
    page.setTotalNum(10);
    investService.selectInvestSuccessRecordPage(parameterMap, page);
}
Example 21
Project: FreeBuilder-master  File: ImportManagerTest.java View source code
@Test
public void testTypeMirrorShortening() {
    ImportManager manager = new ImportManager.Builder().build();
    assertEquals("String", manager.shorten(newTopLevelClass("java.lang.String")));
    assertEquals("List", manager.shorten(newTopLevelClass("java.util.List")));
    assertEquals("java.awt.List", manager.shorten(newTopLevelClass("java.awt.List")));
    ClassTypeImpl mapType = newTopLevelClass("java.util.Map");
    assertEquals("Map", manager.shorten(mapType));
    assertEquals("Map.Entry", manager.shorten(newNestedClass(mapType.asElement(), "Entry")));
    assertThat(manager.getClassImports()).containsExactly("java.util.List", "java.util.Map").inOrder();
}
Example 22
Project: geotools-old-master  File: sldComplexTypes.java View source code
public Object getValue(Element element, ElementValue[] value, Attributes attrs1, Map hints) throws OperationNotSupportedException, SAXException {
    ContrastEnhancement symbol = new ContrastEnhancementImpl();
    for (int i = 0; i < value.length; i++) {
        if ((value[i] == null) || value[i].getElement() == null) {
            continue;
        }
        Element e = value[i].getElement();
        if (elems[NORMALIZE].getName().equals(e.getName()))
            // (Graphic)value[i].getValue()
            symbol.setNormalize();
        if (elems[HISTORGRAM].getName().equals(e.getName()))
            // (Graphic)value[i].getValue()
            symbol.setHistogram();
        if (elems[GAMMAVALUE].getName().equals(e.getName())) {
            symbol.setGammaValue(FilterFactoryFinder.createFilterFactory().createLiteralExpression(((Double) value[i].getValue()).doubleValue()));
        }
    }
    return symbol;
}
Example 23
Project: org.openntf.domino-master  File: DominoDocumentMapAdapter.java View source code
@Override
public Iterator<java.util.Map.Entry<String, Object>> iterator() {
    final Iterator<String> keyIt = keySet().iterator();
    return new Iterator<Map.Entry<String, Object>>() {

        private String currentKey;

        @Override
        public boolean hasNext() {
            return keyIt.hasNext();
        }

        @Override
        public java.util.Map.Entry<String, Object> next() {
            currentKey = keyIt.next();
            final String key = currentKey;
            return new java.util.Map.Entry<String, Object>() {

                @Override
                public String getKey() {
                    return key;
                }

                @Override
                public Object getValue() {
                    return get(key);
                }

                @Override
                public Object setValue(final Object value) {
                    return put(key, value);
                }
            };
        }

        @Override
        public void remove() {
            DominoDocumentMapAdapter.this.remove(currentKey);
        }
    };
}
Example 24
Project: teiid-designer-master  File: PasteContributor.java View source code
// ===========================================================================================================================
// Controller Methods
/**
     * @see org.teiid.designer.core.metamodel.IPasteContributor#contribute(java.util.Map, java.lang.String)
     * @since 4.3.2
     */
@Override
public void contribute(final Map map, final String uri) {
    // Contribute if pasting into an XML Document model
    if (XmlDocumentPackage.eNS_URI.equals(uri)) {
        // Create UUID map for copied objects
        final Map uuidMap = new HashMap(map.size());
        for (final Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
            final Entry entry = (Entry) iter.next();
            final Object obj = entry.getKey();
            if (obj instanceof EObject) {
                uuidMap.put(ModelerCore.getObjectIdString((EObject) obj), ModelerCore.getObjectIdString((EObject) entry.getValue()));
            }
        }
        // Replace UUID's of clipboard objects in pasted object choice criteria with UUID's of corresponding pasted objects
        for (final Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
            final Entry entry = (Entry) iter.next();
            final Object obj = entry.getValue();
            if (obj instanceof XmlElement) {
                final XmlElement pastedElem = (XmlElement) obj;
                final String criteria = pastedElem.getChoiceCriteria();
                if (criteria != null) {
                    final StringBuffer newCriteria = new StringBuffer();
                    int startNdx = 0;
                    int uuidNdx = criteria.indexOf(UUID.PROTOCOL);
                    while (uuidNdx >= 0) {
                        newCriteria.append(criteria.substring(startNdx, uuidNdx));
                        final int endNdx = uuidNdx + UUID.FQ_LENGTH;
                        final String uuid = criteria.substring(uuidNdx, endNdx);
                        final String pastedUuid = (String) uuidMap.get(uuid);
                        if (pastedUuid == null) {
                            // Must be either not one of the pasted objects or an invalid UUID to begin with
                            newCriteria.append(uuid);
                        } else {
                            newCriteria.append(pastedUuid);
                        }
                        startNdx = endNdx;
                        uuidNdx = criteria.indexOf(UUID.PROTOCOL, startNdx);
                    }
                    newCriteria.append(criteria.substring(startNdx));
                    pastedElem.setChoiceCriteria(newCriteria.toString());
                }
            }
        }
    }
}
Example 25
Project: records-management-master  File: RecordableVersionPolicyAuditEvent.java View source code
/**
     * @see org.alfresco.repo.node.NodeServicePolicies.OnUpdatePropertiesPolicy#onUpdateProperties(org.alfresco.service.cmr.repository.NodeRef, java.util.Map, java.util.Map)
     */
@Override
@Behaviour(kind = BehaviourKind.CLASS, type = "cm:cmobject")
public void onUpdateProperties(NodeRef nodeRef, Map<QName, Serializable> before, Map<QName, Serializable> after) {
    if (before.get(PROP_RECORDABLE_VERSION_POLICY) != after.get(PROP_RECORDABLE_VERSION_POLICY)) {
        recordsManagementAuditService.auditEvent(nodeRef, getName(), before, after, true, true);
    }
}
Example 26
Project: openjdk-master  File: GenericStringTest.java View source code
public static void main(String... args) throws ReflectiveOperationException {
    int failures = 0;
    String[][] nested = { { "" } };
    int[][] intArray = { { 1 } };
    failures += checkToGenericString(int.class, "int");
    failures += checkToGenericString(void.class, "void");
    failures += checkToGenericString(args.getClass(), "java.lang.String[]");
    failures += checkToGenericString(nested.getClass(), "java.lang.String[][]");
    failures += checkToGenericString(intArray.getClass(), "int[][]");
    failures += checkToGenericString(java.util.Map.class, "public abstract interface java.util.Map<K,V>");
    Field f = GenericStringTest.class.getDeclaredField("mixed");
    // The expected value includes "<K,V>" rather than
    // "<...String,...Integer>" since the Class object rather than
    // Type objects is being queried.
    failures += checkToGenericString(f.getType(), "java.util.Map<K,V>[]");
    f = GenericStringTest.class.getDeclaredField("mixed2");
    failures += checkToGenericString(f.getType(), "java.util.Map<K,V>[][]");
    for (Class<?> clazz : List.of(GenericStringTest.class, AnInterface.class, LocalMap.class, AnEnum.class, AnotherEnum.class)) {
        failures += checkToGenericString(clazz, clazz.getAnnotation(ExpectedGenericString.class).value());
    }
    if (failures > 0) {
        throw new RuntimeException();
    }
}
Example 27
Project: octarine-master  File: MapSerialiser.java View source code
@Override
public void unsafeAccept(JsonGenerator j, Map<String, ? extends T> ts) throws IOException {
    j.writeStartObject();
    SafeSerialiser<Map.Entry<String, ? extends T>> entrySafeSerialiser = ( j2,  e) -> {
        j2.writeFieldName(e.getKey());
        valueSerialiser.accept(j2, e.getValue());
    };
    ts.entrySet().forEach( e -> {
        entrySafeSerialiser.accept(j, e);
    });
    j.writeEndObject();
}
Example 28
Project: magnificent-mileage-master  File: TravelModeWrapperTest.java View source code
@Test
public void testToTraverseMode() {
    Map<TravelMode, TraverseMode> modeMap = new HashMap<TravelMode, TraverseMode>();
    modeMap.put(TravelMode.BICYCLE, TraverseMode.BICYCLE);
    modeMap.put(TravelMode.CAR, TraverseMode.CAR);
    modeMap.put(TravelMode.CUSTOM_MOTOR_VEHICLE, TraverseMode.CUSTOM_MOTOR_VEHICLE);
    modeMap.put(TravelMode.WALK, TraverseMode.WALK);
    modeMap.put(TravelMode.ANY_TRAIN, TraverseMode.TRAINISH);
    modeMap.put(TravelMode.ANY_TRANSIT, TraverseMode.TRANSIT);
    for (TravelMode travelMode : modeMap.keySet()) {
        TraverseMode expectedTraverseMode = modeMap.get(travelMode);
        TraverseMode actualTraverseMode = (new TravelModeWrapper(travelMode)).toTraverseMode();
        assertEquals(expectedTraverseMode, actualTraverseMode);
    }
}
Example 29
Project: java8-tutorial-master  File: Lock4.java View source code
public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(2);
    Map<String, String> map = new HashMap<>();
    StampedLock lock = new StampedLock();
    executor.submit(() -> {
        long stamp = lock.writeLock();
        try {
            ConcurrentUtils.sleep(1);
            map.put("foo", "bar");
        } finally {
            lock.unlockWrite(stamp);
        }
    });
    Runnable readTask = () -> {
        long stamp = lock.readLock();
        try {
            System.out.println(map.get("foo"));
            ConcurrentUtils.sleep(1);
        } finally {
            lock.unlockRead(stamp);
        }
    };
    executor.submit(readTask);
    executor.submit(readTask);
    ConcurrentUtils.stop(executor);
}
Example 30
Project: btpka3.github.com-master  File: Config.java View source code
public void afterPropertiesSet() throws Exception {
    if (annotationActionEndpointMapping != null) {
        Map<String, SmartEndpointInterceptor> smartInterceptors = BeanFactoryUtils.beansOfTypeIncludingAncestors(getApplicationContext(), SmartEndpointInterceptor.class, true, false);
        if (!smartInterceptors.isEmpty()) {
            SmartEndpointInterceptor[] interceptors = smartInterceptors.values().toArray(new SmartEndpointInterceptor[smartInterceptors.size()]);
            //                annotationActionEndpointMapping.setPreInterceptors(interceptors);
            annotationActionEndpointMapping.setPostInterceptors(interceptors);
        }
    }
}
Example 31
Project: expenditures-master  File: MissionProcessProvider.java View source code
@Override
public Collection getSearchResults(Map<String, String> argsMap, String value, int maxCount) {
    final String currentValue = StringUtils.trim(value);
    final List<MissionProcess> result = new ArrayList<MissionProcess>();
    final MissionSystem missionSystem = MissionSystem.getInstance();
    for (final MissionProcess missionProcess : missionSystem.getMissionProcessesSet()) {
        String[] processIdParts = missionProcess.getProcessNumber().split("/M");
        if (missionProcess.getProcessIdentification().equals(currentValue) || processIdParts[processIdParts.length - 1].equals(currentValue)) {
            result.add(missionProcess);
        }
    }
    return result;
}
Example 32
Project: keycloak-master  File: ClientTemplateQueryPredicate.java View source code
@Override
public boolean test(Map.Entry<String, Revisioned> entry) {
    Object value = entry.getValue();
    if (value == null)
        return false;
    if (!(value instanceof ClientTemplateQuery))
        return false;
    ClientTemplateQuery query = (ClientTemplateQuery) value;
    return query.getTemplates().contains(template);
}
Example 33
Project: CDDA-Tileset-Editor-master  File: Tile.java View source code
public void replaceIndexes(Map<Integer, Integer> replace) {
    if (fg != null) {
        Integer n = replace.get(fg);
        if (n != null) {
            fg = n;
        }
    }
    if (bg != null) {
        Integer n = replace.get(bg);
        if (n != null) {
            bg = n;
        }
    }
}
Example 34
Project: spring4-showcase-master  File: PropertyResolverTest.java View source code
@Test
public void test() throws Exception {
    Map<String, Object> map = new HashMap<>();
    map.put("encoding", "gbk");
    PropertySource propertySource1 = new MapPropertySource("map", map);
    ResourcePropertySource propertySource2 = new ResourcePropertySource("resource", "classpath:resources.properties");
    MutablePropertySources propertySources = new MutablePropertySources();
    propertySources.addFirst(propertySource1);
    propertySources.addLast(propertySource2);
    PropertyResolver propertyResolver = new PropertySourcesPropertyResolver(propertySources);
    System.out.println(propertyResolver.getProperty("encoding"));
    System.out.println(propertyResolver.getProperty("no", "default"));
    System.out.println(propertyResolver.resolvePlaceholders("must be encoding ${encoding}"));
}
Example 35
Project: richfaces-master  File: UIInputNumber.java View source code
@Override
protected void validateValue(FacesContext context, Object newValue) {
    Map<String, Object> attributes = getAttributes();
    DoubleRangeValidator validator = new DoubleRangeValidator(doubleValue(attributes.get("maxValue")), doubleValue(attributes.get("minValue"))) {

        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            super.validate(context, component, UIInputNumber.this.getSubmittedValue());
        }
    };
    addValidator(validator);
    super.validateValue(context, newValue);
    removeValidator(validator);
}
Example 36
Project: sonar-java-master  File: URLHashCodeAndEqualsCheck.java View source code
public void foo(URL url) throws Exception {
    // Noncompliant [[sc=5;ec=22]] {{Use the URI class instead.}}
    Map<URL, Integer> sites = new HashMap<>();
    // Noncompliant {{Use the URI class instead.}}
    Set<URL> otherSites = new HashSet<>();
    // Compliant
    URL homepage = new URL("http://sonarsource.com");
    // Noncompliant [[sc=5;ec=25]] {{Use the URI class instead.}}
    homepage.equals(url);
    // Noncompliant {{Use the URI class instead.}}
    homepage.hashCode();
    // Compliant
    homepage.getPath();
    // Compliant
    Map<URI, URL> uriToUrl = new HashMap<>();
    // Compliant
    Map uriToUrl2 = new Hashmap();
    // Compliant
    Map<> uriToUrl3 = new Hashmap<>();
}
Example 37
Project: ARTPart-master  File: Main.java View source code
public static void main(String[] args) throws Exception {
    // These charsets must be provided; anything else is optional.
    List<String> standardCharsets = Arrays.asList("US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16");
    SortedMap<String, Charset> all = Charset.availableCharsets();
    Set<String> needed = new HashSet<String>(standardCharsets);
    for (Map.Entry<String, Charset> e : all.entrySet()) {
        String canonicalName = e.getKey();
        needed.remove(canonicalName);
    }
    System.out.println("Missing: " + needed);
}
Example 38
Project: FeedMeAndroid-master  File: Pay.java View source code
public static void makePayment() {
    Stripe.apiKey = "L8px8dWKTJmab3qzAuq7Vh4hwp3sXbK4";
    Map<String, Object> chargeMap = new HashMap<String, Object>();
    chargeMap.put("amount", 100);
    chargeMap.put("currency", "usd");
    Map<String, Object> cardMap = new HashMap<String, Object>();
    cardMap.put("number", "4242424242424242");
    cardMap.put("exp_month", 12);
    cardMap.put("exp_year", 2012);
    chargeMap.put("card", cardMap);
    try {
        Charge charge = Charge.create(chargeMap);
        System.out.println(charge);
    } catch (StripeException e) {
        e.printStackTrace();
    }
}
Example 39
Project: extension-aws-master  File: BsfScriptRunner.java View source code
@Override
public Object exec(Script inScript, Map context) throws OpenEditException {
    BSFManager bsfManager = new BSFManager();
    try {
        // expose standard items in the context
        for (Iterator iter = context.keySet().iterator(); iter.hasNext(); ) {
            String element = (String) iter.next();
            Object val = context.get(element);
            if (val != null) {
                bsfManager.declareBean(element, val, val.getClass());
            }
        }
        bsfManager.exec(BSFManager.getLangFromFilename(inScript.getDescription()), inScript.getDescription(), 0, 0, inScript.getScriptText());
    } catch (BSFException ex) {
        Throwable ext = ex.getTargetException();
        if (ext instanceof OpenEditException) {
            throw (OpenEditException) ext;
        }
        throw new OpenEditException(ext);
    }
    return null;
}
Example 40
Project: abmash-master  File: JavaScriptResult.java View source code
public Boolean hasAdequateReturnValue() {
    // TODO other return values
    if (returnValue instanceof WebElement) {
        return true;
    }
    if (returnValue instanceof Double) {
        return (Double) returnValue != 0.0;
    }
    if (returnValue instanceof Long) {
        return (Long) returnValue != 0;
    }
    if (returnValue instanceof Boolean) {
        return (Boolean) returnValue;
    }
    if (returnValue instanceof String) {
        return !((String) returnValue).equals("");
    }
    if (returnValue instanceof List<?>) {
        return !((List<?>) returnValue).isEmpty();
    }
    if (returnValue instanceof Map<?, ?>) {
        return !((Map<?, ?>) returnValue).isEmpty();
    }
    return false;
}
Example 41
Project: ehour-master  File: FieldProcessorEmbeddableImpl.java View source code
@SuppressWarnings("unchecked")
@Override
public <PK extends Serializable, T extends DomainObject<PK, ?>> void process(Field targetField, T targetObject, Map<Class<?>, Object> embeddables, Object parsedColumnValue) throws IllegalAccessException, InstantiationException {
    Class<?> type = targetField.getDeclaringClass();
    Object embeddable;
    if (embeddables.containsKey(type)) {
        embeddable = embeddables.get(type);
    } else {
        embeddable = type.newInstance();
        embeddables.put(type, embeddable);
    }
    targetField.set(embeddable, parsedColumnValue);
}
Example 42
Project: Klyph-master  File: TagSerializer.java View source code
public void serializeMap(Map<String, List<Tag>> tags, JSONObject json, String field) {
    JSONObject tagObject = new JSONObject();
    for (Iterator<String> iterator = tags.keySet().iterator(); iterator.hasNext(); ) {
        String key = (String) iterator.next();
        List<Tag> tag = tags.get(key);
        try {
            tagObject.put(key, super.serializeArray(tag));
        } catch (JSONException e) {
            Log.d("TagSerializer", "JsonException " + e.getMessage());
        }
    }
    try {
        json.put(field, tagObject);
    } catch (JSONException e) {
        Log.d("TagSerializer", "JsonException " + e.getMessage());
    }
}
Example 43
Project: parkandrideAPI-master  File: NotNullElementMapValidator.java View source code
@Override
public boolean isValid(Map<?, ?> map, ConstraintValidatorContext context) {
    context.disableDefaultConstraintViolation();
    boolean ok = true;
    if (map != null) {
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (entry.getValue() == null) {
                context.buildConstraintViolationWithTemplate(message).addBeanNode().inIterable().atKey(entry.getKey()).addConstraintViolation();
                ok = false;
            }
        }
    }
    return ok;
}
Example 44
Project: polly-master  File: GBPasteService.java View source code
@Override
public String doPaste(String message) throws IOException {
    Map<String, String> properties = new HashMap<String, String>(10);
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("nick", "polly");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("lang", "text");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("private", "1");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("desc", "polly log entries");
    //$NON-NLS-1$
    properties.put("code", message);
    return this.postRequest(new URL("http://gbpaste.org/upload"), //$NON-NLS-1$
    properties).getResultURL();
}
Example 45
Project: REST-OCD-Services-master  File: OcdBenchmarkFactory.java View source code
@Override
public OcdBenchmark getInstance(GraphCreationType creationType, Map<String, String> parameters) throws InstantiationException, IllegalAccessException {
    if (isInstantiatable(creationType)) {
        OcdBenchmark benchmark = (OcdBenchmark) creationType.getCreationMethodClass().newInstance();
        benchmark.setParameters(parameters);
        return benchmark;
    }
    throw new IllegalStateException("This creation type is not an instantiatable benchmark.");
}
Example 46
Project: Desktop-master  File: GoogleScholarSearchEngine.java View source code
@Override
public Callable<Collection<MetaData>> getExtractor(String query, Map<ExtractorConfigKey, Object> options, MetaDataListener listener) throws MalformedConfigException {
    Map<ExtractorConfigKey, Object> queryConfig = this.config;
    queryConfig.putAll(options);
    queryConfig.put(CommonConfigKeys.SEARCHVALUE, query);
    return new GoogleScholarExtractor(queryConfig, listener);
}
Example 47
Project: many-ql-master  File: QuestionFactory.java View source code
public Question questionType(uva.sc.ql.statements.Question question, QuestionsPropertiesVisitor questionProperties, Map<ID, List<ID>> patronElements, List<Component> componentList) {
    Type type = question.getType();
    Question questionType = null;
    if (type.equals(new Boolean())) {
        questionType = new CheckBoxQuestion(patronElements, questionProperties, componentList);
    } else if (type.equals(new String())) {
        questionType = new TextBoxQuestion(patronElements, questionProperties, componentList);
    } else {
        questionType = new CalculatedQuestion(patronElements, questionProperties, componentList);
    }
    return questionType;
}
Example 48
Project: Katari-master  File: ModuleWithEntryPointsAndWebletsTest.java View source code
@SuppressWarnings("deprecation")
public void testInit() {
    Map<String, ServletAndParameters> entryPoints;
    entryPoints = new HashMap<String, ServletAndParameters>();
    Map<String, String> weblets = new HashMap<String, String>();
    ModuleWithEntryPointsAndWeblets module;
    module = new ModuleWithEntryPointsAndWeblets(entryPoints, weblets);
    ModuleContext context = createMock(ModuleContext.class);
    context.registerEntryPoints(entryPoints);
    context.registerWeblets(weblets);
    replay(context);
    module.init(context);
    verify(context);
}
Example 49
Project: NucleusFramework-master  File: AgentHashMapTest.java View source code
@Test
public void test() {
    AgentMap<String, ISubscriberAgent> map = new AgentHashMap<String, ISubscriberAgent>() {

        Map<String, ISubscriberAgent> internalMap = new HashMap<>(10);

        @Override
        protected Map<String, ISubscriberAgent> map() {
            return internalMap;
        }
    };
    ISubscriberAgent agent1 = new SubscriberAgent() {
    };
    ISubscriberAgent agent2 = new SubscriberAgent() {
    };
    ISubscriberAgent agent3 = new SubscriberAgent() {
    };
    MapRunnable<String, ISubscriberAgent> test = new MapRunnable<>(map, "a", "b", "c", agent1, agent2, agent3);
    test.run();
}
Example 50
Project: spork-streaming-master  File: AvroMapWrapper.java View source code
@Override
public Set<java.util.Map.Entry<CharSequence, Object>> entrySet() {
    Set<java.util.Map.Entry<CharSequence, Object>> theSet = Sets.newHashSetWithExpectedSize(innerMap.size());
    for (java.util.Map.Entry<CharSequence, Object> e : innerMap.entrySet()) {
        CharSequence k = e.getKey();
        Object v = e.getValue();
        if (k instanceof Utf8) {
            k = k.toString();
        }
        if (v instanceof Utf8) {
            v = v.toString();
        }
        theSet.add(new AbstractMap.SimpleEntry<CharSequence, Object>(k, v));
    }
    return theSet;
}
Example 51
Project: nmonvisualizer-master  File: XMLParserHelper.java View source code
public static Map<String, String> parseAttributes(String unparsedAttributes) {
    if ((unparsedAttributes == null) || "".equals(unparsedAttributes)) {
        return java.util.Collections.emptyMap();
    }
    String[] parts = ATTRIBUTE_SPLIITTER.split(unparsedAttributes);
    int size = parts.length / 2;
    Map<String, String> attributes = new java.util.HashMap<String, String>(size);
    // drop odd numbered end index from array
    size *= 2;
    for (int i = 0; i < size; ) {
        attributes.put(DataHelper.newString(parts[i++].trim()), DataHelper.newString(parts[i++].trim()));
    }
    return attributes;
}