Java Code Examples for java.util.HashMap.get()

The following are Jave code examples for showing how to use get() of the java.util.HashMap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: labtablet   File: FavoriteDetailsActivity.java   View Source Code Vote up 6 votes
/**
 * Generates the necessary files for the forms upload to the SeaBioData repository
 */
private void dispatchSBDExport() throws IOException {


    SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);

    if (!settings.contains(Utils.TAG_SBD_USERNAME)) {
        Toast.makeText(this, getString(R.string.sbd_username_missing_export), Toast.LENGTH_SHORT).show();
        return;
    }

    HashMap<String, ArrayList<FormInstance>> groupedInstances = new HashMap<>();
    for (FormInstance fi : currentItem.getLinkedForms()) {
        if (groupedInstances.containsKey(fi.getParent())) {
            groupedInstances.get(fi.getParent()).add(fi);
            continue;
        }

        ArrayList<FormInstance> newInstances = new ArrayList<>();
        newInstances.add(fi);
        groupedInstances.put(fi.getParent(), newInstances);
    }


    for (String key : groupedInstances.keySet()) {
        FormExportItem exportItem = new FormExportItem(groupedInstances.get(key), settings.getString(Utils.TAG_SBD_USERNAME, ""));
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + key + "_" + new Date().toString() + ".json");

        if(file.createNewFile()) {
            OutputStream fo = new FileOutputStream(file);
            fo.write(new Gson().toJson(exportItem).getBytes());
            fo.close();
        }
    }

    Toast.makeText(getApplicationContext(), getString(R.string.sbd_dorms_exported_successfully), Toast.LENGTH_SHORT).show();
}
 
Example 2
Project: jbump   File: World.java   View Source Code Vote up 6 votes
private void addItemToCell(Item<E> item, float cx, float cy) {
  if (!rows.containsKey(cy)) {
    rows.put(cy, new HashMap<Float, Cell>());
  }
  HashMap<Float, Cell> row = rows.get(cy);
  if (!row.containsKey(cx)) {
    row.put(cx, new Cell());
  }
  Cell cell = row.get(cx);

  nonEmptyCells.put(cell, true);
  if (!cell.items.containsKey(item)) {
    cell.items.put(item, true);
    cell.itemCount = cell.itemCount + 1;
  }
}
 
Example 3
Project: underlx   File: Station.java   View Source Code Vote up 6 votes
public List<Station> getAlternatives(IAlternativeQualifier qualifier, int maxAmount) {
    final HashMap<Station, Double> stationCost = new HashMap<>();
    for (Stop source : getStops()) {
        BellmanFordShortestPath<Stop, Connection> bf = new BellmanFordShortestPath<Stop, Connection>(getNetwork(), source);
        for (Stop sink : getNetwork().vertexSet()) {
            if (sink != source && qualifier.acceptable(sink.getStation()) &&
                    bf.getCost(sink) < (stationCost.get(sink.getStation()) == null ? Double.MAX_VALUE : stationCost.get(sink.getStation()))) {
                stationCost.put(sink.getStation(), bf.getCost(sink));
            }
        }

    }
    List<Station> alternatives = new ArrayList<>(stationCost.keySet());
    Collections.sort(alternatives, new Comparator<Station>() {
        @Override
        public int compare(Station station, Station t1) {
            return stationCost.get(station).compareTo(stationCost.get(t1));
        }
    });
    return alternatives.subList(0, maxAmount > alternatives.size() ? alternatives.size() : maxAmount);
}
 
Example 4
Project: mazes_and_minotaurs   File: PlayerCharacter.java   View Source Code Vote up 6 votes
/**
 * Automatically converts the cash that a player character is holding
 */
