Java Code Examples for java.util.LinkedHashMap

The following are top voted examples for showing how to use java.util.LinkedHashMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: datarouter   File: DatarouterHttpRequestTests.java   Source Code and License 8 votes vote down vote up
@Test
public void testAddHeaders(){
	DatarouterHttpRequest request = new DatarouterHttpRequest(HttpRequestMethod.POST, URL, true);

	Map<String,List<String>> expectedHeaders = new LinkedHashMap<>();
	expectedHeaders.put("valid", Arrays.asList("header"));
	Map<String,String> headers = new LinkedHashMap<>();
	headers.put("valid", "header");
	request.addHeaders(headers);
	Assert.assertEquals(request.getHeaders(), expectedHeaders);

	headers.clear();
	headers.put("", "empty");
	headers.put(null, null);
	request.addHeaders(headers);
	Assert.assertEquals(request.getHeaders().size(), 1);

	request.setContentType(ContentType.TEXT_PLAIN);
	Assert.assertEquals(request.getHeaders().size(), 2);

	request.setContentType(ContentType.TEXT_HTML);
	Assert.assertEquals(request.getHeaders().size(), 2);
	Assert.assertEquals(request.getRequest().getAllHeaders().length, 3);
}
 
Example 2
Project: logistimo-web-service   File: Counter.java   Source Code and License 6 votes vote down vote up
public static ICounter getOrderCounter(Long domainId, String tag, Integer ordType,  String... tgType) {
  Map<String, Object> map = new LinkedHashMap<>();
  map.put(OBJECT_TYPE, "orders");
  if (tgType != null && tgType.length > 0) {
    switch (tgType[0]) {
      case TYPE_ORDER:
        map.put(O_TAGS, tag);
        break;
      default:
        map.put(K_TAGS, tag);
        break;
    }
  } else {
    map.put(K_TAGS, tag);
  }
  map.put(ORD_TYPE, ordType);
  return getInstance(domainId, map);
}
 
Example 3
Project: HCFCore   File: FlatFileDeathbanManager.java   Source Code and License 6 votes vote down vote up
@Override
public void saveDeathbanData() {
    Map<String, Integer> saveMap = new LinkedHashMap<>(livesMap.size());
    livesMap.forEachEntry(new TObjectIntProcedure<UUID>() {
        @Override
        public boolean execute(UUID uuid, int i) {
            saveMap.put(uuid.toString(), i);
            return true;
        }
    });

    livesConfig.set("lives", saveMap);
    livesConfig.save();
}
 
Example 4
Project: synthea_java   File: PrevalenceReport.java   Source Code and License 6 votes vote down vote up
/**
 * Calculates the prevalence rate and percent based on what is on that line of the report. Inserts
 * result of calculation into the prevalence rate and percent columns.
 */
private static void completeSyntheaFields(Connection connection,
    LinkedHashMap<String, String> line) throws SQLException {

  if ((line.get(OCCUR).isEmpty()) || (line.get(POP).isEmpty())) {
    line.put(PREV_RATE, (null));
    line.put(PREV_PERCENT, (null));
  } else {
    double occurr = Double.parseDouble(line.get(OCCUR));
    double pop = Double.parseDouble(line.get(POP));

    if (pop != 0) {
      double prevRate = occurr / pop;
      double prevPercent = prevRate * 100;
      line.put(PREV_RATE, Double.toString(prevRate));
      line.put(PREV_PERCENT, Double.toString(prevPercent));
    } else {
      line.put(PREV_RATE, Double.toString(0));
      line.put(PREV_PERCENT, Double.toString(0));
    }
  }
}
 
Example 5
Project: bpm-client   File: SuperviseMatterServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Object saveSuperviseMatter(String token, Map taskForm) {
    UserVO user = getUser(token); // 获取用户信息
    checkedParameter(taskForm, "type", "title", "describe"); // 检测参数
    String formId = getUUID(), uid = user.getId(); // 生成FormData 相关参数
    Map processObject = startProcess(uid, formId); // 启动流程
    FormDataDO formData = saveSuperviseMatterFromData(taskForm,
            processObject, uid, formId); // 保存进入数据库

    // 整理返回数据
    Map variables = new LinkedHashMap();
    variables.put("fromInfo", formData);
    variables.put("processInfo", processObject);

    return variables;
}
 
Example 6
Project: scanning   File: ScanAtomAssemblerTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test that the ArrayModel can be used to create paths
 */
@Test
public void testArrayPath() throws QueueModelException {
	ScanAtomAssembler scAtAss = new ScanAtomAssembler(null);
	ArrayModel arrayModel = new ArrayModel(new double[]{15.8, 16.5, 15.9, 14.2});
	arrayModel.setName("stage_y");
	CompoundModel<?> cMod = new CompoundModel<>();
	cMod.addData(arrayModel, null);

	/*
	 * Fully specified by template
	 */
	Map<String, DeviceModel> pMods = new LinkedHashMap<>();
	Map<String, Object> devConf = new HashMap<>();
	devConf.put("positions", new Double[]{15.8, 16.5, 15.9, 14.2});
	DeviceModel pathModel = new DeviceModel("Array", devConf);
	pMods.put("stage_y", pathModel);
	ScanAtom scAtMod = new ScanAtom("testScan", pMods, new HashMap<String, DeviceModel>(), new ArrayList<Object>());

	ScanAtom assAt = scAtAss.assemble(scAtMod, new ExperimentConfiguration(null, null, null));
	assertEquals("Template specified path differs from expected", cMod, assAt.getScanReq().getCompoundModel());
}
 
Example 7
Project: flight-management-system-java   File: MainWindow.java   Source Code and License 6 votes vote down vote up
public void loadTableBD(String dateAuj) {
    Result res = db.execute("MATCH (a:Avion)-[r:Affecter]->(d:Depart)<-[c:Constituer]-(v:Vol) WHERE d.date='"+dateAuj+"' RETURN d.numero, d.date, v.villeDep, v.villeArr,  a.type, a.capacite, v.numero, v.heureDep, v.heureArr");
    DefaultTableModel dtm = new DefaultTableModel(0,0);
    String header[] = {"Numero", "Date","Depart", "Arriveé", "Type", "Capacite", "NumVol", "Heure De Depart", "Heure d'arrive"};
    String test[] = {"d.numero", "d.date","v.villeDep", "v.villeArr", "a.type", "a.capacite", "v.numero", "v.heureDep", "v.heureArr"};
    dtm.setColumnIdentifiers(header);
    jTable1.setModel(dtm);
    while(res.hasNext()) {
        Map<String, Object> row = res.next();
        Map<String, Object> obj = new LinkedHashMap();
        for (String t:test) {
            obj.put(t, null);
        }
        for(Map.Entry<String, Object> col : row.entrySet()) {
             obj.put(col.getKey(),col.getValue());   
        }
        
        dtm.addRow(obj.values().toArray());
}
}
 
