javatips.net counter

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: PersistentSet.java View source code
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
    Type elementType = persister.getElementType();
    final java.util.Map sn = (java.util.Map) getSnapshot();
    ArrayList deletes = new ArrayList(sn.size());
    Iterator iter = sn.keySet().iterator();
    while (iter.hasNext()) {
        Object test = iter.next();
        if (!set.contains(test)) {
            // the element has been removed from the set
            deletes.add(test);
        }
    }
    iter = set.iterator();
    while (iter.hasNext()) {
        Object test = iter.next();
        Object oldValue = sn.get(test);
        if (oldValue != null && elementType.isDirty(test, oldValue, getSession())) {
            // the element has changed
            deletes.add(oldValue);
        }
    }
    return deletes.iterator();
}
Example 3
Project: eclipselink.runtime-master  File: MapValueAttributeAccessor.java View source code
public Object getAttributeValueFromObject(Object object) throws DescriptorException {
    Object value = nestedAccessor.getAttributeValueFromObject(object);
    if (null == value) {
        return null;
    }
    Object results = containerPolicy.containerInstance(((Map) value).size());
    Set<Entry> entrySet = ((Map) value).entrySet();
    if (null == entrySet) {
        return results;
    }
    for (Entry entry : entrySet) {
        MapEntry nextEntry;
        try {
            nextEntry = (MapEntry) generatedEntryClass.newInstance();
        } catch (Exception e) {
            return null;
        }
        nextEntry.setKey(entry.getKey());
        nextEntry.setValue(entry.getValue());
        containerPolicy.addInto(nextEntry, results, null);
    }
    return results;
}
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: CrashlyticsTracker.java View source code
@Override
public void onInitExceptionHandler(Map<String, String> metadata) {
    if (metadata != null) {
        for (Entry<String, String> entry : metadata.entrySet()) {
            if (entry.getValue() != null) {
                Crashlytics.getInstance().core.setString(entry.getKey(), entry.getValue());
            }
        }
    }
}
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: GetItemRequestMarshaller.java View source code
public Request<GetItemRequest> marshall(GetItemRequest getItemRequest) {
    if (getItemRequest == null) {
        throw new AmazonClientException("Invalid argument passed to marshall(GetItemRequest)");
    }
    Request<GetItemRequest> request = new DefaultRequest<GetItemRequest>(getItemRequest, "AmazonDynamoDB");
    String target = "DynamoDB_20120810.GetItem";
    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 (getItemRequest.getTableName() != null) {
            String tableName = getItemRequest.getTableName();
            jsonWriter.name("TableName");
            jsonWriter.value(tableName);
        }
        if (getItemRequest.getKey() != null) {
            java.util.Map<String, AttributeValue> key = getItemRequest.getKey();
            jsonWriter.name("Key");
            jsonWriter.beginObject();
            for (java.util.Map.Entry<String, AttributeValue> keyEntry : key.entrySet()) {
                AttributeValue keyValue = keyEntry.getValue();
                if (keyValue != null) {
                    jsonWriter.name(keyEntry.getKey());
                    AttributeValueJsonMarshaller.getInstance().marshall(keyValue, jsonWriter);
                }
            }
            jsonWriter.endObject();
        }
        if (getItemRequest.getAttributesToGet() != null) {
            java.util.List<String> attributesToGet = getItemRequest.getAttributesToGet();
            jsonWriter.name("AttributesToGet");
            jsonWriter.beginArray();
            for (String attributesToGetItem : attributesToGet) {
                if (attributesToGetItem != null) {
                    jsonWriter.value(attributesToGetItem);
                }
            }
            jsonWriter.endArray();
        }
        if (getItemRequest.getConsistentRead() != null) {
            Boolean consistentRead = getItemRequest.getConsistentRead();
            jsonWriter.name("ConsistentRead");
            jsonWriter.value(consistentRead);
        }
        if (getItemRequest.getReturnConsumedCapacity() != null) {
            String returnConsumedCapacity = getItemRequest.getReturnConsumedCapacity();
            jsonWriter.name("ReturnConsumedCapacity");
            jsonWriter.value(returnConsumedCapacity);
        }
        if (getItemRequest.getProjectionExpression() != null) {
            String projectionExpression = getItemRequest.getProjectionExpression();
            jsonWriter.name("ProjectionExpression");
            jsonWriter.value(projectionExpression);
        }
        if (getItemRequest.getExpressionAttributeNames() != null) {
            java.util.Map<String, String> expressionAttributeNames = getItemRequest.getExpressionAttributeNames();
            jsonWriter.name("ExpressionAttributeNames");
            jsonWriter.beginObject();
            for (java.util.Map.Entry<String, String> expressionAttributeNamesEntry : expressionAttributeNames.entrySet()) {
                String expressionAttributeNamesValue = expressionAttributeNamesEntry.getValue();
                if (expressionAttributeNamesValue != null) {
                    jsonWriter.name(expressionAttributeNamesEntry.getKey());
                    jsonWriter.value(expressionAttributeNamesValue);
                }
            }
            jsonWriter.endObject();
        }
        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.0");
    }
    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: MtextLocationMap.java View source code
private void setMapValueToMin(java.util.Map<org.eclipse.emf.ecore.EObject, Integer> map, org.eclipse.emf.ecore.EObject element, int value) {
    // the map concurrently.
    synchronized (this) {
        if (element == null || value < 0)
            return;
        if (map.containsKey(element) && map.get(element) < value)
            return;
        map.put(element, value);
    }
}
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: JsonTreeTest.java View source code
@Test(timeout = 1000)
public void testToJsonTree_add1192() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testToJsonTree_add1192");
    TestTypes.BagOfPrimitives bag = new TestTypes.BagOfPrimitives(10L, 5, false, "foo");
    JsonElement json = gson.toJsonTree(bag);
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1719, json, 1718, json.isJsonObject());
    JsonObject obj = json.getAsJsonObject();
    Set<java.util.Map.Entry<java.lang.String, com.google.gson.JsonElement>> children = obj.entrySet();
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1721, children, 1720, children.size());
    assertContains(obj, new JsonPrimitive(10L));
    assertContains(obj, new JsonPrimitive(10L));
    assertContains(obj, new JsonPrimitive(5));
    assertContains(obj, new JsonPrimitive(false));
    assertContains(obj, new JsonPrimitive("foo"));
    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: SplittableComplexMap.java View source code