public void validateMoney() {
    HashMap<Money, Integer> cash = getMoney();

    // Check for negative balances
    while (cash.get(Money.SILVER) < 0 && cash.get(Money.GOLD) - 1 >= 0) {
        System.out.println(cash);
        cash.put(Money.GOLD, cash.get(Money.GOLD) - 1);
        cash.put(Money.SILVER, cash.get(Money.SILVER) + 100);
    }
    while (cash.get(Money.COPPER) < 0 && cash.get(Money.SILVER) - 1 >= 0){
        System.out.println(cash);
        cash.put(Money.SILVER, cash.get(Money.SILVER) - 1);
        cash.put(Money.COPPER, cash.get(Money.COPPER) + 100);
    }

    // Check for overflow
    int tradedUpSilver = cash.get(Money.COPPER) / 100;
    cash.put(Money.COPPER, cash.get(Money.COPPER) % 100);
    cash.put(Money.SILVER, (cash.get(Money.SILVER) % 100) + tradedUpSilver);

    int tradedUpGold = cash.get(Money.SILVER) / 100;
    cash.put(Money.GOLD, cash.get(Money.GOLD) + tradedUpGold);
}
 
Example 5
Project: smaph   File: SmaphDebugger.java   View Source Code Vote up 6 votes
private JSONArray getEntityFeaturesJson(
		HashMap<String, List<Triple<Integer, HashMap<String, Double>, Boolean>>> source,
		String query, WikipediaInterface wikiApi) throws JSONException,
		IOException {
	JSONArray res = new JSONArray();
	if (source.containsKey(query))
		for (Triple<Integer, HashMap<String, Double>, Boolean> p : source
				.get(query)) {
			JSONObject pairJs = new JSONObject();
			res.put(pairJs);
			pairJs.put("wid", p.getLeft());
			pairJs.put("title", wikiApi.getTitlebyId(p.getLeft()));
			pairJs.put("url", widToUrl(p.getLeft(), wikiApi));
			JSONObject features = new JSONObject();
			pairJs.put("features", features);
			for (String ftrName : SmaphUtils.sorted(p.getMiddle().keySet()))
				features.put(ftrName, p.getMiddle().get(ftrName));
			pairJs.put("accepted", p.getRight());
		}
	return res;
}
 
Example 6
Project: HackerRank_solutions   File: Solution.java   View Source Code Vote up 6 votes
public static long numWays(int n, int [] coins, int coinNumber, HashMap<String, Long> cache) {
    /* Check our cache */
    String key = n + "," + coinNumber;
    if (cache.containsKey(key)) {
        return cache.get(key);
    }
    /* Base case */
    if (coinNumber == coins.length - 1) {
        if (n % coins[coinNumber] == 0) {
            cache.put(key, 1L);
            return 1;
        } else {
            cache.put(key, 0L);
            return 0;
        }
    }
    /* Recursive case */
    long ways = 0;
    for (int i = 0; i <= n; i += coins[coinNumber]) {
        ways += numWays(n - i, coins, coinNumber + 1, cache);
    }
    /* Cache and return solution */
    cache.put(key, ways);
    return ways;
}
 
Example 7
Project: Bewitchment   File: TileEntityWitchAltar.java   View Source Code Vote up 5 votes
private void refreshNature() {
	gain = 1;
	maxPower = 0;
	HashMap<Block, Integer> map = new HashMap<Block, Integer>();

	for (int i = -RADIUS; i <= RADIUS; i++) {
		for (int j = -RADIUS; j <= RADIUS; j++) {
			for (int k = -RADIUS; k <= RADIUS; k++) {
				BlockPos checking = getPos().add(i, j, k);
				int score = getPowerValue(checking);
				if (score > 0) {
					Block block = getWorld().getBlockState(checking).getBlock();
					int currentScore = 0;
					if (map.containsKey(block)) currentScore = map.get(block);
					if (currentScore < MAX_SCORE_PER_CATEGORY) map.put(block, currentScore + score);
				}
			}
		}
	}
	map.values().forEach(i -> maxPower += i);
	maxPower += (map.keySet().size() * 80); //Variety is the most important thing
	double multiplier = 1;
	boolean[] typesGain = new boolean[3]; //Types of modifiers. 0=skull, 1=torch/plate, 2=vase
	boolean[] typesMult = new boolean[3]; //Types of modifiers. 0=skull, 1=goblet, 2=plate
	for (int dx = -1; dx <= 1; dx++)
		for (int dz = -1; dz <= 1; dz++) {
			BlockPos ps = getPos().add(dx, 0, dz);
			if (getWorld().getBlockState(ps).getBlock().equals(ModBlocks.witch_altar) && !getWorld().getBlockState(ps).getValue(BlockWitchAltar.ALTAR_TYPE).equals(AltarMultiblockType.UNFORMED)) {
				multiplier += getMultiplier(ps.up(), typesMult);
				gain += getGain(ps.up(), typesGain);
			}
		}
	maxPower *= multiplier;
}
 