Example 8
Project: OpenJSharp   File: Resolve.java   Source Code and License 6 votes vote down vote up
private Map<Symbol, JCDiagnostic> mapCandidates() {
    Map<Symbol, JCDiagnostic> candidates = new LinkedHashMap<Symbol, JCDiagnostic>();
    for (Candidate c : resolveContext.candidates) {
        if (c.isApplicable()) continue;
        candidates.put(c.sym, c.details);
    }
    return candidates;
}
 
Example 9
Project: XXXX   File: FeignTest.java   Source Code and License 6 votes vote down vote up
@Test
public void queryMapKeysMustBeStrings() throws Exception {
  server.enqueue(new MockResponse());

  TestInterface api = new TestInterfaceBuilder().target("http://localhost:" + server.getPort());

  Map<Object, String> queryMap = new LinkedHashMap<Object, String>();
  queryMap.put(Integer.valueOf(42), "alice");

  try {
    api.queryMap((Map) queryMap);
    Fail.failBecauseExceptionWasNotThrown(IllegalStateException.class);
  } catch (IllegalStateException ex) {
    assertThat(ex).hasMessage("QueryMap key must be a String: 42");
  }
}
 
Example 10
Project: alevin-svn2   File: CompleteNodeLinkMappingHiddenHop.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param vNet
 * @return The set of substrate candidates for each virtual node of vNet
 */
private Map<VirtualNode, List<SubstrateNode>> createCandidateSet(
		SubstrateNetwork sNet, VirtualNetwork vNet) {
	Map<VirtualNode, List<SubstrateNode>> candidateSet = new LinkedHashMap<VirtualNode, List<SubstrateNode>>();
	List<SubstrateNode> substrateSet;
	for (Iterator<VirtualNode> itt = vNet.getVertices().iterator(); itt
			.hasNext();) {
		substrateSet = new LinkedList<SubstrateNode>();
		VirtualNode currVnode = itt.next();
		if (nodeMapping.containsKey(currVnode)) {
			substrateSet.add(nodeMapping.get(currVnode));
		} else {
			substrateSet.addAll(findFulfillingNodes(sNet, currVnode));
		}
		candidateSet.put(currVnode, substrateSet);
	}
	return candidateSet;
}
 
Example 11
Project: oneops   File: AntennaWsController.java   Source Code and License 6 votes vote down vote up
/**
 * Get the cache entry for specific nsPath. If the API returns an entry
 * doesn't mean that entry was existing in the Cache because the cache loader
 * would fetch and load a non existing entry on demand upon expiry.
 *
 * @param nsPath message nspath
 * @return cache entry map.
 */
@RequestMapping(value = "/cache/entry", method = GET)
@ResponseBody
public ResponseEntity<Map<String, Object>> getCacheEntry(@RequestParam(value = "nsPath", required = true) String nsPath) {
    Map<String, Object> stat = new LinkedHashMap<>(2);
    List<BasicSubscriber> entry;
    try {
        entry = cache.instance().get(new SinkKey(nsPath));
    } catch (ExecutionException e) {
        stat.put("status", e.getMessage());
        return new ResponseEntity<>(stat, NOT_FOUND);
    }
    stat.put("status", "ok");
    stat.put("entry", entry.toString());
    return new ResponseEntity<>(stat, OK);
}
 
Example 12
Project: MTweaks-KernelAdiutorMOD   File: ProfileActivity.java   Source Code and License 6 votes vote down vote up
private void returnIntent(LinkedHashMap<String, String> commandsList) {
    ArrayList<String> ids = new ArrayList<>();
    ArrayList<String> commands = new ArrayList<>();
    Collections.addAll(ids, commandsList.keySet().toArray(new String[commands.size()]));
    Collections.addAll(commands, commandsList.values().toArray(new String[commands.size()]));
    if (commands.size() > 0) {
        Intent intent = new Intent();
        intent.putExtra(POSITION_INTENT, mProfilePosition);
        intent.putExtra(RESULT_ID_INTENT, ids);
        intent.putExtra(RESULT_COMMAND_INTENT, commands);
        setResult(0, intent);
        finish();
    } else {
        Utils.toast(R.string.no_changes, ProfileActivity.this);
    }
}
 
Example 13
Project: googles-monorepo-demo   File: ClassPath.java   Source Code and License 6 votes vote down vote up
@VisibleForTesting
static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classloader) {
  LinkedHashMap<File, ClassLoader> entries = Maps.newLinkedHashMap();
  // Search parent first, since it's the order ClassLoader#loadClass() uses.
  ClassLoader parent = classloader.getParent();
  if (parent != null) {
    entries.putAll(getClassPathEntries(parent));
  }
  if (classloader instanceof URLClassLoader) {
    URLClassLoader urlClassLoader = (URLClassLoader) classloader;
    for (URL entry : urlClassLoader.getURLs()) {
      if (entry.getProtocol().equals("file")) {
        File file = toFile(entry);
        if (!entries.containsKey(file)) {
          entries.put(file, classloader);
        }
      }
    }
  }
  return ImmutableMap.copyOf(entries);
}
 
Example 14
Project: WeiXing_xmu-2016-MrCode   File: IndexAction.java   Source Code and License 6 votes vote down vote up
@Action(value="toOrder", results={@Result(name="orderUI", location=ViewLocation.View_ROOT+
		"hotel.jsp")})
public String toOrder() throws Exception{
	//TODO 跳转到选择团购券的页面
	Customer customer = (Customer)session.get(Const.CUSTOMER);
	List<Grouppurchasevoucher> gps = grouppurchasevoucherService.getByCust(customer);
	
	//把数据封装成Map
	Map<Roomtype, List<Grouppurchasevoucher>> rgMap = new LinkedHashMap<Roomtype, List<Grouppurchasevoucher>>();
	for(Grouppurchasevoucher gp : gps){
		if(!rgMap.containsKey(gp.getRoomtype())){
			List<Grouppurchasevoucher> grps = new LinkedList<Grouppurchasevoucher>();
			rgMap.put(gp.getRoomtype(), grps);
		}
		rgMap.get(gp.getRoomtype()).add(gp);
	}
	
	request.setAttribute("rgMap", rgMap);
	
	return "orderUI";
}
 
