Java Examples for java.util.HashMap

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

Example 1
Project: ijoomer-adv-sdk-master  File: SobiproSearchResultActivity.java View source code
/**
	 * This method is used to get intent data
	 */
@SuppressWarnings("unchecked")
public void getIntentData() {
    try {
        IN_POS = getIntent().getIntExtra("IN_POS", 0);
        optionCriteria = getIntent().getStringExtra("IN_OPTIONCRITERIA");
        searchKey = getIntent().getStringExtra("IN_SEARCH_KEY");
        section_id = getIntent().getStringExtra("IN_SECTION_ID");
        searchField = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("IN_SEARCHFIELD");
        IN_FEATUREDFIRST = getIntent().getStringExtra("IN_FEATUREDFIRST");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 2
Project: android_platform_libcore-master  File: HashMapTest.java View source code
/**
     * java.util.HashMap#HashMap(int, float)
     */
public void test_ConstructorIF() {
    // Test for method java.util.HashMap(int, float)
    HashMap hm2 = new HashMap(5, (float) 0.5);
    assertEquals("Created incorrect HashMap", 0, hm2.size());
    try {
        new HashMap(0, 0);
        fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
    }
    HashMap empty = new HashMap(0, 0.75f);
    assertNull("Empty hashtable access", empty.get("nothing"));
    empty.put("something", "here");
    assertTrue("cannot get element", empty.get("something") == "here");
}
Example 3
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 4
Project: open-mika-master  File: AbstractMapTest.java View source code
/**
     * @tests java.util.AbstractMap#keySet()
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
        method = "keySet",
        args = {}
    )
     */
public void test_keySet() {
    AbstractMap map1 = new HashMap(0);
    assertSame("HashMap(0)", map1.keySet(), map1.keySet());
    AbstractMap map2 = new HashMap(10);
    assertSame("HashMap(10)", map2.keySet(), map2.keySet());
    Map map3 = Collections.EMPTY_MAP;
    assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
    AbstractMap map4 = new IdentityHashMap(1);
    assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
    AbstractMap map5 = new LinkedHashMap(122);
    assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
    AbstractMap map6 = new TreeMap();
    assertSame("TreeMap", map6.keySet(), map6.keySet());
    AbstractMap map7 = new WeakHashMap();
    assertSame("WeakHashMap", map7.keySet(), map7.keySet());
}
Example 5
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 6
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 7
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 8
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 9
Project: extension-aws-master  File: ReplacerTest.java View source code
public void testReplacer() throws Exception {
    SearcherManager manager = (SearcherManager) getBean("searcherManager");
    Replacer replacer = new Replacer();
    replacer.setCatalogId("system");
    replacer.setAlwaysReplace(true);
    replacer.setSearcherManager(manager);
    String code = "${one}/${longvariable}/${user.email}/${notfound}/${two}/${user.id}${nogap1}${nogap2}";
    Map vars = new HashMap();
    vars.put("user", "admin");
    vars.put("one", "Uno");
    vars.put("nogap1", "123");
    vars.put("nogap2", "456");
    vars.put("two", "TOOOOLONG");
    vars.put("longvariable", "short");
    String returned = replacer.replace(code, vars);
    assertEquals("[email protected]//TOOOOLONG/admin123456", returned);
}
Example 10
Project: polly-master  File: PHCNPasteService.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("language", "");
    //$NON-NLS-1$ //$NON-NLS-2$
    properties.put("blppassword", "");
    //$NON-NLS-1$
    properties.put("input", message);
    //$NON-NLS-1$
    PostResult pr = this.postRequest(new URL("http://paste.phcn.ws/#"), properties);
    Matcher m = PATTERN.matcher(pr.getResultString());
    if (!m.find()) {
        //$NON-NLS-1$
        throw new IOException("invalid result");
    }
    return pr.getResultString().substring(m.start(), m.end());
}
Example 11
Project: sitebricks-master  File: ShowIfWidgetTest.java View source code
@Test(dataProvider = EXPRESSIONS_AND_EVALS)
public final void hideChildren(String expression, boolean should) {
    final boolean[] run = new boolean[1];
    WidgetChain mockChain = new ProceedingWidgetChain() {

        @Override
        public void render(Object bound, Respond respond) {
            run[0] = true;
        }
    };
    //try to render widget
    new ShowIfWidget(mockChain, expression, new MvelEvaluator()).render(new HashMap<String, Object>() {

        {
            put("visible", true);
        }
    }, RespondersForTesting.newRespond());
    assert run[0] == should : "ShowIf did not do as it should " + should;
}
Example 12
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 13
Project: dk-master  File: IColorReportServiceImplTest.java View source code
@Test
public void testColorInvestReport() {
    Map parameterMap = new HashMap();
    parameterMap.put("investStartDate", "2014-01-01");
    parameterMap.put("investEndDate", "2014-10-13");
    PageDo page = new PageDo();
    page = colorReportService.queryColorInvest(parameterMap, page);
    List<Map<String, Object>> l = page.getPage();
    for (Map<String, Object> map : l) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("key:" + entry.getKey() + " / " + entry.getValue());
        }
    }
}
Example 14
Project: NucleusFramework-master  File: AgentMapTest.java View source code
@Test
public void testMap() {
    AgentMap<String, ISubscriberAgent> map = new AgentMap<String, ISubscriberAgent>() {

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

        @Override
        protected Map<String, ISubscriberAgent> map() {
            return internalMap;
        }
    };
    DisposableAgent agent1 = new DisposableAgent() {
    };
    DisposableAgent agent2 = new DisposableAgent() {
    };
    DisposableAgent agent3 = new DisposableAgent() {
    };
    new MapRunnable<>(map, "a", "b", "c", agent1, agent2, agent3).run();
    map.clear();
    map.put("test", agent1);
    assertEquals(1, map.size());
    agent1.dispose();
    assertEquals(0, map.size());
}
Example 15
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 16
Project: SideScrollerGDW2012-Max-master  File: WebstartMuffin.java View source code
/**
	 * @see org.newdawn.slick.muffin.Muffin#saveFile(java.util.HashMap, java.lang.String)
	 */