Example 8
Project: Helpers   File: ParserNode.java   View Source Code Vote up 5 votes
private BigDecimal eval(Interpreter interpreter, HashMap<String, BigDecimal> arguments, HashSet<String> reserved) throws SyntaxException, ArithmeticException, StackOverflowError {
    if (value == null) {
        BigDecimal l = left.eval(interpreter, arguments);
        BigDecimal r = right.eval(interpreter, arguments);
        switch (operator) {
            case '-': return l.subtract(r);
            case '+': return l.add(r);
            case '*': return l.multiply(r);
            case '%': return l.remainder(r);
            case '/': return l.divide(r, interpreter.getInternalRounding(), RoundingMode.HALF_UP);
            case '^': return l.pow(r.intValue());
        }
    }
    if (reserved.contains(value))
        throw new SyntaxException("Variable '" + value + "' is reserved");
    if(arguments.containsKey(value))
        return arguments.get(value);

    HashMap<String, BigDecimal> variables = interpreter.getVariables();
    if(variables.containsKey(value))
        return variables.get(value);
    if (value.contains("(")) {
        HashMap<String, Function> functions = interpreter.getFunctions();
        String name = value.split("\\(")[0];
        if(!functions.containsKey(name)) throw new SyntaxException("Function '" + name + "' not defined");
        String args = value.substring(name.length() + 1, value.length() - 1);
        return functions.get(name).eval(interpreter, arguments, args);
    }
    if(value.matches("[0-9]+(\\.[0-9]*)?"))
        return new BigDecimal(value);
    throw new SyntaxException("Variable '" + value + "' not defined");
}
 
Example 9
Project: xcc   File: LCSSA.java   View Source Code Vote up 5 votes
/**
 * Get the value to use within the specified basic block available values
 * are in phis.
 * @param domNode
 * @param inst
 * @param phis
 * @return
 */
private Value getValueForBlock(DomTreeNodeBase<BasicBlock> domNode,
		Instruction inst, HashMap<DomTreeNodeBase<BasicBlock>, Value> phis)
{
	if (domNode == null)
		return Value.UndefValue.get(inst.getType());

	if(phis.containsKey(domNode))
		return phis.get(domNode);

	DomTreeNodeBase<BasicBlock> idom = domNode.getIDom();

	if (!inLoop(idom.getBlock()))
	{
		Value val = getValueForBlock(idom, inst, phis);
		phis.put(domNode, val);
		return val;
	}

	BasicBlock bb = domNode.getBlock();
	PhiNode pn = new PhiNode(inst.getType(),
			predCache.getNumPreds(bb),
			inst.getName()+".lcssa",
			bb);
	phis.put(domNode, pn);
	predCache.getPreds(bb).forEach(pred->
	{
		pn.addIncoming(getValueForBlock(dt.getNode(pred), inst, phis), pred);
	});
	return pn;
}
 