@Override
public Iterator<java.util.Map.Entry<K, V>> iterator() {
    return new Iterator<Map.Entry<K, V>>() {

        Iterator<K> keyIt = keys.iterator();

        ListIterator<V> valueIt = values.listIterator();

        public boolean hasNext() {
            assert keyIt.hasNext() == valueIt.hasNext();
            return keyIt.hasNext();
        }

        public java.util.Map.Entry<K, V> next() {
            return new Map.Entry<K, V>() {

                final K key = keyIt.next();

                final V value = valueIt.next();

                public K getKey() {
                    return key;
                }

                public V getValue() {
                    return value;
                }

                public V setValue(V value) {
                    valueIt.set(value);
                    return value;
                }
            };
        }

        public void remove() {
            keyIt.remove();
            valueIt.remove();
        }
    };
}
Example 15
Project: DrakkarKeel-master  File: _SessionContainerDelD.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) {
                SessionContainer __servant = null;
                try {
                    __servant = (SessionContainer) __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: PhoneNumbStatisticsExplorer.java View source code
@Override
public Map<String, String> getSubClassQueryMap() {
    Map<String, String> map = new HashMap<String, String>();
    switch(this.indicatorEnum) {
        case ValidPhoneCountIndicatorEnum:
        case PossiblePhoneCountIndicatorEnum:
        case ValidRegCodeCountIndicatorEnum:
        case InvalidRegCodeCountIndicatorEnum:
        case WellFormE164PhoneCountIndicatorEnum:
        case WellFormIntePhoneCountIndicatorEnum:
        case WellFormNationalPhoneCountIndicatorEnum:
            map.put(MENU_VIEW_ROWS, null);
            map.put(MENU_VIEW_VALUES, null);
            break;
        default:
    }
    return map;
}
Example 18
Project: WS171-development-master  File: SignatureSourcerTest.java View source code
@Test
public void testManyArgs() {
    SignatureReader reader = new SignatureReader("<X:TT;Y:Ljava/lang/Object;>(Ljava/util/List<TT;>;Ljava/util/Map<TT;TU;>;Ljava/util/Map<TX;Ljava/util/Set<-TY;>;>;)V");
    reader.accept(mSourcer);
    Assert.assertTrue(mSourcer.hasFormalsContent());
    String formals = mSourcer.formalsToString();
    Assert.assertEquals("<X extends T, Y extends java.lang.Object>", formals);
    String result = mSourcer.getReturnType().toString();
    Assert.assertEquals("void", result);
    ArrayList<SignatureSourcer> params = mSourcer.getParameters();
    Assert.assertNotNull(params);
    String[] array = toStringArray(params);
    Assert.assertArrayEquals(new String[] { "java.util.List<T>", "java.util.Map<T, U>", "java.util.Map<X, java.util.Set<? super Y>>" }, array);
}
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: WMSDescribeLayerTypes.java View source code
/* (non-Javadoc)
         * @see org.geotools.xml.schema.Type#getValue(org.geotools.xml.schema.Element, org.geotools.xml.schema.ElementValue[], org.xml.sax.Attributes, java.util.Map)
         */
public Object getValue(Element element, ElementValue[] value, Attributes attrs, Map hints) throws SAXException, OperationNotSupportedException {
    LayerDescription[] layerDescs = new LayerDescription[value.length];
    for (int i = 0; i < value.length; i++) {
        layerDescs[i] = (LayerDescription) value[i].getValue();
    }
    return layerDescs;
}
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: DiagramTargetMatcher.java View source code
/** 
     * @see org.teiid.designer.core.compare.TwoPhaseEObjectMatcher#addMappings(org.eclipse.emf.ecore.EReference, java.util.List, java.util.List, java.util.Map, org.eclipse.emf.mapping.Mapping, org.eclipse.emf.mapping.MappingFactory)
     * @since 4.2
     */
@Override
public void addMappings(final EReference reference, final List inputs, final List outputs, final Map inputsToOutputs, final Mapping mapping, final MappingFactory factory) {
    final Map inputEntityByTargetObject = new HashMap();
    // Loop over the inputs and find any of the above objects ...
    final Iterator iter = inputs.iterator();
    while (iter.hasNext()) {
        final Diagram diagram = (Diagram) iter.next();
        final EObject targetObject = diagram.getTarget();
        if (targetObject != null) {
            final Object outputTargetObject = inputsToOutputs.get(targetObject);
            inputEntityByTargetObject.put(outputTargetObject, diagram);
        }
    }
    // Loop over the outputs and find matches for any of the above objects ...
    final Iterator outputIter = outputs.iterator();
    while (outputIter.hasNext()) {
        final Diagram outputDiagram = (Diagram) outputIter.next();
        final EObject outputTraget = outputDiagram.getTarget();
        if (outputTraget != null) {
            final Diagram inputDiagram = (Diagram) inputEntityByTargetObject.get(outputTraget);
            if (inputDiagram != null) {
                inputs.remove(inputDiagram);
                outputIter.remove();
                addMapping(inputDiagram, outputDiagram, mapping, factory);
                inputsToOutputs.put(inputDiagram, outputDiagram);
            }
        }
    }
}
Example 25
Project: records-management-master  File: VitalRecordDefinitionAspect.java View source code
public Void doWork() {
    if (nodeService.exists(nodeRef) && nodeService.hasAspect(nodeRef, ASPECT_FILE_PLAN_COMPONENT)) {
        // check that vital record definition has been changed in the first place
        Map<QName, Serializable> changedProps = PropertyMap.getChangedProperties(before, after);
        if (changedProps.containsKey(PROP_VITAL_RECORD_INDICATOR) || changedProps.containsKey(PROP_REVIEW_PERIOD)) {
            recordsManagementActionService.executeRecordsManagementAction(nodeRef, "broadcastVitalRecordDefinition");
        }
    }
    return null;
}
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: Maps1.java View source code
public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        map.putIfAbsent(i, "val" + i);
    }
    map.forEach(( id,  val) -> System.out.println(val));
    map.computeIfPresent(3, ( num,  val) -> val + num);
    // val33
    System.out.println(map.get(3));
    map.computeIfPresent(9, ( num,  val) -> null);
    // false
    System.out.println(map.containsKey(9));
    map.computeIfAbsent(23,  num -> "val" + num);
    // true
    System.out.println(map.containsKey(23));
    map.computeIfAbsent(3,  num -> "bam");
    // val33
    System.out.println(map.get(3));
    // not found
    System.out.println(map.getOrDefault(42, "not found"));
    map.remove(3, "val3");
    // val33
    System.out.println(map.get(3));
    map.remove(3, "val33");
    // null
    System.out.println(map.get(3));
    map.merge(9, "val9", ( value,  newValue) -> value.concat(newValue));
    // val9
    System.out.println(map.get(9));
    map.merge(9, "concat", ( value,  newValue) -> value.concat(newValue));
    // val9concat
    System.out.println(map.get(9));
}
Example 30
Project: btpka3.github.com-master  File: FontTest.java View source code
/**
     * TODO 方法的作用是?
     *
     * @author zhangliangliang
     * @date 2013-12-25下午5:07:05
     *
     * @param args
     * @throws IOException
     */