Example 15
Project: ZooKeeper   File: ZooInspectorManagerImpl.java   Source Code and License 6 votes vote down vote up
public Pair<Map<String, List<String>>, Map<String, String>> getConnectionPropertiesTemplate() {
    Map<String, List<String>> template = new LinkedHashMap<String, List<String>>();
    template.put(CONNECT_STRING, Arrays
            .asList(new String[] { defaultHosts }));
    template.put(SESSION_TIMEOUT, Arrays
            .asList(new String[] { defaultTimeout }));
    template.put(DATA_ENCRYPTION_MANAGER, Arrays
            .asList(new String[] { defaultEncryptionManager }));
    template.put(AUTH_SCHEME_KEY, Arrays
            .asList(new String[] { defaultAuthScheme }));
    template.put(AUTH_DATA_KEY, Arrays
            .asList(new String[] { defaultAuthValue }));
    Map<String, String> labels = new LinkedHashMap<String, String>();
    labels.put(CONNECT_STRING, "Connect String");
    labels.put(SESSION_TIMEOUT, "Session Timeout");
    labels.put(DATA_ENCRYPTION_MANAGER, "Data Encryption Manager");
    labels.put(AUTH_SCHEME_KEY, "Authentication Scheme");
    labels.put(AUTH_DATA_KEY, "Authentication Data");
    return new Pair<Map<String, List<String>>, Map<String, String>>(
            template, labels);
}
 
Example 16
Project: incubator-netbeans   File: TimesCollectorPeer.java   Source Code and License 6 votes vote down vote up
private synchronized Map<String, Description> getKey2Desc(final Object fo) {
    Map<String, Description> result = fo2Key2Desc.get(fo);
    
    if (result == null) {
        files.add(new CleanableWeakReference<Object>(fo));
        fo2Key2Desc.put(fo, result = Collections.synchronizedMap(new LinkedHashMap<String, Description>()));
        pcs.firePropertyChange("fos", null, fo);
        
        if (fo instanceof FileObject) {
            ((FileObject)fo).addFileChangeListener(new FileChangeAdapter() {
                @Override
                public void fileDeleted(FileEvent ev) {
                    fileDeletedSync(ev, (FileObject)fo);
                }
            });
        }
    }
    return result;
}
 
Example 17
Project: gradle-postgresql-embedded   File: GradlePostgresqlEmbeddedPlugin.java   Source Code and License 6 votes vote down vote up
IVersion parseVersion(String version) {
	Map<String, IVersion> versions = new LinkedHashMap<>();

	versions.put(PRODUCTION.name(), PRODUCTION);
	versions.put(V10.name(), V10);
	versions.put(V9_6.name(), V9_6);
	versions.put(V9_5.name(), V9_5);

	versions.put(V10_0.name(), V10_0);
	versions.put(V9_6_5.name(), V9_6_5);

	versions.put(V10_0.asInDownloadPath(), V10_0);
	versions.put(V9_6_5.asInDownloadPath(), V9_6_5);

	return versions.getOrDefault(version, () -> version);
}
 
Example 18
Project: xemime   File: DotCallNode.java   Source Code and License 6 votes vote down vote up
@Override
public Node run() throws Exception {
    Node o = obj.run();
    if (map != null) {
        LinkedHashMap<Symbol, Node> map2 = new LinkedHashMap<>();
        for (Map.Entry<Symbol, Node> entry : map.entrySet()) map2.put(entry.getKey(), entry.getValue().run());
        map = map2;
        o = o.message(getLocation(), symbol, map);
        return o;
    } else if (list != null) {
        ArrayList<Node> list2 = new ArrayList<>();
        for (Node arg : list) list2.add(arg.run());
        list = list2;
        o = o.message(getLocation(), symbol, list);
        return o;
    } else {
        o = o.message(getLocation(), symbol, new ArrayList<>());
        return o;
    }
}
 
Example 19
Project: hy.common.report   File: RTemplate.java   Source Code and License 6 votes vote down vote up
public RTemplate()
{
    this.sheetIndex           = 0;
    this.direction            = 0;
    this.templateSheet        = null;
    this.excelVersion         = null;
    this.valueMethods         = new LinkedHashMap<String ,RCellGroup>();
    this.valueNames           = new Hashtable<String ,String>();
    this.autoHeights         = new Hashtable<String ,Object>();
    this.valueListeners       = new Hashtable<String ,ValueListener>();
    this.sheetListeners       = new ArrayList<SheetListener>();
    this.isIntegerShowDecimal = false;
    this.isExcelFilter        = false;
    this.cells                = new HashMap<String ,RCell>();
    this.isSafe               = false;
    this.isBig                = true;
    this.isCheck              = true;
    this.rowAccessWindowSize  = SXSSFWorkbook.DEFAULT_WINDOW_SIZE * 10;
    this.titlePageHeaderFirstWriteByRow           = 0;
    this.titlePageHeaderFirstWriteByRealDataCount = 0;
    this.titlePageHeaderRate                      = 0;
    this.setValueSign(":");
    this.setTitleUseOnePage(false);
}
 
Example 20
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 6 votes vote down vote up
/**
 * Return ordered custom fields by the given identifiers
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param customFields
 *            the expected custom fields identifiers.
 * @param project
 *            Jira project identifier. Required to filter custom field agains contexts.
 * @return ordered custom fields by their identifier.
 */
public Map<Integer, CustomFieldEditor> getCustomFieldsById(final DataSource dataSource, final Set<Integer> customFields, final int project) {
	if (customFields.isEmpty()) {
		// No custom field, we save an useless query
		return new HashMap<>();
	}

	// Get map as list
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	final RowMapper<CustomFieldEditor> rowMapper = new BeanPropertyRowMapper<>(CustomFieldEditor.class);
	final List<CustomFieldEditor> resultList = jdbcTemplate
			.query("SELECT ID AS id, TRIM(cfname) AS name, DESCRIPTION AS description, CUSTOMFIELDTYPEKEY AS fieldType FROM customfield WHERE ID IN ("
					+ newIn(customFields) + ") ORDER BY id", rowMapper, customFields.toArray());

	// Make a Map of valid values for single/multi select values field
	final Map<Integer, CustomFieldEditor> result = new LinkedHashMap<>();
	addListToMapIdentifier(dataSource, resultList, result, project);
	return result;
}
 
Example 21
Project: pac4j-plus   File: DefaultSecurityLogicTests.java   Source Code and License 5 votes vote down vote up
@Test
public void testAlreadyAuthenticatedNotAuthorized() throws Exception {
    final CommonProfile profile = new CommonProfile();
    final LinkedHashMap<String, CommonProfile> profiles = new LinkedHashMap<>();
    profiles.put(NAME, profile);
    context.setSessionAttribute(Pac4jConstants.USER_PROFILES, profiles);
    final IndirectClient indirectClient = new MockIndirectClient(NAME, null, new MockCredentials(), new CommonProfile());
    authorizers = NAME;
    config.setClients(new Clients(CALLBACK_URL, indirectClient));
    config.addAuthorizer(NAME, (context, prof) -> ID.equals(((CommonProfile) prof.get(0)).getId()));
    call();
    assertEquals(403, context.getResponseStatus());
}
 