Example 10
Project: org.openhab.binding.heos   File: HeosPlayer.java   View Source Code Vote up 5 votes
public void updatePlayerInfo(HashMap<String, String> values) {

        playerInfo = values;
        for (String key : values.keySet()) {
            if (key.equals("name")) {
                name = values.get(key);
            }
            if (key.equals("pid")) {
                pid = values.get(key);
            }
            if (key.equals("ip")) {
                ip = values.get(key);
            }
            if (key.equals("model")) {
                model = values.get(key);
            }
            if (key.equals("version")) {
                version = values.get(key);
            }
            if (key.equals("lineout")) {
                lineout = values.get(key);
            }
            if (key.equals("network")) {
                network = values.get(key);
            }
            if (key.equals("gid")) {
                gid = values.get(key);
            }
        }

    }
 
Example 11
Project: mutaflow   File: Parser.java   View Source Code Vote up 5 votes
/**
 * Reduces Map1 and its elements to the ones which did not occur in Map2.
 * 
 * @param Map1
 * @param Map2
 */
private static void makeDiffMap1(HashMap<String, HashSet<String>> Map1,
		HashMap<String, HashSet<String>> Map2) {
	Set<String> keySet1 = new HashSet(Map1.keySet()); // conversion is type
														// safe
	Set<String> keySet2 = new HashSet(Map2.keySet()); // conversion is type
														// safe
	for (String s : keySet1) {
		HashSet<String> values1 = Map1.get(s);
		HashSet<String> values2 = null;
		try {
			values2 = (HashSet<String>) Map2.get(s).clone(); // conversion
																// is type
																// safe
		} catch (NullPointerException e) {
			continue; // here a method was found which is new and did not
						// occur in map1
		}

		if ((values1 == null) || (values2 == null)) { // values should not
														// be both null
														// since only the
														// intersection is
														// considered
			throw new Error("Values are not both not null.");
		}
		values1.removeAll(values2);
		if (values1.isEmpty()) {
			Map1.remove(s);
		}
	}
}
 
Example 12
Project: OpenJSharp   File: XMBeanAttributes.java   View Source Code Vote up 5 votes
private ZoomedCell getZoomedCell(XMBean mbean, String attribute, Object value) {
    synchronized (viewersCache) {
        HashMap<String, ZoomedCell> viewers;
        if (viewersCache.containsKey(mbean)) {
            viewers = viewersCache.get(mbean);
        } else {
            viewers = new HashMap<String, ZoomedCell>();
        }
        ZoomedCell cell;
        if (viewers.containsKey(attribute)) {
            cell = viewers.get(attribute);
            cell.setValue(value);
            if (cell.isMaximized() && cell.getType() != XDataViewer.NUMERIC) {
                // Plotters are the only viewers with auto update capabilities.
                // Other viewers need to be updated manually.
                Component comp =
                    mbeansTab.getDataViewer().createAttributeViewer(
                        value, mbean, attribute, XMBeanAttributes.this);
                cell.init(cell.getMinRenderer(), comp, cell.getMinHeight());
                XDataViewer.registerForMouseEvent(comp, mouseListener);
            }
        } else {
            cell = new ZoomedCell(value);
            viewers.put(attribute, cell);
        }
        viewersCache.put(mbean, viewers);
        return cell;
    }
}
 
Example 13
Project: incubator-netbeans   File: JavadocCompletionQuery.java   View Source Code Vote up 5 votes
private DeclaredType getDeclaredType(TypeElement e, HashMap<? extends Element, ? extends TypeMirror> map, Types types) {
    List<? extends TypeParameterElement> tpes = e.getTypeParameters();
    TypeMirror[] targs = new TypeMirror[tpes.size()];
    int i = 0;
    for (Iterator<? extends TypeParameterElement> it = tpes.iterator(); it.hasNext();) {
        TypeParameterElement tpe = it.next();
        TypeMirror t = map.get(tpe);
        targs[i++] = t != null ? t : tpe.asType();
    }
    Element encl = e.getEnclosingElement();
    if ((encl.getKind().isClass() || encl.getKind().isInterface()) && !((TypeElement)encl).getTypeParameters().isEmpty())
            return types.getDeclaredType(getDeclaredType((TypeElement)encl, map, types), e, targs);
    return types.getDeclaredType(e, targs);
}
 