public static void main(String[] args) throws IOException {
    Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
    attributes.put(TextAttribute.KERNING, TextAttribute.KERNING_ON);
    attributes.put(TextAttribute.TRACKING, TextAttribute.TRACKING_TIGHT);
    Font font = new Font("Arial", Font.BOLD, 40);
    font = font.deriveFont(attributes);
    BufferedImage img = new BufferedImage(500, 200, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    // set background
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, img.getWidth(), img.getHeight());
    g.setFont(font);
    g.setColor(Color.BLACK);
    FontMetrics metrics = g.getFontMetrics(font);
    g.drawString("HELLO testing", 0, metrics.getHeight());
    ImageIO.write(img, "jpg", new File("/test.jpg"));
}
Example 31
Project: expenditures-master  File: PersonAutoComplete.java View source code
@Override
public Collection getSearchResults(Map argsMap, String value, int maxCount) {
    Set<Person> people = new HashSet<Person>();
    String[] values = StringNormalizer.normalize(value).toLowerCase().split(" ");
    for (Person person : Bennu.getInstance().getPersonsSet()) {
        if (person.getUser() != null && person.getUser().getProfile() != null) {
            if (person.getUser().getProfile().getFullName() != null) {
                final String normalizedName = StringNormalizer.normalize(person.getUser().getProfile().getFullName()).toLowerCase();
                if (hasMatch(values, normalizedName)) {
                    people.add(person);
                }
            }
            if (person.getUser() != null && person.getUser().getUsername().indexOf(value) >= 0) {
                people.add(person);
            }
        }
    }
    return people;
}
Example 32
Project: keycloak-master  File: ClientQueryPredicate.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 ClientQuery))
        return false;
    ClientQuery query = (ClientQuery) value;
    if (client != null && !query.getClients().contains(client))
        return false;
    if (inRealm != null && !query.getRealm().equals(inRealm))
        return false;
    return true;
}
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;
}
Example 52
Project: cms-ce-master  File: TemplateProcessor.java View source code
public String process(final String name, final Map<String, Object> model) throws IOException {
    final Template template = this.config.getTemplate(name);
    try {
        final StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    } catch (final TemplateException e) {
        throw new IOException(e);
    }
}
Example 53
Project: arquillian_deprecated-master  File: ScopeAwareBean.java View source code
@SuppressWarnings("unchecked")
public String getScope() {
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    ExternalContext extCtx = facesCtx.getExternalContext();
    Map scopeMap = extCtx.getRequestMap();
    if (scopeMap.containsValue(this))
        return "request";
    scopeMap = facesCtx.getViewRoot().getViewMap();
    if (scopeMap.containsValue(this))
        return "view";
    scopeMap = extCtx.getSessionMap();
    if (scopeMap.containsValue(this))
        return "session";
    scopeMap = extCtx.getApplicationMap();
    if (scopeMap.containsValue(this))
        return "application";
    return "unknown";
}
Example 54
Project: O2OMobile_Android-master  File: Transmitter.java View source code
public static void transmit(Command c, Map h, String b, java.io.OutputStream out) throws IOException {
    StringBuffer message = new StringBuffer(c.toString());
    message.append("\n");
    if (h != null) {
        for (Iterator keys = h.keySet().iterator(); keys.hasNext(); ) {
            String key = (String) keys.next();
            String value = (String) h.get(key);
            message.append(key);
            message.append(":");
            message.append(value);
            message.append("\n");
        }
    }
    message.append("\n");
    if (b != null)
        message.append(b);
    message.append("\000");
    out.write(message.toString().getBytes(Command.ENCODING));
}
Example 55
Project: Campus-master  File: IntentUtil.java View source code
public static void start_activity(Activity activity, Class<?> cls, Map<String, Integer> params) {
    Intent intent = new Intent();
    intent.setClass(activity, cls);
    if (params != null) {
        for (Map.Entry<String, Integer> entry : params.entrySet()) {
            intent.putExtra(entry.getKey(), entry.getValue());
        }
    }
    activity.startActivity(intent);
    activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
Example 56
Project: aipo-master  File: CategoryIterator.java View source code
protected boolean filter() {
    java.util.Map.Entry entry = (java.util.Map.Entry) mapIterator.next();
    String entryKey = (String) entry.getKey();
    int pos = entryKey.indexOf('.');
    this.category = "";
    if (-1 == pos) {
        this.group = entryKey;
    } else {
        this.group = entryKey.substring(0, pos);
        int length = entryKey.length();
        if (length > pos + 1)
            this.category = entryKey.substring(pos + 1, length);
    }
    if (!findall && !entryKey.startsWith(this.key))
        // end of criteria
        return false;
    bucket = (HashMap) entry.getValue();
    bucketIterator = bucket.entrySet().iterator();
    iteratingMaps = false;
    if (bucketIterator.hasNext() == false)
        return false;
    return getPortletEntry();
}
Example 57
Project: JDK-master  File: ParserImplBase.java View source code
protected void setFields(Map map) {
    Set entries = map.entrySet();
    Iterator iter = entries.iterator();
    while (iter.hasNext()) {
        java.util.Map.Entry entry = (java.util.Map.Entry) (iter.next());
        final String name = (String) (entry.getKey());
        final Object value = entry.getValue();
        try {
            AccessController.doPrivileged(new PrivilegedExceptionAction() {

                public Object run() throws IllegalAccessException, IllegalArgumentException {
                    Field field = getAnyField(name);
                    field.setAccessible(true);
                    field.set(ParserImplBase.this, value);
                    return null;
                }
            });
        } catch (PrivilegedActionException exc) {
            throw wrapper.errorSettingField(exc.getCause(), name, value.toString());
        }
    }
    // Make sure that any extra initialization takes place after all the
    // fields are set from the map.
    complete();
}
Example 58
Project: phantom-pojos-master  File: PhantomPojo.java View source code
static PropertiesCapture wrapping(Map<String, Object> properties) {
    return new PropertiesCapture() {

        @Override
        public <P extends PhantomPojo<B>, B extends Supplier<P>> P with(Class<? extends P> klass) {
            PhantomBuilderClassPair<P, B> classPair = PhantomBuilderClassPair.forPhantomClass(klass);
            PropertySchema schema = classPair.getPropertySchema();
            PropertyStore store = schema.createStoreFromMap(properties, PojoPromoter::promote);
            return classPair.createPhantom(store);
        }
    };
}
Example 59
Project: iview-android-tv-master  File: IViewApi.java View source code
Uri buildApiUrl(String path, Map<String, String> params) {
    Uri.Builder uri = Uri.parse(API_URL).buildUpon();
    uri.appendPath(path);
    if (params != null) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            uri.appendQueryParameter(param.getKey(), param.getValue());
        }
    }
    return uri.build();
}
Example 60
Project: quickml-master  File: MapUtilsTest.java View source code
@Test
public void testGetEntryWithLowestValue() throws Exception {
    Map<String, Double> map = Maps.newHashMap();
    map.put("one", 1.0);
    map.put("onepointfive", 1.5);
    map.put("zeropointfive", 0.5);
    final Optional<Map.Entry<String, Double>> entryWithLowestValue = MapUtils.getEntryWithLowestValue(map);
    Assert.assertTrue(entryWithLowestValue.isPresent(), "Map isn't empty so it should return a result");
    Assert.assertEquals(entryWithLowestValue.get().getKey(), "zeropointfive");
    Assert.assertEquals(entryWithLowestValue.get().getValue(), 0.5);
}
Example 61
Project: FireflowEngine20-master  File: WorkflowStatementRemoteImpl.java View source code
//	/* (non-Javadoc)
//	 * @see org.fireflow.engine.WorkflowStatement#getCurrentProcessInstance()
//	 */
//	@Override
//	public ProcessInstance getCurrentProcessInstance() {
//		return null;
//	}
//
//	/* (non-Javadoc)
//	 * @see org.fireflow.engine.WorkflowStatement#getCurrentActivityInstance()
//	 */
//	@Override
//	public ActivityInstance getCurrentActivityInstance() {
//		return null;
//	}
//
//	/* (non-Javadoc)
//	 * @see org.fireflow.engine.WorkflowStatement#getLatestCreatedWorkItems()
//	 */
//	@Override
//	public List<WorkItem> getLatestCreatedWorkItems() {
//		return null;
//	}
/* (non-Javadoc)
	 * @see org.fireflow.engine.WorkflowStatement#setDynamicAssignmentHandler(java.lang.String, org.fireflow.engine.invocation.AssignmentHandler)
	 */