Example 22
Project: elasticsearch_my   File: ContextCompletionSuggestSearchIT.java   Source Code and License 5 votes vote down vote up
public void testSingleContextBoosting() throws Exception {
    CategoryContextMapping contextMapping = ContextBuilder.category("cat").field("cat").build();
    LinkedHashMap<String, ContextMapping> map = new LinkedHashMap<String, ContextMapping>(Collections.singletonMap("cat", contextMapping));
    final CompletionMappingBuilder mapping = new CompletionMappingBuilder().context(map);
    createIndexAndMapping(mapping);
    int numDocs = 10;
    List<IndexRequestBuilder> indexRequestBuilders = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        indexRequestBuilders.add(client().prepareIndex(INDEX, TYPE, "" + i)
                .setSource(jsonBuilder()
                                .startObject()
                                .startObject(FIELD)
                                .field("input", "suggestion" + i)
                                .field("weight", i + 1)
                                .endObject()
                                .field("cat", "cat" + i % 2)
                                .endObject()
                ));
    }
    indexRandom(true, indexRequestBuilders);
    CompletionSuggestionBuilder prefix = SuggestBuilders.completionSuggestion(FIELD).prefix("sugg")
            .contexts(Collections.singletonMap("cat",
                    Arrays.asList(CategoryQueryContext.builder().setCategory("cat0").setBoost(3).build(),
                    CategoryQueryContext.builder().setCategory("cat1").build()))
            );
    assertSuggestions("foo", prefix, "suggestion8", "suggestion6", "suggestion4", "suggestion9", "suggestion2");
}
 
Example 23
Project: xemime   File: Function.java   Source Code and License 5 votes vote down vote up
protected Node exec(ArrayList<Node> args, Address self) throws Exception {
    return exec(new LinkedHashMap<Symbol, Node>(){{
        int i = 1;
        for (Map.Entry<Symbol, Type> entry : params.entrySet()) {
            put(entry.getKey(), args.get(i));
            i ++;
        }
    }}, self);
}
 
Example 24
Project: datatree-adapters   File: JsonJohnzon.java   Source Code and License 5 votes vote down vote up
@Override
public Object parse(String source) throws Exception {
	char c = source.charAt(0);
	if (c == '{') {
		return mapper.readObject(source, LinkedHashMap.class);
	}
	if (c == '[') {
		return mapper.readObject(source, Object[].class);
	}
	throw new IllegalArgumentException("Malformed JSON: " + source);
}
 
Example 25
Project: elasticsearch_my   File: InheritingState.java   Source Code and License 5 votes vote down vote up
@Override
public void makeAllBindingsToEagerSingletons(Injector injector) {
    Map<Key<?>, Binding<?>> x = new LinkedHashMap<>();
    for (Map.Entry<Key<?>, Binding<?>> entry : this.explicitBindingsMutable.entrySet()) {
        Key key = entry.getKey();
        BindingImpl<?> binding = (BindingImpl<?>) entry.getValue();
        Object value = binding.getProvider().get();
        x.put(key, new InstanceBindingImpl<Object>(injector, key, SourceProvider.UNKNOWN_SOURCE, new InternalFactory.Instance(value),
                emptySet(), value));
    }
    this.explicitBindingsMutable.clear();
    this.explicitBindingsMutable.putAll(x);
}
 
Example 26
Project: uavstack   File: SlowOperSpan.java   Source Code and License 5 votes vote down vote up
public Map<String, Object> toMap() {

        Map<String, Object> m = new LinkedHashMap<String, Object>();

        m.put("traceid", this.traceId);
        m.put("spanid", this.spanId);
        m.put("epinfo", this.endpointInfo);
        m.put("appid", this.appid);

        return m;
    }
 