public void saveFile(HashMap scoreMap, String fileName) throws IOException {
    PersistenceService ps;
    BasicService bs;
    URL configURL;
    try {
        ps = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
        bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
        URL baseURL = bs.getCodeBase();
        // System.out.println("CodeBase was " + baseURL);
        configURL = new URL(baseURL, fileName);
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to save state: ");
    }
    try {
        ps.delete(configURL);
    } catch (Exception e) {
        Log.info("No exisiting Muffin Found - First Save");
    }
    try {
        // 1024 bytes for our data
        ps.create(configURL, 1024);
        FileContents fc = ps.get(configURL);
        DataOutputStream oos = new DataOutputStream(fc.getOutputStream(false));
        // scroll through hashMap and write key and value to file
        // get the keys
        Set keys = scoreMap.keySet();
        // get values using keys
        for (Iterator i = keys.iterator(); i.hasNext(); ) {
            String key = (String) i.next();
            oos.writeUTF(key);
            if (fileName.endsWith("Number")) {
                double value = ((Double) scoreMap.get(key)).doubleValue();
                oos.writeDouble(value);
            } else {
                String value = (String) scoreMap.get(key);
                oos.writeUTF(value);
            }
        }
        oos.flush();
        oos.close();
    } catch (Exception e) {
        Log.error(e);
        throw new IOException("Failed to store map of state data");
    }
}
Example 17
Project: sosies-generator-master  File: JsonFailuresOutput.java View source code
@Override
public void write(JSONObject object) {
    super.write(object);
    failuresDict = new HashMap<>();
    int id = 0;
    for (Transformation t : getTransformations()) {
        if (t.getFailures() != null && t.getFailures().size() > 0) {
            for (String s : t.getFailures()) if (!failuresDict.containsKey(s) && s != null) {
                failuresDict.put(s, id++);
            }
        }
    }
    try {
        object.put(FAILURES_DICTIONARY, failuresDict);
    } catch (JSONException e) {
        throw new PersistenceException(e);
    }
}
Example 18
Project: sysart-itext-master  File: BookmarksTest.java View source code
@Test
public void testNoBreakSpace() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, baos);
    document.open();
    writer.setPageEvent(new PdfPageEventHelper() {

        public void onParagraph(PdfWriter writer, Document document, float position) {
            PdfContentByte cb = writer.getDirectContent();
            PdfDestination destination = new PdfDestination(PdfDestination.FITH, position);
            new PdfOutline(cb.getRootOutline(), destination, TITLE);
        }
    });
    document.add(new Paragraph("Hello World"));
    document.close();
    // read bookmark back
    PdfReader r = new PdfReader(baos.toByteArray());
    List bookmarks = SimpleBookmark.getBookmark(r);
    assertEquals("bookmark size", 1, bookmarks.size());
    HashMap<String, Object> b = (HashMap<String, Object>) bookmarks.get(0);
    String title = (String) b.get("Title");
    assertEquals("bookmark title", TITLE, title);
}
Example 19
Project: Mint-Programming-Language-master  File: ViewStrings.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    short i = 0;
    while (i < Short.MAX_VALUE) {
        try {
            HashMap<Integer, String> strs = Heap.strings;
            if (strs == null) {
                return EMPTY_LIST;
            }
            Table tbl = new Table();
            ArrayList<Integer> keys = new ArrayList<Integer>();
            Set<Integer> s = strs.keySet();
            for (int element : s) {
                keys.add(element);
            }
            s = null;
            for (int key : keys) {
                SmartList<Pointer> pair = new SmartList<Pointer>();
                pair.add(new Pointer(Constants.INT_TYPE, key));
                pair.add(Heap.allocateString(strs.get(key)));
                tbl.addBinding(pair);
            }
            return Heap.allocateTable(tbl);
        } catch (Throwable t) {
        }
        ++i;
    }
    try {
        return Heap.allocateString(Heap.strings.toString());
    } catch (Throwable t) {
        return ChangeString.ERROR;
    }
}
Example 20
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 21
Project: bigtable-sql-master  File: EntryPanelManager.java View source code
public void init(ISyntaxHighlightTokenMatcherFactory syntaxHighlightTokenMatcherFactory, ToolsPopupAccessor tpa) {
    HashMap props = new HashMap();
    props.put(IParserEventsProcessorFactory.class.getName(), null);
    if (null != syntaxHighlightTokenMatcherFactory) {
        props.put(ISyntaxHighlightTokenMatcherFactory.class.getName(), syntaxHighlightTokenMatcherFactory);
    }
    if (null != tpa) {
        props.put(ToolsPopupAccessor.class.getName(), tpa);
    }
    _entry = _session.getApplication().getSQLEntryPanelFactory().createSQLEntryPanel(_session, props);
    _component = _entry.getTextComponent();
    if (false == _entry.getDoesTextComponentHaveScroller()) {
        _component = new JScrollPane(_entry.getTextComponent());
        _component.setBorder(BorderFactory.createEmptyBorder());
    }
    new UndoHandlerImpl(_session.getApplication(), _entry);
}
Example 22
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 23
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 24
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 25
Project: ecologylabFundamental-master  File: ConfParser.java View source code
public HashMap<String, String> parse() throws FileNotFoundException {
    confMap = new HashMap<String, String>();
    if (!confFile.exists() || !confFile.canRead()) {
        System.err.println("Failed to parse conf file: " + confFile);
        throw new FileNotFoundException();
    }
    //go line by line and add to the hash map if it's not a comment;
    Scanner scanner = new Scanner(confFile);
    scanner.useDelimiter("=|\\n");
    while (scanner.hasNextLine()) {
        //ignore comments
        if (scanner.findInLine("#") != null) {
            scanner.nextLine();
            continue;
        }
        try {
            String key = scanner.next().trim();
            String value = scanner.next().trim();
            System.out.println(key + ": " + value);
            confMap.put(key, value);
        } catch (NoSuchElementException e) {
            break;
        }
    }
    return confMap;
}
Example 26
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 27
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 28
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();
    }
}
Example 29
Project: org.eclipse.ecr-master  File: TestParseProperties.java View source code
public void test() throws Exception {
    Map<String, String> props = new HashMap<String, String>();
    assertEquals(props, parse(""));
    String expr = "key1=val1";
    props.put("key1", "val1");
    assertEquals(props, parse(expr));
    expr += ";";
    assertEquals(props, parse(expr));
    expr += "key2=val2";
    props.put("key2", "val2");
    assertEquals(props, parse(expr));
    expr += ";";
    assertEquals(props, parse(expr));
    expr += "key3=a=b;;c===d;;;;e=f";
    props.put("key3", "a=b;c===d;;e=f");
    assertEquals(props, parse(expr));
}
Example 30
Project: geotools-old-master  File: QuickstartNotes.java View source code
public void snipetDataStoreFinder() throws Exception {
    // start datastore
    File file = JFileDataStoreChooser.showOpenFile("shp", null);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("url", file.toURI().toURL());
    params.put("create spatial index", false);
    params.put("memory mapped buffer", false);
    params.put("charset", "ISO-8859-1");
    DataStore store = DataStoreFinder.getDataStore(params);
    SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
// end datastore
}
Example 31
Project: checkstyle-master  File: InputLocalVariableNameOneCharVarName.java View source code
public void fooMethod() {
    for (int i = 1; i < 10; i++) {
    //ok
    //some code
    }
    //warn
    int i = 0;
    for (int index = 1; index < 10; index++) {
    //ok
    //some code
    }
    for (int I_ndex = 1; I_ndex < 10; I_ndex++) {
    //warn
    //some code
    }
    int index = 1;
    for (; index < 10; index++) {
    //ok  
    //some code
    }
    for (; i < 12; i++) {
    //ok
    //some code
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Map.Entry<String, String> e : map.entrySet()) {
    //ok
    //some code
    }
    for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
    //ok
    // something
    }
    for (int i_ndex = 1; i_ndex < 10; i_ndex++) {
    //warn
    //some code
    }
    for (int ii_i1 = 1; ii_i1 < 10; ii_i1++) {
    //warn
    //some code
    }
    for (int $index = 1; $index < 10; $index++) {
    //warn
    //some code
    }
    for (int in$dex = 1; in$dex < 10; in$dex++) {
    //warn
    //some code
    }
    for (int index$ = 1; index$ < 10; index$++) {
    //warn
    //some code
    }
}
Example 32
Project: sphereMiners-master  File: Pacifist.java View source code
@Override
protected void playTurn() {
    // first check if we could split
    List<Sphere> splits = new ArrayList<>();
    for (Sphere s : ownSpheres) {
        if (s.getSize() > getConstants().getMinSplittingsize()) {
            splits.add(s);
        }
    }
    split(splits);
    // then change directions
    Sphere ownSphere = null;
    Iterator<Sphere> ownIt = ownSpheres.iterator();
    Map<Sphere, Position> newDirections = new HashMap<>();
    while (ownIt.hasNext()) {
        ownSphere = ownIt.next();
        Iterator<Sphere> dotsIt = dots.iterator();
        Sphere nextDot = dotsIt.next();
        double minDist = ownSphere.getPosition().dist(nextDot.getPosition());
        while (dotsIt.hasNext()) {
            Sphere tmpSphere = dotsIt.next();
            double tmpDist = ownSphere.getPosition().dist(tmpSphere.getPosition());
            if (tmpDist < minDist) {
                minDist = tmpDist;
                nextDot = tmpSphere;
            }
        }
        final Position moveTo = nextDot.getPosition().sub(ownSphere.getPosition());
        newDirections.put(ownSphere, moveTo);
    }
    changeMoveDirection(newDirections);
}
Example 33
Project: de.htwg.se.muehle-master  File: GamefieldDisplayTest.java View source code
@Test
public void test() {
    Controller controller = new Controller(new GamefieldAdapter(new GamefieldGraph()));
    controller.setStone(2);
    String log;
    Map<Integer, Character> map = new HashMap<>();
    for (int i = 1; i <= 24; i++) {
        map.put(i, controller.getVertexColor(i));
    }
    log = "%1-----------%2-----------%3\t\t" + "1-----------2-----------3\n" + "|           |           |\t\t" + "|           |           |\n" + "|   %4-------%5-------%6   |\t\t" + "|   4-------5-------6   |\n" + "|   |       |       |   |\t\t" + "|   |       |       |   |\n" + "|   |   %7---%8---%9   |   |\t\t" + "|   |   7---8---9   |   |\n" + "|   |   |       |   |   |\t\t" + "|   |   |       |   |   |\n" + "%10---%11---%12       %13---%14---%15\t\t" + "10--11--12      13--14--15\n" + "|   |   |       |   |   |\t\t" + "|   |   |       |   |   |\n" + "|   |   %16---%17---%18   |   |\t\t" + "|   |   16--17--18  |   |\n" + "|   |       |       |   |\t\t" + "|   |       |       |   |\n" + "|   %19-------%20-------%21   |\t\t" + "|   19------20------21  |\n" + "|           |           |\t\t" + "|           |           |\n" + "%22-----------%23-----------%24\t\t" + "22----------23----------24\n";
    formatGamefield(log, map);
}
Example 34
Project: unutopia-android-master  File: MyListActivity2.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
    for (int x = 0; x < 10; x++) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("nombre", "Pepe " + x);
        map.put("apellido", "Lopez " + x);
        data.add(map);
    }
    int layout = android.R.layout.simple_list_item_2;
    String[] from = new String[] { "nombre", "apellido" };
    int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
    SimpleAdapter adapter = new SimpleAdapter(this, data, layout, from, to);
    setListAdapter(adapter);
}
Example 35
Project: raylew_algorithm-master  File: 统计字符.java View source code
public static void main(String[] args) {
    String str = "zdsgzd";
    Map map = new HashMap();
    int maxvalue = 0;
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (map.get(c) == null) {
            map.put(c, 1);
        } else {
            int total = (Integer) map.get(c);
            total++;
            map.put(c, total);
            if (maxvalue < total) {
                maxvalue = total;
            }
        }
    }
    System.out.println("maxvalue:" + maxvalue);
    System.out.println(map.toString());
    Set set = map.keySet();
    Iterator iterator = set.iterator();
    int max = 0;
    char maxkey = 0;
    char key = 0;
    while (iterator.hasNext()) {
        key = (Character) iterator.next();
        if (max <= (Integer) map.get(key)) {
            max = (Integer) map.get(key);
            maxkey = key;
        }
    }
    System.out.println(maxkey + ":" + max);
}
Example 36
Project: codemap-master  File: RegressionTestNN.java View source code
@Test
public void nearestNeighborRegression() {
    final HashMap<Point, Integer> points = new HashMap<Point, Integer>();
    QuickNDirtyMap.anotherDebugPointSet(points);
    Configuration configuration = new Configuration(points.keySet());
    MapInstance mapInstance = configuration.withSize(mapSize, new MapScheme<Double>() {

        @Override
        public Double forLocation(Point location) {
            // TODO fill in size
            return (double) points.get(location);
        }
    });
    int badCount = 0;
    for (int x = 0; x < mapInstance.width; x++) {
        for (int y = 0; y < mapInstance.height; y++) {
            Location kdTreeNearest = mapInstance.kdTreeNearest(x, y);
            Location naiveNearest = mapInstance.naiveNearest(x, y);
            if (naiveNearest.equals(kdTreeNearest))
                continue;
            badCount++;
        //                assertEquals(naiveNearest, kdTreeNearest);
        }
    }
    System.out.println("number of wrong neighbors: " + badCount);
}
Example 37
Project: bennu-master  File: FileStorageConfiguration.java View source code
public static void createMissingStorageConfigurations() {
    Map<String, FileStorageConfiguration> configs = new HashMap<>();
    for (FileStorageConfiguration config : FileSupport.getInstance().getConfigurationSet()) {
        if (FenixFramework.getDomainModel().findClass(config.getFileType()) == null) {
            config.delete();
        } else {
            configs.put(config.getFileType(), config);
        }
    }
    for (Class<? extends DomainObject> fileTypeClass : DomainModelUtil.getDomainClassHierarchy(GenericFile.class, true, false)) {
        if (!configs.containsKey(fileTypeClass.getName())) {
            new FileStorageConfiguration(fileTypeClass);
        }
    }
}
Example 38
Project: android-bankdroid-master  File: LegacyBankHelper.java View source code
private static void generateLegacyProviderReferences() {
    Map<Integer, String> references = new HashMap<>();
    Map<String, Integer> legacyIds = new HashMap<>();
    Field[] fields = IBankTypes.class.getFields();
    for (Field field : fields) {
        try {
            String reference = field.getName().toLowerCase().replaceAll("_", "-");
            Integer legacyId = field.getInt(new IBankTypes() {
            });
            references.put(legacyId, reference);
            legacyIds.put(reference, legacyId);
        } catch (IllegalAccessException e) {
            Timber.e(e, "Provider could not be mapped");
        }
    }
    legacyProviderReferences = legacyIds;
    providerReferences = references;
}
Example 39
Project: SensorsWebLogger-master  File: SendSensorData.java View source code
protected String addSensorDataToUrl(String url, HashMap parms) {
    if (!url.endsWith("?"))
        url += "?";
    List<NameValuePair> params = new LinkedList<NameValuePair>();
    Set set = parms.entrySet();
    Iterator i = set.iterator();
    while (i.hasNext()) {
        Map.Entry me = (Map.Entry) i.next();
        params.add(new BasicNameValuePair(String.valueOf(me.getKey()), String.valueOf(me.getValue())));
    }
    String paramString = URLEncodedUtils.format(params, "utf-8");
    url += paramString;
    return url;
}
Example 40
Project: park-alert-master  File: UserRankServlet.java View source code
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String ranks = "";
    int total = 10;
    HashMap<Integer, String> tmp = new HashMap<Integer, String>();
    for (String user : Container.userRank.keySet()) {
        tmp.put(Container.userRank.get(user), user);
    }
    Collection<Integer> value = Container.userRank.values();
    ArrayList<Integer> ranksList = new ArrayList<Integer>(value);
    Collections.sort(ranksList);
    for (Integer rank : ranksList) {
        if (total == 0) {
            break;
        } else {
            total--;
            ranks = ranks + tmp.get(rank) + ";" + rank + ":";
        }
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println(ranks);
}
Example 41
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 42
Project: REST-OCD-Services-master  File: NewmanModularityCombinedTest.java View source code
@Ignore
@Test
public void testOnJmol() throws AdapterException, FileNotFoundException, IllegalArgumentException, ParseException, OcdAlgorithmException, InterruptedException {
    CustomGraph graph = OcdTestGraphFactory.getJmolTestGraph();
    OcdAlgorithm algo = new CostFunctionOptimizationClusteringAlgorithm();
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put(CostFunctionOptimizationClusteringAlgorithm.MAXIMUM_K_NAME, Integer.toString(5));
    parameters.put(CostFunctionOptimizationClusteringAlgorithm.OVERLAPPING_THRESHOLD_NAME, Double.toString(0.3));
    algo.setParameters(parameters);
    Cover cover = algo.detectOverlappingCommunities(graph);
    NewmanModularityCombined metric = new NewmanModularityCombined();
    double value = metric.measure(cover);
    System.out.println(value);
}
Example 43
Project: Desktop-master  File: MetaDataTest.java View source code
public static void main(String[] args) {
    Map<ExtractorConfigKey, Object> config = new HashMap<ExtractorConfigKey, Object>();
    config.put(CommonConfigKeys.SEARCHVALUE, "Google Scholar's ranking Algorithm: An Overview");
    try {
        for (int i = 0; i < count; i++) {
            System.out.println(i + " von " + count);
            new GoogleScholarExtractor(config);
            Collection<MetaData> result = new GoogleScholarExtractor().search("Google Scholar's ranking Algorithm: An Overview");
            System.out.println(result.size());
        }
    } catch (MalformedConfigException e) {
        e.printStackTrace();
    }
}
Example 44
Project: TextSecureSMP-master  File: CountryListLoader.java View source code
@Override
public ArrayList<Map<String, String>> loadInBackground() {
    Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions();
    ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size());
    for (String region : regions) {
        Map<String, String> data = new HashMap<String, String>(2);
        data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region));
        data.put("country_code", "+" + PhoneNumberUtil.getInstance().getCountryCodeForRegion(region));
        results.add(data);
    }
    Collections.sort(results, new RegionComparator());
    return results;
}
Example 45
Project: cms-ce-master  File: TranslationReaderTest.java View source code
@Test
public void testTranslate() throws Exception {
    Map<String, String> translations = new HashMap<String, String>();
    translations.put("%__example__%", "alert");
    final String xslFilename = getClass().getName().replace('.', '/') + ".xsl";
    final InputStream xslInputStream = getClass().getClassLoader().getResourceAsStream(xslFilename);
    final Reader reader = new InputStreamReader(xslInputStream, Charset.forName("UTF-8"));
    final TranslationReader translationReader = new TranslationReader(translations, reader);
    final int length = xslInputStream.available();
    final char[] xslBuffer = new char[length];
    translationReader.read(xslBuffer, 0, length);
    final String xslString = new String(xslBuffer);
    assertFalse("The XSL contains untranslated string", xslString.contains("%__example__%"));
}
Example 46
Project: FireflowEngine20-master  File: MapPairInjector.java View source code
@SuppressWarnings("unchecked")
public Object get(ServletContext sc, HttpServletRequest req, HttpServletResponse resp, Object refer) {
    Map<String, Object> map = new HashMap<String, Object>();
    Enumeration<String> enu = (Enumeration<String>) req.getParameterNames();
    while (enu.hasMoreElements()) {
        String name = enu.nextElement();
        String[] vs = req.getParameterValues(name);
        // Null Value
        if (null == vs || vs.length == 0) {
            map.put(name, null);
        } else // Has Value
        if (vs.length == 1) {
            map.put(name, vs[0]);
        } else // Array Value
        {
            map.put(name, vs);
        }
    }
    return map;
}
Example 47
Project: McMMOPlus-master  File: PartyAutoKickTask.java View source code
@Override
public void run() {
    HashMap<OfflinePlayer, Party> toRemove = new HashMap<OfflinePlayer, Party>();
    List<String> processedPlayers = new ArrayList<String>();
    long currentTime = System.currentTimeMillis();
    for (Party party : PartyManager.getParties()) {
        for (String memberName : party.getMembers()) {
            OfflinePlayer member = mcMMO.p.getServer().getOfflinePlayer(memberName);
            boolean isProcessed = processedPlayers.contains(memberName);
            if ((!member.isOnline() && (currentTime - member.getLastPlayed() > KICK_TIME)) || isProcessed) {
                toRemove.put(member, party);
            }
            if (!isProcessed) {
                processedPlayers.add(memberName);
            }
        }
    }
    for (Entry<OfflinePlayer, Party> entry : toRemove.entrySet()) {
        PartyManager.removeFromParty(entry.getKey(), entry.getValue());
    }
}
Example 48
Project: jade_agents-master  File: HashMap.java View source code
/**
                 * @see jade.util.leap.Set interface
                 */