//	@Override
//	public WorkflowStatement setDynamicAssignmentHandler(String activityId,
//			AssignmentHandler dynamicAssignmentHandler) {
//		return null;
//	}
//	/* (non-Javadoc)
//	 * @see org.fireflow.engine.WorkflowStatement#setAttribute(java.lang.String, java.lang.Object)
//	 */
//	@Override
//	public WorkflowStatement setAttribute(String name, Object attr) {
//		return null;
//	}
/* (non-Javadoc)
	 * @see org.fireflow.engine.WorkflowStatement#startProcess(java.lang.String, int, java.lang.String, java.util.Map)
	 */
public ProcessInstance startProcess(String workflowProcessId, int version, String bizId, Map<String, Object> variables) throws InvalidModelException, WorkflowProcessNotFoundException, InvalidOperationException {
    if (!checkVariableMap(variables))
        return null;
    MapConvertor mapConvertor = new MapConvertor();
    mapConvertor.putAll(variables, MapConvertor.MAP_TYPE_VARIABLE);
    return this.workflowServer.startProcess2(this.remoteSession.getSessionId(), workflowProcessId, version, bizId, mapConvertor);
}
Example 62
Project: GeoGig-master  File: IniRepositoryFilter.java View source code
/**
     * Parses an ini section and adds it as a filter.
     * 
     * @param featurePath the path of the features to filter
     * @param config the ini
     */
private void parseFilter(String featurePath, Map<String, String> config) {
    if (featurePath != null) {
        String type = config.get(featurePath + ".type");
        String filter = config.get(featurePath + ".filter");
        addFilter(featurePath, type, filter);
    }
}
Example 63
Project: mkgmap-master  File: BoundaryLister.java View source code
/**
	 * @param args
	 * @throws IOException 
	 */
public static void main(String[] args) throws IOException {
    String boundsdir = args[0];
    String outDirName = boundsdir;
    if (args.length >= 2)
        outDirName = args[1];
    File outDir = new File(outDirName);
    if (outDir.exists()) {
        if (outDir.isDirectory() == false) {
            System.err.println("target is not a directory, output is written to bounds.txt");
            outDir = new File(".");
        }
    }
    List<String> bndFileNames = BoundaryUtil.getBoundaryDirContent(boundsdir);
    PrintWriter out = new PrintWriter(new File(outDir, "bounds.txt"), "UTF-8");
    //uk.me.parabola.imgfmt.app.Area searchBbox = new uk.me.parabola.imgfmt.app.Area (0,0,0,0);
    for (String bndFile : bndFileNames) {
        out.println(bndFile + "****************");
        BoundaryQuadTree bqt = BoundaryUtil.loadQuadTree(boundsdir, bndFile);
        if (bqt == null)
            break;
        Map<String, Tags> map = bqt.getTagsMap();
        for (Entry<String, Tags> entry : map.entrySet()) {
            TreeMap<String, String> btree = new TreeMap<String, String>();
            String line = bndFile + ":" + entry.getKey();
            Iterator<Entry<String, String>> tagIter = entry.getValue().entryIterator();
            while (tagIter.hasNext()) {
                Entry<String, String> tag = tagIter.next();
                btree.put(tag.getKey(), tag.getValue());
            }
            // print sorted tags
            for (Entry<String, String> e : btree.entrySet()) {
                out.println(line + ";" + e);
            }
        }
    }
    out.close();
}
Example 64
Project: MyFramework-master  File: JsonUtil.java View source code
/**
	 * 针对DWZ的下拉框返回的数据格式
	 * 例如:[["a","b"]]
	 * @param map
	 * @param isAdd 判断是否为添加界面
	 * @return
	 */