Example 27
Project: android-chunk-utils   File: ResourceConfiguration.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a map of the configuration parts for {@link #toString}.
 *
 * <p>If a configuration part is not defined for this {@link ResourceConfiguration}, its value
 * will be the empty string.
 */
public final Map<Type, String> toStringParts() {
  Map<Type, String> result = new LinkedHashMap<>();  // Preserve order for #toString().
  result.put(Type.MCC, mcc() != 0 ? "mcc" + mcc() : "");
  result.put(Type.MNC, mnc() != 0 ? "mnc" + mnc() : "");
  result.put(Type.LANGUAGE_STRING, !languageString().isEmpty() ? "" + languageString() : "");
  result.put(Type.REGION_STRING, !regionString().isEmpty() ? "r" + regionString() : "");
  result.put(Type.SCREEN_LAYOUT_DIRECTION,
      getOrDefault(SCREENLAYOUT_LAYOUTDIR_VALUES, screenLayoutDirection(), ""));
  result.put(Type.SMALLEST_SCREEN_WIDTH_DP,
      smallestScreenWidthDp() != 0 ? "sw" + smallestScreenWidthDp() + "dp" : "");
  result.put(Type.SCREEN_WIDTH_DP, screenWidthDp() != 0 ? "w" + screenWidthDp() + "dp" : "");
  result.put(Type.SCREEN_HEIGHT_DP, screenHeightDp() != 0 ? "h" + screenHeightDp() + "dp" : "");
  result.put(Type.SCREEN_LAYOUT_SIZE,
      getOrDefault(SCREENLAYOUT_SIZE_VALUES, screenLayoutSize(), ""));
  result.put(Type.SCREEN_LAYOUT_LONG,
      getOrDefault(SCREENLAYOUT_LONG_VALUES, screenLayoutLong(), ""));
  result.put(Type.SCREEN_LAYOUT_ROUND,
      getOrDefault(SCREENLAYOUT_ROUND_VALUES, screenLayoutRound(), ""));
  result.put(Type.ORIENTATION, getOrDefault(ORIENTATION_VALUES, orientation(), ""));
  result.put(Type.UI_MODE_TYPE, getOrDefault(UI_MODE_TYPE_VALUES, uiModeType(), ""));
  result.put(Type.UI_MODE_NIGHT, getOrDefault(UI_MODE_NIGHT_VALUES, uiModeNight(), ""));
  result.put(Type.DENSITY_DPI, getOrDefault(DENSITY_DPI_VALUES, density(), density() + "dpi"));
  result.put(Type.TOUCHSCREEN, getOrDefault(TOUCHSCREEN_VALUES, touchscreen(), ""));
  result.put(Type.KEYBOARD_HIDDEN, getOrDefault(KEYBOARDHIDDEN_VALUES, keyboardHidden(), ""));
  result.put(Type.KEYBOARD, getOrDefault(KEYBOARD_VALUES, keyboard(), ""));
  result.put(Type.NAVIGATION_HIDDEN,
      getOrDefault(NAVIGATIONHIDDEN_VALUES, navigationHidden(), ""));
  result.put(Type.NAVIGATION, getOrDefault(NAVIGATION_VALUES, navigation(), ""));
  result.put(Type.SDK_VERSION, sdkVersion() != 0 ? "v" + sdkVersion() : "");
  return result;
}
 
Example 28
Project: logistimo-web-service   File: Counter.java   Source Code and License 5 votes vote down vote up
public static ICounter getTransferOrderCounter(Long domainId, Long entityId, String otype) {
  Map<String, Object> map = new LinkedHashMap<>();
  map.put(OBJECT_TYPE, "orders");
  map.put(K_ID, entityId);
  map.put(ORD_TYPE, 0);
  map.put(ORDER_TYPE, otype);
  return getInstance(domainId, map);
}
 
Example 29
Project: googles-monorepo-demo   File: ImmutableBiMapTest.java   Source Code and License 5 votes vote down vote up
public void testCopyOf() {
  Map<String, Integer> original = new LinkedHashMap<String, Integer>();
  original.put("one", 1);
  original.put("two", 2);
  original.put("three", 3);

  ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
  assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
  assertSame(copy, ImmutableBiMap.copyOf(copy));
}
 
Example 30
Project: Hydrograph   File: TransformUiConverter.java   Source Code and License 5 votes vote down vote up
private void createPropagationDataForOperationFileds(GridRow gridRow) {
	ComponentsOutputSchema componentsOutputSchema = null;
	Map<String, ComponentsOutputSchema> schemaMap = (Map<String, ComponentsOutputSchema>) propertyMap.get(Constants.SCHEMA_TO_PROPAGATE);
	if (schemaMap == null) {
		schemaMap = new LinkedHashMap<>();
		componentsOutputSchema = new ComponentsOutputSchema();
		schemaMap.put(Constants.FIXED_OUTSOCKET_ID, componentsOutputSchema);
		 propertyMap.put(Constants.SCHEMA_TO_PROPAGATE, schemaMap);
	} else if (schemaMap.get(Constants.FIXED_OUTSOCKET_ID) == null) {
		componentsOutputSchema = new ComponentsOutputSchema();
		schemaMap.put(Constants.FIXED_OUTSOCKET_ID, componentsOutputSchema);
	}
	componentsOutputSchema = schemaMap.get(Constants.FIXED_OUTSOCKET_ID);
	componentsOutputSchema.addSchemaFields(gridRow);
}
 
Example 31
Project: mongodb-rdbms-sync   File: OrclToMngSyncReader.java   Source Code and License 5 votes vote down vote up
private void refreshConnection() throws SQLException, InterruptedException, SyncError {
	Thread.sleep(waitTime);
	waitTime *= retryCount;
	for (SelectQueryHolder holder : queryMap.values()) {
		DbResourceUtils.closeResources(null, holder.getPstmt(), null);
	}
	DbResourceUtils.closeResources(null, null, connection);
	queryMap = new LinkedHashMap<String, SelectQueryHolder>();
	connection = DBCacheManager.INSTANCE.getCachedOracleConnection(map.getSourceDbName(), map.getSourceUserName());
}
 
Example 32
Project: aws-sdk-java-v2   File: PutItemSpec.java   Source Code and License 5 votes vote down vote up
/**
 * Applicable only when an expression has been specified.
 * Used to specify the actual values for the attribute-name placeholders,
 * where the value in the map can either be string for simple attribute
 * name, or a JSON path expression.
 */
public PutItemSpec withNameMap(Map<String, String> nameMap) {
    if (nameMap == null) {
        this.nameMap = null;
    } else {
        this.nameMap = Collections.unmodifiableMap(
                new LinkedHashMap<String, String>(nameMap));
    }
    return this;
}
 
Example 33
Project: alvisnlp   File: FeatureElement.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String,List<String>> getFeatures() {
	Map<String,List<String>> result = new LinkedHashMap<String,List<String>>(element.getFeatures());
	result.put(KEY_FEATURE_KEY, Collections.singletonList(this.key));
	result.put(VALUE_FEATURE_KEY, Collections.singletonList(this.value));
	return result;
}
 
Example 34
Project: GitHub   File: LruCache.java   Source Code and License 5 votes vote down vote up
/** Create a cache with a given maximum size in bytes. */
public LruCache(int maxSize) {
  if (maxSize <= 0) {
    throw new IllegalArgumentException("Max size must be positive.");
  }
  this.maxSize = maxSize;
  this.map = new LinkedHashMap<>(0, 0.75f, true);
}
 
Example 35
Project: Huochexing12306   File: TT.java   Source Code and License 5 votes vote down vote up
public static Map<String, String> getPassenger_card_types() {
	if (passenger_card_types == null){
		passenger_card_types = new LinkedHashMap<String, String>();
		passenger_card_types.put("一代身份证","2");
		passenger_card_types.put("二代身份证","1");
		passenger_card_types.put("临时证","3");
		passenger_card_types.put("护照","B");
		passenger_card_types.put("港澳通行证","C");
		passenger_card_types.put("台湾通行证","G");
	}
	return passenger_card_types;
}
 
Example 36
Project: Mount   File: PackageItemAdapter.java   Source Code and License 5 votes vote down vote up
public PackageItemAdapter(Context context, List<PackageRecord> list) {
    super(context, R.layout.layout_package_item, list);

    mContext = context;
    mPackageList = list;
    mSectionMap = new LinkedHashMap<>();
    mSectionArray = new String[0];

    buildSection();
}
 
Example 37
Project: Azure-Functions-For-Java-Sample   File: TranslatorFunction.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param request
 * @param context
 * @return
 */
@FunctionName("translate")
public HttpResponseMessage translate(@HttpTrigger(name = "req",
        methods = {"post"},
        authLevel = AuthorizationLevel.ANONYMOUS, dataType = "string") HttpRequestMessage request,
        final ExecutionContext context) {
    context.getLogger().info("Translator was invoked:");

    Map headers = request.getHeaders();
    Object body = request.getBody();
    String originText = "";

    String contentType = (String) headers.get("content-type");
    switch (contentType) {
        case "application/json":
            originText = getTextFromJSon((LinkedHashMap) body);
            break;
        case "text/plain":
            originText = (String) body;
            break;
        default:
            break;
    }
    TranslatorTextServices translator = new TranslatorTextServices();
    String translateEnglishToJapanese = translator.translateEnglishToJapanese(originText);
    String jsonBody = createJSonMessage(originText,translateEnglishToJapanese);
    context.getLogger().info(jsonBody);

    HttpResponseMessage response = request
            .createResponse(200, jsonBody);
    return response;
}
 
Example 38
Project: CommentView   File: Autolink.java   Source Code and License 5 votes vote down vote up
public void linkToCashtag(Extractor.Entity entity, String text, StringBuilder builder) {
    CharSequence cashtag = entity.getValue();

    Map<String, String> attrs = new LinkedHashMap<String, String>();
    attrs.put("href", cashtagUrlBase + cashtag);
    attrs.put("title", "$" + cashtag);
    attrs.put("class", cashtagClass);

    linkToTextWithSymbol(entity, "$", cashtag, attrs, builder);
}
 
Example 39
Project: LightSIP   File: NameValueList.java   Source Code and License 5 votes vote down vote up
/**
 * @return the hmap
 */
   protected Map<String,NameValue> getMap() {
	if(this.hmap == null) {
		if (sync) {
			this.hmap = new ConcurrentHashMap<String,NameValue>(0);
		} else {
			this.hmap = new LinkedHashMap<String,NameValue>(0);
		}
	}
	return hmap;
}
 
Example 40
Project: Hydrograph   File: Component.java   Source Code and License 5 votes vote down vote up
/**
 * Instantiates a new component.
 */
public Component() {
	location = new Point(0, 0);
	size = new Dimension(100, 80);
	properties = new LinkedHashMap<>();
	subJobContainer= new LinkedHashMap<>();
	leftPortCount = 0;
	rightPortCount = 0;
	bottomPortCount = 0;
	inputLinksHash = new Hashtable<String, ArrayList<Link>>();

	inputLinks = new ArrayList<Link>();
	outputLinksHash = new Hashtable<String, ArrayList<Link>>();
	outputLinks = new ArrayList<Link>();
	inputportTerminals = new ArrayList<String>();
	outputPortTerminals = new ArrayList<String>();
	watcherTerminals = new HashMap();
	newInstance = true;
	validityStatus = ValidityStatus.WARN.name();
	componentName = DynamicClassProcessor.INSTANCE.getClazzName(this
			.getClass());

	componentLabel = new ComponentLabel(componentName);
	componentLabelMargin = 16;

	prefix = XMLConfigUtil.INSTANCE.getComponent(componentName)
			.getDefaultNamePrefix();
	
	defaultPrefix=XMLConfigUtil.INSTANCE.getComponent(componentName)
			.getDefaultNamePrefix();
	initPortSettings();
	toolTipErrorMessages = new LinkedHashMap<>();
	status = ComponentExecutionStatus.BLANK;
}
 
Example 41
Project: Pxls   File: AuthService.java   Source Code and License 5 votes vote down vote up
protected static Map<String, String> parseQuery(String s) {
    Map<String, String> query_pairs = new LinkedHashMap<String, String>();
    try {
        String query = s;
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
        }
    } catch (UnsupportedEncodingException e) {
        
    }
    return query_pairs;
}
 