Example 14
Project: openjdk-jdk10   File: MessageContextFactory.java   View Source Code Vote up 5 votes
static Map<String, List<String>> toMap(MimeHeaders headers) {
    HashMap<String, List<String>> map = new HashMap<String, List<String>>();
    for (Iterator<MimeHeader> i = headers.getAllHeaders(); i.hasNext();) {
        MimeHeader mh = i.next();
        List<String> values = map.get(mh.getName());
        if (values == null) {
            values = new ArrayList<String>();
            map.put(mh.getName(), values);
        }
        values.add(mh.getValue());
    }
    return map;
}
 
Example 15
Project: GitHub   File: SimpleMonthView.java   View Source Code Vote up 4 votes
/**
     * 设置传递进来的参数
     *
     * @param params
     */
    public void setMonthParams(HashMap<String, Object> params) {
        if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) {
            throw new InvalidParameterException("You must specify month and year for this view");
        }
        setTag(params);

//        if (params.containsKey(VIEW_PARAMS_HEIGHT)) {
//            mRowHeight = (int) params.get(VIEW_PARAMS_HEIGHT);
//            if (mRowHeight < MIN_HEIGHT) {
//                mRowHeight = MIN_HEIGHT;
//            }
//        }

        if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DATE)) {
            mStartDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_BEGIN_DATE);
        }
        if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DATE)) {
            mEndDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_LAST_DATE);
        }

        if (params.containsKey("mNearestDay")) {
            mNearestDay = (SimpleMonthAdapter.CalendarDay) params.get("mNearestDay");
        }

        mMonth = (int) params.get(VIEW_PARAMS_MONTH);
        mYear = (int) params.get(VIEW_PARAMS_YEAR);

        mHasToday = false;
        mToday = -1;

        mCalendar.set(Calendar.MONTH, mMonth);
        mCalendar.set(Calendar.YEAR, mYear);
        mCalendar.set(Calendar.DAY_OF_MONTH, 1);
        mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK);

        if (params.containsKey(VIEW_PARAMS_WEEK_START)) {
            mWeekStart = (int) params.get(VIEW_PARAMS_WEEK_START);
        } else {
            mWeekStart = mCalendar.getFirstDayOfWeek();
        }

        mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear);
        for (int i = 0; i < mNumCells; i++) {
            final int day = i + 1;
            if (sameDay(day, today)) {
                mHasToday = true;
                mToday = day;
            }
        }

        mNumRows = calculateNumRows();
    }
 