public static String toDWZComboxData(Map<String, String> map, String isSelect) {
    StringBuffer comBoxStr = new StringBuffer("");
    if (StringUtils.equalsIgnoreCase(isSelect, "true")) {
        comBoxStr.append("[[\"\",\"全部\"]");
    } else {
        comBoxStr.append("[[\"\",\"请选择\"]");
    }
    if (map != null && map.size() > 0) {
        @SuppressWarnings("rawtypes") Iterator item = map.entrySet().iterator();
        while (item.hasNext()) {
            @SuppressWarnings("unchecked") Entry<String, String> entry = (Entry<String, String>) item.next();
            comBoxStr.append(",");
            comBoxStr.append("[\"" + entry.getKey() + "\",\"" + entry.getValue() + "\"]");
        }
    }
    comBoxStr.append("]");
    return comBoxStr.toString();
}
Example 65
Project: guava-experimental-master  File: RegularImmutableBiMap_CustomFieldSerializer.java View source code
public static RegularImmutableBiMap<Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException {
    Map<Object, Object> entries = new LinkedHashMap<Object, Object>();
    Map_CustomFieldSerializerBase.deserialize(reader, entries);
    /*
     * For this custom field serializer to be invoked, the map must have been
     * RegularImmutableBiMap before it's serialized. Since RegularImmutableBiMap
     * always have one or more elements, ImmutableBiMap.copyOf always return a
     * RegularImmutableBiMap back.
     */
    return (RegularImmutableBiMap<Object, Object>) ImmutableBiMap.copyOf(entries);
}
Example 66
Project: AndroidBinding-master  File: ItemPositionsObservable.java View source code
public void putAll(Map<Integer, Boolean> values) {
    for (Entry<Integer, Boolean> set : values.entrySet()) {
        arr.put(set.getKey(), set.getValue());
    }
    notifyCollectionChanged(new CollectionChangedEventArg(Action.Add, values.keySet()));
}
Example 67
Project: cdo-master  File: LissomeStoreFactory.java View source code
public IStore createStore(String repositoryName, Map<String, String> repositoryProperties, Element storeConfig) {
    LissomeStore store = new LissomeStore();
    Map<String, String> storeProperties = RepositoryConfigurator.getProperties(storeConfig, 1);
    store.setProperties(storeProperties);
    return store;
}
Example 68
Project: alien4cloud-master  File: MockLocationConfigurerFactory.java View source code
public ILocationConfiguratorPlugin newInstance(String locationType) {
    if (MockOrchestratorFactory.OPENSTACK.equals(locationType)) {
        return applicationContext.getBean(MockOpenStackLocationConfigurer.class);
    }
    if (MockOrchestratorFactory.AWS.equals(locationType)) {
        return applicationContext.getBean(MockAmazonLocationConfigurer.class);
    }
    return new ILocationConfiguratorPlugin() {

        @Override
        public List<PluginArchive> pluginArchives() {
            return new ArrayList<>();
        }

        @Override
        public List<String> getResourcesTypes() {
            return new ArrayList<>();
        }

        @Override
        public Map<String, MatchingConfiguration> getMatchingConfigurations() {
            return new HashMap<>();
        }

        @Override
        public List<LocationResourceTemplate> instances(ILocationResourceAccessor resourceAccessor) {
            return null;
        }
    };
}
Example 69
Project: jtotus-master  File: DataFetcherTest.java View source code
@Test
public void testDataSource() {
    DataFetcher instance = new DataFetcher();
    instance.setSource("NasdaqOmxNordic");
    Map<String, Double> result = instance.fetchPeriodData("Metso Oyj", "2011-09-13", "2011-09-15", "close");
    for (Entry<String, Double> entry : result.entrySet()) {
        System.out.printf("%s - %f\n", entry.getKey(), entry.getValue());
    }
    assertEquals(result.get("2011-09-15"), Double.valueOf("25.230000"));
    assertEquals(result.get("2011-09-14"), Double.valueOf("23.880000"));
    assertEquals(result.get("2011-09-13"), Double.valueOf("23.370000"));
    result = instance.fetchPeriodData("Metso Oyj", "2011-09-13", "2011-09-15", "volume");
    for (Entry<String, Double> entry : result.entrySet()) {
        System.out.printf("Volume: %s - %f\n", entry.getKey(), entry.getValue());
    }
    assertEquals(result.get("2011-09-15"), Double.valueOf("1021909"));
    assertEquals(result.get("2011-09-14"), Double.valueOf("718663"));
    assertEquals(result.get("2011-09-13"), Double.valueOf("819216"));
    result = instance.fetchPeriodData("Metso Oyj", "2011-09-13", "2011-09-15", "trades");
    for (Entry<String, Double> entry : result.entrySet()) {
        System.out.printf("trades: %s - %f\n", entry.getKey(), entry.getValue());
    }
    assertEquals(result.get("2011-09-15"), Double.valueOf("5704"));
    assertEquals(result.get("2011-09-14"), Double.valueOf("4795"));
    assertEquals(result.get("2011-09-13"), Double.valueOf("4901"));
}
Example 70
Project: eis-master  File: AllPerceptPerceptHandler.java View source code
@Override
public final LinkedList<Percept> getAllPercepts() throws PerceiveException {
    LinkedList<Percept> percepts = new LinkedList<Percept>();
    Map<Method, Object> batchPerceptObjects;
    batchPerceptObjects = allPercepProvider.getAllPercepts();
    for (Entry<Method, Object> entry : batchPerceptObjects.entrySet()) {
        Method method = (Method) entry.getKey();
        Object perceptObject = entry.getValue();
        List<Object> perceptObjects = unpackPerceptObject(method, perceptObject);
        List<Percept> translatedPercepts = translatePercepts(method, perceptObjects);
        percepts.addAll(translatedPercepts);
    }
    return percepts;
}
Example 71
Project: schach-master  File: Fingerprint.java View source code
/*
     * Gibt einen eindeutigen Fingerprint des aktuellen Spielfeldes
     * (Schachfiguren auf Brett) zurueck, um eine Situation zu identifizieren
     * 
     * @param map HashMap<Integer,Byte> mit Situation von der Fingerprint
     * erstellt werden soll
     * 
     * @return String Fingerprint als String als Format
     * "pos1,figwert1--pos2,figwert2--..."
     */
@SuppressWarnings("unchecked")
public static String getFingerprint(HashMap<Integer, Byte> map) {
    HashMap<Integer, Byte> cloneMap = (HashMap<Integer, Byte>) map.clone();
    String fingerprint = "";
    Iterator<Entry<Integer, Byte>> it = cloneMap.entrySet().iterator();
    /*
         * Da die HashMap die Eintraege unterschiedlich ausliest, ist hier die Moeglichkeit,
         * FigureValue mit position zu verknuepfen um sie dann sortieren zu koennen.
         */
    class Identifier implements Comparable {

        byte figureValue;

        int position;

        public Identifier(byte figureValue, int position) {
            this.figureValue = figureValue;
            this.position = position;
        }

        public byte getFigureValue() {
            return this.figureValue;
        }

        public int getPosition() {
            return this.position;
        }

        public int compareTo(Object id) {
            int position;
            if (id instanceof Identifier) {
                position = ((Identifier) id).getPosition();
                return (position - this.position);
            } else {
                return 0;
            }
        }
    }
    List<Identifier> id = new LinkedList<Identifier>();
    while (it.hasNext()) {
        Map.Entry<Integer, Byte> pair = (Map.Entry<Integer, Byte>) it.next();
        byte figureValue = pair.getValue();
        int position = pair.getKey().intValue();
        id.add(new Identifier(figureValue, position));
        it.remove();
    }
    //fuer einen eindeutigen Fingerprint, muss Liste sortiert werden.
    Collections.sort(id);
    while (id.size() > 0) {
        fingerprint += id.get(0).getPosition() + "," + id.get(0).getFigureValue() + "--";
        id.remove(0);
    }
    fingerprint = fingerprint.substring(0, fingerprint.length() - 2);
    return fingerprint;
}
Example 72
Project: windowtester-master  File: SequentialActivityPart.java View source code
/**
 * @see ActivityPart#contributeEdgesToGraph(org.eclipse.graph.CompoundDirectedGraph, 
 * 											java.util.Map)
 */
public void contributeEdgesToGraph(CompoundDirectedGraph graph, Map map) {
    super.contributeEdgesToGraph(graph, map);
    Node node, prev = null;
    EditPart a;
    List members = getChildren();
    for (int n = 0; n < members.size(); n++) {
        a = (EditPart) members.get(n);
        node = (Node) map.get(a);
        if (prev != null) {
            Edge e = new Edge(prev, node);
            e.weight = 50;
            graph.edges.add(e);
        }
        prev = node;
    }
}
Example 73
Project: tmdm-studio-se-master  File: DescAnnotationCompositeTest.java View source code
/**
     * Test method for [email protected] [email protected]anguageString(java.util.Map)}.
     */