Example 42
Project: ucar-weex-core   File: FunctionParser.java   Source Code and License 5 votes vote down vote up
private LinkedHashMap<K, V> definition() {
  LinkedHashMap<K, V> result = new LinkedHashMap<>();
  do {
    result.putAll(function());
  } while (lexer.getCurrentToken() == Token.FUNC_NAME);
  return result;
}
 
Example 43
Project: enigma-vk   File: MappingsConverter.java   Source Code and License 5 votes vote down vote up
public static void convertMappings(Mappings mappings, BiMap<ClassEntry,ClassEntry> changes) {
	
	// sort the changes so classes are renamed in the correct order
	// ie. if we have the mappings a->b, b->c, we have to apply b->c before a->b
	LinkedHashMap<ClassEntry,ClassEntry> sortedChanges = Maps.newLinkedHashMap();
	int numChangesLeft = changes.size();
	while (!changes.isEmpty()) {
		Iterator<Map.Entry<ClassEntry,ClassEntry>> iter = changes.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<ClassEntry,ClassEntry> change = iter.next();
			if (changes.containsKey(change.getValue())) {
				sortedChanges.put(change.getKey(), change.getValue());
				iter.remove();
			}
		}
		
		// did we remove any changes?
		if (numChangesLeft - changes.size() > 0) {
			// keep going
			numChangesLeft = changes.size();
		} else {
			// can't sort anymore. There must be a loop
			break;
		}
	}
	if (!changes.isEmpty()) {
		throw new Error("Unable to sort class changes! There must be a cycle.");
	}
	
	// convert the mappings in the correct class order
	for (Map.Entry<ClassEntry,ClassEntry> entry : sortedChanges.entrySet()) {
		mappings.renameObfClass(entry.getKey().getName(), entry.getValue().getName());
	}
}
 
Example 44
Project: kaltura-ce-sakai-extension   File: KalturaAPIServiceStub.java   Source Code and License 5 votes vote down vote up
@Override
protected Map<String, Map<String, String>> getMetadataForEntry(String containerId, String... entryIds) {
    if (entryIds == null) {
        throw new IllegalArgumentException("entry id must be set");
    }
    if (StringUtils.isEmpty(containerId)) {
        throw new IllegalArgumentException("container id must be set");
    }
    Map<String, Map<String, String>> metadata = new LinkedHashMap<String, Map<String, String>>();
    List<MediaItem> itemsList = mockItems;
    if (!containerId.startsWith("ref-")) {
        // this is probably a collection so look through the collections
        for (MediaCollection mc : mockCollections) {
            if (StringUtils.equals(mc.getId(), containerId)) {
                if (mc.getItems() != null) {
                    itemsList = mc.getItems();
                }
                break;
            }
        }
    }
    for (String entryId : entryIds) {
        Map<String, String> entryMetadata = null; //MediaItem.makeMetaDataMap(true, false, false, "UNKNOWN");
        for (MediaItem mi : itemsList) {
            if (StringUtils.equals(mi.getIdStr(), entryId)) {
                entryMetadata = mi.extractMetaDataMap();
            }
        }
        metadata.put(entryId, entryMetadata);
    }
    return metadata;
}
 
Example 45
Project: jmt   File: DefaultsEditor.java   Source Code and License 5 votes vote down vote up
/**
 * Adds an input field to choose a Drop rule.
 * @param text text to be shown on a label
 * @param property property to be changed in Defaults
 * @param cont container where input field must be added
 */
protected void addInputDropRule(String text, final String property, Container cont) {
	// Creates a Map with Drop rule names, then delegates addInputCombo to create
	// graphical components
	Map<String, String> dropRules = new LinkedHashMap<String, String>();
	dropRules.put(CommonConstants.FINITE_DROP, CommonConstants.FINITE_DROP);
	dropRules.put(CommonConstants.FINITE_BLOCK, CommonConstants.FINITE_BLOCK);
	dropRules.put(CommonConstants.FINITE_WAITING, CommonConstants.FINITE_WAITING);
	addInputCombo(text, property, cont, dropRules);
}
 