Example 16
Project: ctsms   File: EcrfFieldRowProcessor.java   View Source Code Vote up 4 votes
@Override
protected int processRow(String[] values, long rowNumber) throws Throwable {
	String probandGroupToken = getEcrfProbandGroup(values);
	Long ecrfPosition = Long.parseLong(getEcrfPosition(values));
	ECRF ecrf = getEcrf(probandGroupToken, ecrfPosition);
	Long position = Long.parseLong(getPosition(values));
	String section = getSection(values);
	ECRFField ecrfField = null;
	if (ecrf != null) {
		try {
			ecrfField = eCRFFieldDao.findByEcrfSectionPosition(ecrf.getId(), section, position).iterator().next();
		} catch (NoSuchElementException e) {
		}
	}
	String inputFieldName = getInputFieldName(values);
	ECRFFieldInVO ecrfFieldIn = new ECRFFieldInVO();
	ecrfFieldIn.setId(ecrfField != null ? ecrfField.getId() : null);
	ecrfFieldIn.setVersion(ecrfField != null ? ecrfField.getVersion() : 0l);
	ecrfFieldIn.setTrialId(context.getEntityId());
	ecrfFieldIn.setEcrfId(ecrf != null ? ecrf.getId() : null);
	ecrfFieldIn.setSection(section);
	ecrfFieldIn.setPosition(position);
	ecrfFieldIn.setExternalId(getExternalId(values));
	ecrfFieldIn.setFieldId(getInputFieldId(inputFieldName));
	ecrfFieldIn.setComment(getComment(values));
	ecrfFieldIn.setSeries(Boolean.parseBoolean(getSeries(values)));
	ecrfFieldIn.setOptional(Boolean.parseBoolean(getOptional(values)));
	ecrfFieldIn.setDisabled(Boolean.parseBoolean(getDisabled(values)));
	ecrfFieldIn.setAuditTrail(Boolean.parseBoolean(getAuditTrail(values)));
	ecrfFieldIn.setReasonForChangeRequired(Boolean.parseBoolean(getReasonForChangeRequired(values)));
	String jsVariableName = getJsVariableName(values);
	boolean clearJs = CommonUtil.isEmptyString(jsVariableName)
			|| (!CommonUtil.isEmptyString(getCommentChar()) && !CommonUtil.isEmptyString(jsVariableName) && jsVariableName.startsWith(getCommentChar()));
	ecrfFieldIn.setJsVariableName(clearJs ? null : getJsVariableName(values));
	ecrfFieldIn.setJsValueExpression(clearJs ? null : getJsValueExpression(values));
	ecrfFieldIn.setJsOutputExpression(clearJs ? null : getJsOutputExpression(values));

	Set<ECRFFieldInVO> ecrfFields;
	HashMap<Long, Set<ECRFFieldInVO>> positionMap;
	if (ecrfFieldMap.containsKey(probandGroupToken)) {
		positionMap = ecrfFieldMap.get(probandGroupToken);
	} else {
		positionMap = new HashMap<Long, Set<ECRFFieldInVO>>();
		ecrfFieldMap.put(probandGroupToken, positionMap);
	}
	if (positionMap.containsKey(ecrfPosition)) {
		ecrfFields = positionMap.get(ecrfPosition);
	} else {
		ecrfFields = new LinkedHashSet<ECRFFieldInVO>();
		positionMap.put(ecrfPosition, ecrfFields);
	}
	String label = "ecrf for proband group " + (CommonUtil.isEmptyString(probandGroupToken) ? "<no group>" : probandGroupToken) + ", position " + ecrfPosition
			+ ": field section " + section + ", position " + position + ", field '" + inputFieldName + "'";
	if (ecrfFields.add(ecrfFieldIn)) {
		jobOutput.println(label + " added");
		return 1;
	} else {
		jobOutput.println(label + " SKIPPED");
		return 0;
	}
}
 
Example 17
Project: OpenJSharp   File: XMBeanAttributes.java   View Source Code Vote up 4 votes
protected void addTableData(DefaultTableModel tableModel,
                            XMBean mbean,
                            MBeanAttributeInfo[] attributesInfo,
                            HashMap<String, Object> attributes,
                            HashMap<String, Object> unavailableAttributes,
                            HashMap<String, Object> viewableAttributes) {

    Object rowData[] = new Object[2];
    int col1Width = 0;
    int col2Width = 0;
    for (int i = 0; i < attributesInfo.length; i++) {
        rowData[0] = (attributesInfo[i].getName());
        if (unavailableAttributes.containsKey(rowData[0])) {
            rowData[1] = Messages.UNAVAILABLE;
        } else if (viewableAttributes.containsKey(rowData[0])) {
            rowData[1] = viewableAttributes.get(rowData[0]);
            if (!attributesInfo[i].isWritable() ||
                !Utils.isEditableType(attributesInfo[i].getType())) {
                rowData[1] = getZoomedCell(mbean, (String) rowData[0], rowData[1]);
            }
        } else {
            rowData[1] = attributes.get(rowData[0]);
        }

        tableModel.addRow(rowData);

        //Update column width
        //
        String str = null;
        if(rowData[0] != null) {
            str = rowData[0].toString();
            if(str.length() > col1Width)
                col1Width = str.length();
        }
        if(rowData[1] != null) {
            str = rowData[1].toString();
            if(str.length() > col2Width)
                col2Width = str.length();
        }
    }
    updateColumnWidth(col1Width, col2Width);
}
 