@Test
public void testEscapeMultiLanguageString() {
    Map<String, String> map = new HashMap<String, String>();
    map.put("en", "English view description");
    map.put("fr", "French view description");
    String ret = DescAnnotationComposite.escapeMultiLanguageString(map);
    assertTrue(ret.contains("EN"));
    assertTrue(ret.contains("FR"));
    map.clear();
    map.put("eN", "English view description");
    map.put("Fr", "French view description");
    ret = DescAnnotationComposite.escapeMultiLanguageString(map);
    assertTrue(ret.contains("EN"));
    assertTrue(ret.contains("FR"));
    map.clear();
    map.put("Ab", "English view description");
    map.put("zh", "French view description");
    ret = DescAnnotationComposite.escapeMultiLanguageString(map);
    assertTrue(ret.contains("AB"));
    assertTrue(ret.contains("ZH"));
}
Example 74
Project: levelup-java-examples-master  File: XMLToMapXstream.java View source code
@Test
public void deserialize_xml_to_hashmap() {
    String xmlAsMap = "<map>\n <entry>\n <int>1</int>\n <com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n <id>1</id>\n <name>Woodlawn super club</name>\n <address>Fort Atkinson</address>\n <outer-class>\n <restaurantByKey reference=\"../../../..\"/>\n </outer-class>\n </com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n </entry>\n <entry>\n <int>2</int>\n <com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n <id>2</id>\n <name>Sammy's</name>\n <address>Fort Atkinson</address>\n <outer-class reference=\"../../../entry/com.levelup.java.xml.XMLToMapXstream_-Restaurant/outer-class\"/>\n </com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n </entry>\n <entry>\n <int>3</int>\n <com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n <id>3</id>\n <name>ColdSpring Inn</name>\n <address>Cold Spring</address>\n <outer-class reference=\"../../../entry/com.levelup.java.xml.XMLToMapXstream_-Restaurant/outer-class\"/>\n </com.levelup.java.xml.XMLToMapXstream_-Restaurant>\n </entry>\n</map>\n";
    XStream xStream = new XStream();
    xStream.alias("map", java.util.Map.class);
    @SuppressWarnings("unchecked") Map<Integer, Restaurant> resturantConverted = (Map<Integer, Restaurant>) xStream.fromXML(xmlAsMap);
    assertThat(resturantConverted, hasKey(new Integer("1")));
}
Example 75
Project: schemacrawler-master  File: SchemaCrawlerSqlTypesGenerator.java View source code
private static Map<Integer, String> getJavaSqlTypes() {
    final Map<Integer, String> javaSqlTypes = new HashMap<Integer, String>();
    final Field[] staticFields = Types.class.getFields();
    for (final Field field : staticFields) {
        try {
            final String fieldName = field.getName();
            final Integer fieldValue = (Integer) field.get(null);
            javaSqlTypes.put(fieldValue, fieldName);
        } catch (final SecurityException e) {
            continue;
        } catch (final IllegalAccessException e) {
            continue;
        }
    }
    return Collections.unmodifiableMap(javaSqlTypes);
}
Example 76
Project: raml-tester-master  File: RestAssuredRamlMessage.java View source code
protected Values mapToValues(Map<String, ?> map) {
    final Values values = new Values();
    for (final Entry<String, ?> param : map.entrySet()) {
        if (param.getValue() instanceof Collection) {
            values.addValues(param.getKey(), (Collection<?>) param.getValue());
        } else {
            values.addValue(param.getKey(), param.getValue());
        }
    }
    return values;
}
Example 77
Project: corespring-master  File: StubAccountManager.java View source code
public void updateBeneficiaryAllocationPercentages(Long accountId, Map<String, Percentage> allocationPercentages) {
    Account account = accountsById.get(accountId);
    for (Entry<String, Percentage> entry : allocationPercentages.entrySet()) {
        account.getBeneficiary(entry.getKey()).setAllocationPercentage(entry.getValue());
    }
}
Example 78
Project: skalli-master  File: IgnoreUnknownElementsXStream.java View source code
public static XStream getXStreamInstance(Set<? extends Converter> converters, Set<ClassLoader> entityClassLoaders, Map<String, Class<?>> aliases) {
    XStream xstream = new IgnoreUnknownElementsXStream();
    if (converters != null) {
        for (Converter converter : converters) {
            xstream.registerConverter(converter);
        }
    }
    if (entityClassLoaders != null) {
        xstream.setClassLoader(new CompositeEntityClassLoader(entityClassLoaders));
    }
    if (aliases != null) {
        for (Entry<String, Class<?>> entry : aliases.entrySet()) {
            xstream.alias(entry.getKey(), entry.getValue());
        }
    }
    return xstream;
}
Example 79
Project: eclipse-integration-commons-master  File: SimpleDownloadService.java View source code
[email protected]
public void fetch(URL url, OutputStream writeTo) throws IOException {
    URLConnection conn = null;
    InputStream input = null;
    try {
        conn = connectionFactory.createConnection(url);
        conn.connect();
        if (DEBUG) {
            System.out.println(">>> " + url);
            Map<String, List<String>> headers = conn.getHeaderFields();
            for (Entry<String, List<String>> header : headers.entrySet()) {
                System.out.println(header.getKey() + ":");
                for (String value : header.getValue()) {
                    System.out.println("   " + value);
                }
            }
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        }
        input = conn.getInputStream();
        IOUtil.pipe(input, writeTo);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (Throwable e) {
            }
        }
    }
}
Example 80
Project: tapestry-facebook-master  File: FBSubscribeWorker.java View source code
@Override
public void subscribe(final Map<String, Subscribe> events, final PlasticMethod method) {
    method.addAdvice(new MethodAdvice() {

        public void advise(MethodInvocation invocation) {
            ComponentResources resources = invocation.getInstanceContext().get(ComponentResources.class);
            FacebookEnvironment facebookEnvironment = environment.peekRequired(FacebookEnvironment.class);
            for (Entry<String, Subscribe> entry : events.entrySet()) {
                String name = entry.getKey();
                Subscribe subscribe = entry.getValue();
                String url = resources.createEventLink(name).toURI();
                facebookEnvironment.addInitializerCall(script(name, url, subscribe));
            //javaScriptSupport.addScript(script(name, url, subscribe));
            }
            invocation.proceed();
        }
    });
}
Example 81
Project: platform_tools_motodev-master  File: ZoomInOutHandler.java View source code
/*
     * (non-Javadoc)
     * @see com.motorola.studio.android.emulator.ui.handlers.AbstractZoomHandler#getZoomFactor(java.util.Map)
     */