Example 46
Project: pandionj   File: ObjectModel.java   Source Code and License 5 votes vote down vote up
private void init(IJavaObject object) throws DebugException {
	fields = new ArrayList<IVariableModel<?>>();
	references = new LinkedHashMap<String, ReferenceModel>();
	refsOfSameType = new ArrayList<>();
	addFields(object);

	if(refsOfSameType.size() == 2) {
		leftField = refsOfSameType.get(0);
		rightField = refsOfSameType.get(1);
	}

	extension = ExtensionManager.getObjectExtension(this);
}
 
Example 47
Project: JavaGraph   File: EncodedExplorationMode.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String,Boolean> fixedValues() {
    Map<String,Boolean> result = new LinkedHashMap<>();
    result.put(POSITIVE, true);
    result.put(NEGATIVE, false);
    return result;
}
 
Example 48
Project: concurrentlimit-servlet-filter   File: ConcurrentLimitFilter.java   Source Code and License 5 votes vote down vote up
Limit(final long timeByIP, final int ipMaxSize, final int concurrentMax) {
	this.timeByIP = Math.max(timeByIP, 0);
	this.ipMaxSize = Math.max(ipMaxSize, 0);
	this.concurrentMax = Math.max(concurrentMax, 0);
	this.concurrent = (concurrentMax <= 0 ? null : new Semaphore(concurrentMax));
	this.seenIP = (((timeByIP <= 0) || (ipMaxSize <= 0)) ? null : new LinkedHashMap<String, Long>() {
		private static final long serialVersionUID = 42L;

		@Override
		protected boolean removeEldestEntry(java.util.Map.Entry<String, Long> eldest) {
			return (size() > ipMaxSize);
		}
	});
}
 
Example 49
Project: burstcoin   File: AT_Controller.java   Source Code and License 5 votes vote down vote up
public static LinkedHashMap< ByteBuffer , byte[] > getATsFromBlock( byte[] blockATs ) throws AT_Exception
{
	if ( blockATs.length > 0 )
	{
		if ( blockATs.length % (getCostOfOneAT() ) != 0 )
		{
			throw new AT_Exception("blockATs must be a multiple of cost of one AT ( " + getCostOfOneAT() +" )" );
		}
	}
	
	ByteBuffer b = ByteBuffer.wrap( blockATs );
	b.order( ByteOrder.LITTLE_ENDIAN );

	byte[] temp = new byte[ AT_Constants.AT_ID_SIZE ];

	LinkedHashMap< ByteBuffer , byte[] > ats = new LinkedHashMap<>();

	while ( b.position() < b.capacity() )
	{
		b.get( temp , 0 , temp.length );
		byte[] md5 = new byte[ 16 ];
		b.get( md5 , 0 , md5.length );
		ByteBuffer atId = ByteBuffer.allocate(AT_Constants.AT_ID_SIZE);
		atId.put(temp);
		atId.clear();
		if(ats.containsKey(atId)) {
			throw new AT_Exception("AT included in block multiple times");
		}
		ats.put( atId , md5 ); 
	}

	if ( b.position() != b.capacity() )
	{
		throw new AT_Exception("bytebuffer not matching");
	}

	return ats;
}
 
Example 50
Project: jmt   File: DefaultsEditor.java   Source Code and License 5 votes vote down vote up
/**
 * Adds an input field to choose a distribution.
 * @param text text to be shown on a label
 * @param property property to be changed in Defaults
 * @param cont container where input field must be added
 */
protected void addInputDistribution(String text, final String property, Container cont) {
	// Creates a Map with distribution names, then delegates addInputCombo to create
	// graphical components
	Map<String, String> distributions = new LinkedHashMap<String, String>();
	Distribution[] all = Distribution.findAll();
	for (Distribution element : all) {
		distributions.put(element.getClass().getName(), element.getName());
	}
	addInputCombo(text, property, cont, distributions);
}
 
Example 51
Project: kafka-0.11.0.0-src-with-comment   File: Protocol.java   Source Code and License 5 votes vote down vote up
private static void schemaToBnfHtml(Schema schema, StringBuilder b, int indentSize) {
    final String indentStr = indentString(indentSize);
    final Map<String, Type> subTypes = new LinkedHashMap<>();

    // Top level fields
    for (Field field: schema.fields()) {
        if (field.type instanceof ArrayOf) {
            b.append("[");
            b.append(field.name);
            b.append("] ");
            Type innerType = ((ArrayOf) field.type).type();
            if (!subTypes.containsKey(field.name))
                subTypes.put(field.name, innerType);
        } else {
            b.append(field.name);
            b.append(" ");
            if (!subTypes.containsKey(field.name))
                subTypes.put(field.name, field.type);
        }
    }
    b.append("\n");

    // Sub Types/Schemas
    for (Map.Entry<String, Type> entry: subTypes.entrySet()) {
        if (entry.getValue() instanceof Schema) {
            // Complex Schema Type
            b.append(indentStr);
            b.append(entry.getKey());
            b.append(" => ");
            schemaToBnfHtml((Schema) entry.getValue(), b, indentSize + 2);
        } else {
            // Standard Field Type
            b.append(indentStr);
            b.append(entry.getKey());
            b.append(" => ");
            b.append(entry.getValue());
            b.append("\n");
        }
    }
}
 
Example 52
Project: Hydrograph   File: ParameterFileManager.java   Source Code and License 5 votes vote down vote up
private Map<String, String> updatePropertyMap(Map<String, String> parameterMap){
	Map<String,String> map=new  LinkedHashMap<>(parameterMap);
	for(Entry<String, String> entry:parameterMap.entrySet()){
		if(StringUtils.contains(entry.getValue(), ESCAPE_CHAR)){
			map.put(entry.getKey(), StringUtils.replaceChars(entry.getValue(),ESCAPE_CHAR, BACKWARD_SLASH));
		}
	}
	return map;
}
 
Example 53
Project: Java-APIs   File: TermHints.java   Source Code and License 5 votes vote down vote up
protected TermHints(Element element) {
	logger.debug("Constructor - entry");
	termHintsMap = new LinkedHashMap<String, TermHint>();

	NodeList nodeList = element.getChildNodes();
	for (int n = 0; n < nodeList.getLength(); n++) {
		Node node = nodeList.item(n);
		if (node.getNodeType() == Node.ELEMENT_NODE) {
			Element childElement = (Element) node;

			if ("TERM_HINT".equals(childElement.getNodeName())) {
				addTermHint(new TermHint(childElement));
			} else {
				logger.trace("Unrecognized child node: '" + childElement.getNodeName() + "'");
			}
		} else if ((node.getNodeType() == Node.TEXT_NODE) && (node.getNodeValue() != null) && (node.getNodeValue().trim().length() > 0)) {
			logger.trace("Unexpected text node (" + this.getClass().getName() + "): '" + node.getNodeValue() + "'");
		}
	}
	NamedNodeMap namedNodeMap = element.getAttributes();
	if (namedNodeMap != null) {
		for (int a = 0; a < namedNodeMap.getLength(); a++) {
			Attr attributeNode = (Attr) namedNodeMap.item(a);
			logger.trace("Unrecognized attribute: '" + attributeNode.getName() + "'");
		}
	}

	logger.debug("Constructor - exit");
}
 