Example 18
Project: OpenDiabetes   File: TestScripts.java   View Source Code Vote up 4 votes
static void test(String url, String user, String password, String db,
                 String[] scriptList, String[] idList,
                 Boolean[] persistList) {

    if (scriptList.length < 1) {
        System.err.println("Nothing to do.  No scripts specified.");

        return;
    }

    HashMap connMap = new HashMap();

    if (db != null) {
        deleteDatabase(db);
    }

    try {
        DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver());

        Connection cConnection = null;
        String     id;

        for (int i = 0; i < scriptList.length; i++) {
            id = idList[i];

            System.out.println("ID: " + id);

            cConnection = ((id == null) ? null
                                        : (Connection) connMap.get(id));

            if (cConnection == null) {
                System.out.println("Getting NEW conn");

                cConnection = DriverManager.getConnection(url, user,
                        password);

                if (id != null) {

                    // If new named conn., then store it.
                    connMap.put(id, cConnection);
                    System.out.println("Storing NEW conn");
                }
            }

            testScript(cConnection, scriptList[i]);

            if (persistList[i] == null ||!persistList[i].booleanValue()) {
                if (id != null) {
                    connMap.remove(id);
                    System.out.println("Removed conn");
                }

                cConnection.close();
                System.out.println("Closed conn");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        print("TestSelf init error: " + e.getMessage());
    }
}
 
Example 19
Project: OpenVSP3Plugin   File: OpenVSP3Plugin.java   View Source Code Vote up 4 votes
void readCompGeomMaps(Map<String, String> compGeomMap, Map<String, String> tagCompGeomMap) throws Exception {
	LOG.trace("readCompGeomMaps()");
	// Read the CompGeom file and store data in map parameters if not null
	HashMap<String, Integer> nameCount = new HashMap<>();
	String line;
	try (BufferedReader br = new BufferedReader(new FileReader(tempDir + "\\OpenVSP3PluginCompGeom.csv"))) {
		boolean firstTable = true;
		br.readLine(); // read headers
		while ((line = br.readLine()) != null) {
			String[] columns = line.split(CSVSPLITSTRING);
			if (columns.length < 3) {
				firstTable = false;
				br.readLine(); // read 2nd headers after blank line
			} else if (firstTable) { // old table
				if (compGeomMap != null) {
					if (columns.length != 5) {
						throw new Exception(String.format("CompGeom table has %d columns not 5/n%s", columns.length, line));
					}
					// Keep names unique by adding a count
					String name = columns[0];
					if (!name.equals("Totals")) {
						if (nameCount.containsKey(name)) nameCount.put(name, nameCount.get(name) + 1);
						else nameCount.put(name, 0);
						name += nameCount.get(name);
				}
					for (int i = 1; i < 5; i++) {
						compGeomMap.put(String.format("%s:%s:%s", COMPGEOM, name, COMPGEOMVALUES[i - 1]), columns[i]);
					}
				}
			} else { // tag table
				if (tagCompGeomMap != null) {
					StringBuilder group = new StringBuilder(columns[0]);
					for (int i = 1; i < columns.length - 2; i++) {
						group.append("_");
						group.append(columns[i]);
					}
					for (int i = 0; i < 2; i++) {
						tagCompGeomMap.put(String.format("%s:%s:%s", COMPGEOM2, group.toString(), COMPGEOMVALUES2[i]), columns[columns.length - 2 + i]);
					}
				}
			}
		}
	}
}
 
Example 20
Project: ui-atoms-android   File: HashMapEx.java   View Source Code Vote up 4 votes
public static <TKey,TR> TR getOrDefaultValue(HashMap<TKey, TR> members, TKey key, TR o) {
    TR r = members.get(key);
    if(r==null)
        return o;
    return r;
}