@SuppressWarnings("rawtypes")
@Override
protected double getZoomFactor(Map parameters) {
    double zoomFactor = DEFAULT_ZOOM;
    IAndroidEmulatorInstance instance = AbstractAndroidView.getActiveInstance();
    String viewId = (String) parameters.get(ACTIVE_VIEW_PARAMETER);
    String changeFactorString = (String) parameters.get(ZOOM_CHANGE_FACTOR_PARAMETER);
    if ((instance != null) && (viewId != null) && (changeFactorString != null)) {
        IViewPart viewPart = EclipseUtils.getActiveView(viewId);
        if (viewPart instanceof AbstractAndroidView) {
            AbstractAndroidView view = (AbstractAndroidView) viewPart;
            double currentZoomFactor = view.getZoomFactor(instance);
            try {
                double changeZoomFactor = Double.parseDouble(changeFactorString);
                zoomFactor = currentZoomFactor + changeZoomFactor;
            } catch (Exception e) {
                zoomFactor = currentZoomFactor;
            }
        }
    }
    if (zoomFactor < MINIMUM_ZOOM) {
        zoomFactor = MINIMUM_ZOOM;
    } else if (zoomFactor > MAXIMUM_ZOOM) {
        zoomFactor = MAXIMUM_ZOOM;
    }
    return zoomFactor;
}
Example 82
Project: dbfound-master  File: LogUtil.java View source code
public static void log(String sql, Map<String, Param> params) {
    if (openLog) {
        log.info("execute sql: " + sql);
        Set<Entry<String, Param>> setp = params.entrySet();
        for (Entry<String, Param> entry : setp) {
            Param param = entry.getValue();
            log.info(String.format("sql param:%s, value:%s, dataType:%s, sourcePath:%s", param.getName(), param.getValue(), param.getDataType(), param.getSourcePathHistory()));
        }
    }
}
Example 83
Project: seasar2-master  File: OgnlExpression.java View source code
public Map evaluate(final Object source) {
    final Map map = (Map) OgnlUtil.getValue(parsedExpression, source);
    final Map result = new LinkedHashMap(map.size());
    for (final Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
        final Entry entry = (Entry) it.next();
        final Object key = entry.getKey();
        final Object value = entry.getValue();
        if (key instanceof Character) {
            result.put(new String(new char[] { ((Character) key).charValue() }), value);
        } else {
            result.put(key, value);
        }
    }
    return result;
}
Example 84
Project: sisu-guice-master  File: MoreTypesTest.java View source code
public void testParameterizedTypeToString() {
    TypeLiteral<Inner<String>> innerString = new TypeLiteral<Inner<String>>() {
    };
    assertEquals("com.google.inject.internal.MoreTypesTest$Inner<java.lang.String>", MoreTypes.typeToString(innerString.getType()));
    TypeLiteral<Set<Inner<Integer>>> mapInnerInteger = new TypeLiteral<Set<Inner<Integer>>>() {
    };
    assertEquals("java.util.Set<com.google.inject.internal.MoreTypesTest$Inner<java.lang.Integer>>", MoreTypes.typeToString(mapInnerInteger.getType()));
    TypeLiteral<Map<Inner<Long>, Set<Inner<Long>>>> mapInnerLongToSetInnerLong = new TypeLiteral<Map<Inner<Long>, Set<Inner<Long>>>>() {
    };
    assertEquals("java.util.Map<com.google.inject.internal.MoreTypesTest$Inner<java.lang.Long>, " + "java.util.Set<com.google.inject.internal.MoreTypesTest$Inner<java.lang.Long>>>", MoreTypes.typeToString(mapInnerLongToSetInnerLong.getType()));
}
Example 85
Project: pmd-eclipse-plugin-master  File: ImageColumnDescriptor.java View source code
/**
     * @see net.sourceforge.pmd.eclipse.ui.preferences.br.IRuleColumnDescriptor#newTreeColumnFor(org.eclipse.swt.widgets.Tree, int, net.sourceforge.pmd.eclipse.ui.preferences.br.SortListener, java.util.Map)
     */
public TreeColumn newTreeColumnFor(Tree parent, int columnIndex, final SortListener sortListener, Map<Integer, List<Listener>> paintListeners) {
    TreeColumn tc = buildTreeColumn(parent, sortListener);
    setLabelIfImageMissing(tc);
    if (painterBuilder != null)
        painterBuilder.addPainterFor(tc.getParent(), columnIndex, accessor(), paintListeners);
    return tc;
}
Example 86
Project: turmeric-eclipse-master  File: TestMapUtil.java View source code
/**
	 * Test method for [email protected] [email protected]rray(java.util.Map, boolean)}.
	 */
@Test
public void testToArrayMapOfKVBoolean() {
    Map<String, String> data = new LinkedHashMap<String, String>();
    data.put("flickr", "http://www.flickr.com");
    data.put("twitter", "http://twitter.com");
    data.put("bbc", "http://www.bbc.co.uk");
    Object[] array = MapUtil.toArray(data, false);
    System.out.println(Arrays.asList(array));
    Assert.assertEquals("Data is not expected", "flickr", array[0]);
    Assert.assertEquals("Data is not expected", "http://www.bbc.co.uk", array[array.length - 1]);
    data.put(null, "data");
    array = MapUtil.toArray(data, true);
    System.out.println(Arrays.asList(array));
    Assert.assertEquals("Data is not expected", "flickr", array[0]);
    Assert.assertEquals("Data is not expected", "data", array[array.length - 1]);
}
Example 87
Project: tcf-master  File: TerminalsMementoHandler.java View source code
/* (non-Javadoc)
	 * @see org.eclipse.tcf.te.ui.terminals.interfaces.IMementoHandler#saveState(org.eclipse.ui.IMemento, java.util.Map)
	 */
@Override
public void saveState(IMemento memento, Map<String, Object> properties) {
    Assert.isNotNull(memento);
    Assert.isNotNull(properties);
    // Do not write the terminal title to the memento -> needs to
    // be recreated at the time of restoration.
    memento.putString(ITerminalsConnectorConstants.PROP_ENCODING, (String) properties.get(ITerminalsConnectorConstants.PROP_ENCODING));
    // Get the selection from the properties
    ISelection selection = (ISelection) properties.get(ITerminalsConnectorConstants.PROP_SELECTION);
    if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
        Object element = ((IStructuredSelection) selection).getFirstElement();
        if (element instanceof IPeerNode) {
            IPeerNode peerNode = (IPeerNode) element;
            //$NON-NLS-1$
            memento.putString(//$NON-NLS-1$
            "peerID", //$NON-NLS-1$
            peerNode.getPeerId());
        }
    }
}
Example 88
Project: openmap-master  File: MapRule.java View source code
/**
     * Returns a String of concatenated record values.
     * 
     * @param fieldNames column names
     * @param record Map to use to fetch values
     * @return String of content
     */
public String getContent(List<String> fieldNames, Map record) {
    StringBuffer buf = new StringBuffer();
    if (fieldNames != null) {
        for (String field : fieldNames) {
            buf.append(PropUtils.unnull(record.get(field))).append(" ");
        }
    }
    // Might be more than just that last ""
    return buf.toString().trim();
}
Example 89
Project: Strata-master  File: MapTokenEvaluator.java View source code
@Override
public EvaluationResult evaluate(Map<?, ?> map, CalculationFunctions functions, String firstToken, List<String> remainingTokens) {
    return MapStream.of(map).filterKeys( key -> firstToken.equalsIgnoreCase(key.toString())).findFirst().map( e -> EvaluationResult.success(e.getValue(), remainingTokens)).orElse(invalidTokenFailure(map, firstToken));
}
Example 90
Project: molgenis-master  File: JsMagmaScriptExecutor.java View source code
/**
	 * Execute a JavaScript using the Magma API
	 *
	 * @param jsScript
	 * @param parameters
	 * @return
	 */
Object executeScript(String jsScript, Map<String, Object> parameters) {
    EntityType entityType = entityTypeFactory.create().setSimpleName("entity");
    parameters.keySet().forEach( key -> entityType.addAttribute(attributeFactory.create().setName(key)));
    Entity entity = new DynamicEntity(entityType);
    parameters.entrySet().forEach( parameter -> entity.set(parameter.getKey(), parameter.getValue()));
    return jsMagmaScriptEvaluator.eval(jsScript, entity);
}
Example 91
Project: wpcleaner-master  File: ApiXmlPurgeResult.java View source code
/**
   * Execute purge request.
   * 
   * @param properties Properties defining request.
   * @throws APIException
   */