Example 54
Project: sunbird-lms-mw   File: BaseMetricsActor.java   Source Code and License 5 votes vote down vote up
protected List<Map<String, Object>> createBucketStrForWeek(String periodStr) {
  Map<String, Object> periodMap = getStartAndEndDateForWeek(periodStr);
  String date = (String) periodMap.get(startDate);
  List<Map<String, Object>> bucket = new ArrayList<>();
  Calendar cal = Calendar.getInstance();
  for (int day = 0; day < 5; day++) {
    Map<String, Object> bucketData = new LinkedHashMap<String, Object>();
    String keyName = "";
    String key = "";
    Date dateValue = null;
    try {
      keyName = formatKeyNameString(date);
      dateValue = new SimpleDateFormat("yyyy-MM-dd").parse(date);
      cal.setTime(dateValue);
      int week = cal.get(Calendar.WEEK_OF_YEAR);
      key = cal.get(Calendar.YEAR) + "" + week;
      date = keyName.toLowerCase().split("to")[1];
      date = date.trim();
      dateValue = new SimpleDateFormat("yyyy-MM-dd").parse(date);
      cal.setTime(dateValue);
      cal.add(Calendar.DATE, +1);
      date = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    } catch (ParseException e) {
      ProjectLogger.log("Error occured", e);
    }
    bucketData.put(KEY, key);
    bucketData.put(KEYNAME, keyName);
    bucketData.put(VALUE, 0);
    bucket.add(bucketData);
  }
  return bucket;
}
 
Example 55
Project: JRediClients   File: RedissonGeoTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testRadiusWithPositionOrderCount() {
    RGeo<String> geo = redisson.getGeo("test");
    geo.add(new GeoEntry(13.361389, 38.115556, "Palermo"), new GeoEntry(15.087269, 37.502669, "Catania"));

    Map<String, GeoPosition> descExpected = new LinkedHashMap<String, GeoPosition>();
    descExpected.put("Palermo", new GeoPosition(13.361389338970184, 38.115556395496299));
    assertThat(geo.radiusWithPosition(15, 37, 200, GeoUnit.KILOMETERS, GeoOrder.DESC, 1).entrySet()).containsExactlyElementsOf(descExpected.entrySet());
    
    Map<String, GeoPosition> ascExpected = new LinkedHashMap<String, GeoPosition>();
    ascExpected.put("Catania", new GeoPosition(15.087267458438873, 37.50266842333162));
    assertThat(geo.radiusWithPosition(15, 37, 200, GeoUnit.KILOMETERS, GeoOrder.ASC, 1).entrySet()).containsExactlyElementsOf(ascExpected.entrySet());
}
 
Example 56
Project: Hydrograph   File: ViewExecutionHistoryUtility.java   Source Code and License 5 votes vote down vote up
private ViewExecutionHistoryUtility() {
	trackingMap = new HashMap<String, ExecutionStatus>();
	trackingJobMap = new HashMap<String, List<Job>>();
	unusedCompOnCanvas = new LinkedHashMap<>();
	executionTrackingFields = new LinkedHashMap<>();
		selectedTrackingDetails = new LinkedList<>();
}
 
Example 57
Project: VoxelGamesLibv2   File: OrderedProperties.java   Source Code and License 5 votes vote down vote up
/**
 * Builds a new {@link OrderedProperties} instance.
 *
 * @return the new instance
 */
public OrderedProperties build() {
    Map<String, String> properties = (this.comparator != null) ?
            new TreeMap<String, String>(comparator) :
            new LinkedHashMap<String, String>();
    return new OrderedProperties(properties, suppressDate);
}
 
Example 58
Project: sstore-soft   File: MultimapBuilder.java   Source Code and License 5 votes vote down vote up
/**
 * Uses a {@link LinkedHashMap} to map keys to value collections, initialized to expect the
 * specified number of keys.
 *
 * <p>The collections returned by {@link Multimap#keySet()}, {@link Multimap#keys()}, and
 * {@link Multimap#asMap()} will iterate through the keys in the order that they were first added
 * to the multimap, save that if all values associated with a key are removed and then the key is
 * added back into the multimap, that key will come last in the key iteration order.
 */
public static MultimapBuilderWithKeys<Object> linkedHashKeys(final int expectedKeys) {
  checkNonnegative(expectedKeys, "expectedKeys");
  return new MultimapBuilderWithKeys<Object>() {
    @Override
    <K, V> Map<K, Collection<V>> createMap() {
      return new LinkedHashMap<K, Collection<V>>(expectedKeys);
    }
  };
}
 
Example 59
Project: openrouteservice   File: JSONObject.java   Source Code and License 5 votes vote down vote up
/**
 * Construct an empty JSONObject.
 */
public JSONObject(boolean ordered, int capacity) {
	if (ordered)
		this. map = new LinkedHashMap<>(capacity);
	else
		this.map = new HashMap<String, Object>(capacity);
}
 
Example 60
Project: GitHub   File: JavaApiConverterTest.java   Source Code and License 5 votes vote down vote up
@Test public void createOkResponseForCacheGet() throws Exception {
  final String statusLine = "HTTP/1.1 200 Fantastic";
  URI uri = new URI("http://foo/bar");
  Request request = new Request.Builder().url(uri.toURL()).build();
  CacheResponse cacheResponse = new CacheResponse() {
    @Override public Map<String, List<String>> getHeaders() throws IOException {
      Map<String, List<String>> headers = new LinkedHashMap<>();
      headers.put(null, Collections.singletonList(statusLine));
      headers.put("xyzzy", Arrays.asList("bar", "baz"));
      return headers;
    }

    @Override public InputStream getBody() throws IOException {
      return new ByteArrayInputStream("HelloWorld".getBytes(StandardCharsets.UTF_8));
    }
  };

  Response response = JavaApiConverter.createOkResponseForCacheGet(request, cacheResponse);
  Request cacheRequest = response.request();
  assertEquals(request.url(), cacheRequest.url());
  assertEquals(request.method(), cacheRequest.method());
  assertEquals(0, request.headers().size());

  assertEquals(Protocol.HTTP_1_1, response.protocol());
  assertEquals(200, response.code());
  assertEquals("Fantastic", response.message());
  Headers okResponseHeaders = response.headers();
  assertEquals("baz", okResponseHeaders.get("xyzzy"));
  assertEquals("HelloWorld", response.body().string());
  assertNull(response.handshake());
}