public Iterator iterator() {
    return new Iterator() {

        java.util.Iterator it = HashMap.this.realHiddenMap.keySet().iterator();

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public boolean hasNext() {
            return it.hasNext();
        }

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public Object next() {
            return it.next();
        }

        /**
                         * @see jade.util.leap.Iterator interface
                         */
        public void remove() {
            it.remove();
        }
    };
}
Example 49
Project: eclipse.jdt.ui-master  File: CleanUpTest17.java View source code
public void testRemoveRedundantTypeArguments1() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("import java.util.HashMap;\n");
    buf.append("import java.util.List;\n");
    buf.append("import java.util.Map;\n");
    buf.append("public class E {\n");
    buf.append("    void foo() {\n");
    buf.append("        new ArrayList<String>().add(\"a\")\n");
    buf.append("        List<String> a = new ArrayList<String>();\n");
    buf.append("        Map<Integer, String> m = new HashMap<Integer, String>();\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu1 = pack1.createCompilationUnit("E1.java", buf.toString(), false, null);
    enable(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("import java.util.HashMap;\n");
    buf.append("import java.util.List;\n");
    buf.append("import java.util.Map;\n");
    buf.append("public class E {\n");
    buf.append("    void foo() {\n");
    buf.append("        new ArrayList<String>().add(\"a\")\n");
    buf.append("        List<String> a = new ArrayList<>();\n");
    buf.append("        Map<Integer, String> m = new HashMap<>();\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 });
}
Example 50
Project: openjdk8-jdk-master  File: ZFSTests.java View source code
static void test7156873() throws Throwable {
    String DIRWITHSPACE = "testdir with spaces";
    Path dir = Paths.get(DIRWITHSPACE);
    Path path = Paths.get(DIRWITHSPACE, "file.zip");
    try {
        Files.createDirectory(dir);
        URI uri = URI.create("jar:" + path.toUri());
        Map<String, Object> env = new HashMap<String, Object>();
        env.put("create", "true");
        try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        }
    } finally {
        Files.deleteIfExists(path);
        Files.deleteIfExists(dir);
    }
}
Example 51
Project: lucene-solr-master  File: TestSimpleAttributeImpl.java View source code
// this checks using reflection API if the defaults are correct
public void testAttributes() {
    TestUtil.assertAttributeReflection(new PositionIncrementAttributeImpl(), Collections.singletonMap(PositionIncrementAttribute.class.getName() + "#positionIncrement", 1));
    TestUtil.assertAttributeReflection(new PositionLengthAttributeImpl(), Collections.singletonMap(PositionLengthAttribute.class.getName() + "#positionLength", 1));
    TestUtil.assertAttributeReflection(new FlagsAttributeImpl(), Collections.singletonMap(FlagsAttribute.class.getName() + "#flags", 0));
    TestUtil.assertAttributeReflection(new TypeAttributeImpl(), Collections.singletonMap(TypeAttribute.class.getName() + "#type", TypeAttribute.DEFAULT_TYPE));
    TestUtil.assertAttributeReflection(new PayloadAttributeImpl(), Collections.singletonMap(PayloadAttribute.class.getName() + "#payload", null));
    TestUtil.assertAttributeReflection(new KeywordAttributeImpl(), Collections.singletonMap(KeywordAttribute.class.getName() + "#keyword", false));
    TestUtil.assertAttributeReflection(new OffsetAttributeImpl(), new HashMap<String, Object>() {

        {
            put(OffsetAttribute.class.getName() + "#startOffset", 0);
            put(OffsetAttribute.class.getName() + "#endOffset", 0);
        }
    });
}