@Override
public void executePurge(Map<String, String> properties) throws APIException {
    try {
        checkForError(getRoot(properties, ApiRequest.MAX_ATTEMPTS));
    } catch (JDOMParseException e) {
        log.error("Error purging page cache", e);
        throw new APIException("Error parsing XML", e);
    }
}
Example 92
Project: LambdaDojo-master  File: S406StreamInsteadOfFor.java View source code
private void wordCount() {
    List<String> sentences = Arrays.asList("Peter Piper picked", "a peck of pickled peppers.", "A peck of pickled peppers", "Peter Piper picked. ", "If Peter Piper picked", "a peck of pickled peppers,", "Where's the peck of pickled peppers", "Peter Piper picked? ");
    Map<String, Integer> result = new HashMap<>();
    for (String sentence : sentences) {
        String[] splitedSentence = sentence.split("[\\.,\\? ]");
        for (String word : splitedSentence) {
            String lowerWord = word.toLowerCase();
            int count = result.getOrDefault(lowerWord, 0);
            result.put(lowerWord, count + 1);
        }
    }
    System.out.println(result);
}
Example 93
Project: dataverse-master  File: LazyFileMetadataDataModel.java View source code
@Override
public List<FileMetadata> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
    //fileServiceBean.findFileMetadataByDatasetVersionIdLazy(datasetVersionId, pageSize, sortField, sortField, first);
    List<FileMetadata> listFileMetadata = null;
    //this.setRowCount(fileServiceBean.findCountByDatasetVersionId(datasetVersionId).intValue());
    return listFileMetadata;
}
Example 94
Project: erlide-master  File: MapUtils.java View source code
public static <K, V> Map<V, List<K>> inverseList(final Map<K, List<V>> map) {
    final Map<V, List<K>> result = new LinkedHashMap<>();
    for (final Map.Entry<K, List<V>> entry : map.entrySet()) {
        for (final V v : entry.getValue()) {
            if (!result.containsKey(v)) {
                result.put(v, new ArrayList<K>());
            }
            result.get(v).add(entry.getKey());
        }
    }
    return result;
}
Example 95
Project: dtangler-master  File: ArgumentBuilder.java View source code
public Arguments build(String[] cmdLineArgs) {
    Map<String, String> values = new CommandLineParser(ParserConstants.VALID_KEYS).parseValues(cmdLineArgs);
    ArgumentParser parser = new ArgumentParser();
    // if config file was given, read it first
    if (values.containsKey(ParserConstants.CONFIG_FILE_KEY)) {
        File configFile = new File(values.get(ParserConstants.CONFIG_FILE_KEY));
        Map<String, String> configFileValues = new ConfigFileParser(configFile, ParserConstants.VALID_KEYS).parseValues();
        parser.parseArguments(configFileValues);
    }
    return parser.parseArguments(values);
}
Example 96
Project: hci-2011-2-master  File: Util.java View source code
public static List<? extends Map<String, ?>> getMapped(List<?> objects, String[] desired_fields) {
    ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
    for (Object object : objects) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Class<? extends Object> c = object.getClass();
        for (Field field : c.getFields()) {
            Annotation[] ann = (Annotation[]) field.getAnnotations();
            for (Annotation annotation : ann) {
                if (annotation instanceof Element || annotation instanceof Attribute) {
                    try {
                        boolean is_in = false;
                        for (String desired_field : desired_fields) {
                            if (desired_field.equals(field.getName())) {
                                is_in = true;
                                break;
                            }
                        }
                        if (is_in) {
                            map.put(field.getName(), field.get(object));
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        list.add(map);
    }
    return list;
}
Example 97
Project: mind-compiler-master  File: OutputBinaryADLLocator.java View source code
public URL findBinaryADL(final String name, final Map<Object, Object> context) {
    URL binADL = null;
    try {
        final File binADLOutputFile = outputFileLocatorItf.getMetadataOutputFile(BasicADLLocator.getADLBinaryName(name), context);
        if (binADLOutputFile.exists()) {
            binADL = binADLOutputFile.toURI().toURL();
        }
    } catch (final IOException e) {
    }
    if (binADL == null) {
        binADL = clientLocatorItf.findBinaryADL(name, context);
    }
    return binADL;
}
Example 98
Project: geoserver-enterprise-master  File: GetCapabilitiesKvpRequestReader.java View source code
@Override
@SuppressWarnings("unchecked")
public Object read(Object request, Map kvp, Map rawKvp) throws Exception {
    // make sure we get the right accepts versions param -> workaround for GEOS-1719
    if (rawKvp.containsKey("acceptVersions")) {
        OWS11AcceptVersionsKvpParser avp = new OWS11AcceptVersionsKvpParser();
        AcceptVersionsType avt = (AcceptVersionsType) avp.parse((String) rawKvp.get("acceptVersions"));
        kvp.put("acceptVersions", avt);
    }
    request = super.read(request, kvp, rawKvp);
    return request;
}
Example 99
Project: ISAcreator-master  File: AnnotatorSearchClientTest.java View source code
@Test
public void testAnnotatorClient() {
    System.out.println("_____Testing NCBO Annotator search client____");
    AnnotatorSearchClient sc = new AnnotatorSearchClient();
    Set<String> testTerms = new HashSet<String>();
    testTerms.add("CY3");
    testTerms.add("DOSE");
    testTerms.add("ASSAY");
    testTerms.add("Ethanol");
    testTerms.add("drug vehicle (90% ethanol/10% tween-20)");
    Map<String, Map<String, AnnotatorResult>> result = sc.searchForTerms(testTerms);
    for (String key : result.keySet()) {
        System.out.println(key + " matched:");
        for (String ontologyId : result.get(key).keySet()) {
            System.out.println("\t" + ontologyId + " -> " + result.get(key).get(ontologyId).getOntologyTerm().getOntologyTermName() + " (" + result.get(key).get(ontologyId).getOntologySource().getOntologyDisplayLabel() + ")");
        }
    }
    assertTrue("No matches found", result.size() > 0);
}
Example 100
Project: geotoolkit-master  File: FishDataStoreDemo.java View source code
public static void main(String[] args) throws DataStoreException, URISyntaxException {
    Demos.init();
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("path", FishDataStoreDemo.class.getResource("/data/fishes.fsh").toURI());
    FeatureStore store = (FeatureStore) DataStores.open(params);
    for (GenericName name : store.getNames()) {
        System.out.println(store.getFeatureType(name.toString()));
        System.out.println("\n---------------------------\n");
        System.out.println(store.createSession(true).getFeatureCollection(QueryBuilder.all(name)));
    }
}
Example 101
Project: avaje-ebeanorm-master  File: RawJdbcHstoreTest.java View source code
@Test
public void test() throws SQLException {
    Transaction txn = Ebean.beginTransaction();
    try {
        Connection connection = txn.getConnection();
        String insert = "update p_customer set tags = ? where id = 1";
        PreparedStatement pstmt1 = connection.prepareStatement(insert);
        Map<String, String> map = new HashMap<>();
        map.put("one", "123123");
        map.put("two", "hello");
        pstmt1.setObject(1, map);
        int rows = pstmt1.executeUpdate();
        System.out.println("updated rows " + rows);
        String sql = "select id, name, tags from p_customer";
        PreparedStatement pstmt = connection.prepareStatement(sql);
        ResultSet rset = pstmt.executeQuery();
        while (rset.next()) {
            Long id = rset.getLong(1);
            String name = rset.getString(2);
            Object tags = rset.getObject(3);
            System.out.println("rows:" + id + " " + name + " " + tags);
        }
    } finally {
        txn.end();
    }
}