List of usage examples for java.util ArrayList contains
public boolean contains(Object o)
From source file:de.andreasschoknecht.LS3.DocumentCollection.java
/** * Delete a model from the Term-Document Matrix search structure. * * @param modelName The model name of the model to be removed. *//*from w w w .j a va 2 s. c om*/ public void deleteModel(String modelName) { // Make sure file name is correct if (!modelName.endsWith(".pnml")) modelName = modelName + ".pnml"; // Delete column from TD Matrix and set correct number of columns int deletionIndex = 0; for (int i = 0, l = fileList.length; i < l; i++) { if (fileList[i].equals(modelName)) { tdMatrix.deleteColumn(i); deletionIndex = i; } } // Delete model name from fileList (update to new file list). String[] newFileList = new String[fileList.length - 1]; int counter = 0; for (int i = 0, l = fileList.length; i < l; i++) { if (i != deletionIndex) { newFileList[counter] = fileList[i]; counter++; } } setFileList(newFileList); // Delete LS3Document representation of file "modelName" (update to new ArrayList of LS3Documents). for (int i = 0, l = ls3Documents.size(); i < l; i++) { if (ls3Documents.get(i).getPNMLPath().endsWith(modelName)) { ls3Documents.remove(i); i = l; } } // Delete term rows that only contain values 0.0. I.e. delete unnecessary terms. ArrayList<Integer> termDeletionIndices = new ArrayList<Integer>(); boolean delete = true; double[][] matrix = tdMatrix.getMatrix(); for (int i = 0, k = tdMatrix.getRowNumber(); i < k; i++) { for (int j = 0, l = tdMatrix.getColumnNumber(); j < l; j++) { if (matrix[i][j] != 0.0) { delete = false; j = l; } } if (delete == true) termDeletionIndices.add(i); else delete = true; } int deletionCounter = 0; for (int index : termDeletionIndices) { tdMatrix.deleteRow(index - deletionCounter); deletionCounter++; } // Update term list of document collection. deletionCounter = 0; LinkedHashSet<String> newTermList = new LinkedHashSet<String>(); for (String term : termCollection) { if (!termDeletionIndices.contains(deletionCounter)) newTermList.add(term); deletionCounter++; } setTermCollection(newTermList); // Update term list of TDMatrix object tdMatrix.setTermArray(termCollection.toArray(new String[0])); }
From source file:beast.evolution.tree.partitioned.IndividualSEIR.java
public double evaluateLogP() { // try { // PrintStream firstSteam = new PrintStream("tt.nex"); ////from w w w .j a v a 2 s. c o m // PartitionedTreeLogger.debugLog(tree, 0, false, firstSteam); // } catch (FileNotFoundException e){ // e.printStackTrace(); // } double transLogProb = 0; double rate = baseTransmissionRate.getValue(); ArrayList<ClinicalCase> previouslyInfectious = new ArrayList<>(); double currentEventTime; boolean first = true; for (TreeEvent event : sortedTreeEvents) { currentEventTime = event.getTime(); ClinicalCase thisCase = event.getCase(); if (event.getType() == EventType.INFECTION) { if (first) { // index infection if (indexCasePrior != null) { transLogProb += Math.log(indexCasePrior.get(thisCase)); } if (initialInfectionTimePrior != null) { transLogProb += initialInfectionTimePrior.logDensity(currentEventTime); } if (!hasLatentPeriods) { previouslyInfectious.add(thisCase); } first = false; } else { ClinicalCase infector = event.getInfector(); if (thisCase.wasEverInfected()) { if (previouslyInfectious.contains(thisCase)) { return Double.NEGATIVE_INFINITY; } if (event.getTime() > thisCase.getEndTime()) { return Double.NEGATIVE_INFINITY; } if (infector.getEndTime() < event.getTime()) { return Double.NEGATIVE_INFINITY; } if (getInfectiousTime(infector) > event.getTime()) { return Double.NEGATIVE_INFINITY; } if (!previouslyInfectious.contains(infector)) { throw new RuntimeException("Infector not previously infected"); } } // no other previously infectious case has infected this case... for (ClinicalCase nonInfector : previouslyInfectious) { double timeDuringWhichNoInfection; if (nonInfector.getEndTime() < event.getTime()) { timeDuringWhichNoInfection = nonInfector.getEndTime() - getInfectiousTime(nonInfector); } else { timeDuringWhichNoInfection = event.getTime() - getInfectiousTime(nonInfector); } if (timeDuringWhichNoInfection < 0) { throw new RuntimeException("negative time"); } double transRate = rate; if (hasGeography) { try { transRate *= kernel.getValue((GeographicallyLocatedClinicalCase) thisCase, (GeographicallyLocatedClinicalCase) nonInfector); } catch (FunctionEvaluationException e) { e.printStackTrace(); } } transLogProb += -transRate * timeDuringWhichNoInfection; } // ...until the end if (thisCase.wasEverInfected()) { double transRate = rate; if (hasGeography) { try { transRate *= kernel.getValue((GeographicallyLocatedClinicalCase) thisCase, (GeographicallyLocatedClinicalCase) infector); } catch (FunctionEvaluationException e) { e.printStackTrace(); } } transLogProb += Math.log(transRate); } if (!hasLatentPeriods) { previouslyInfectious.add(thisCase); } } } else if (event.getType() == EventType.INFECTIOUSNESS) { if (event.getTime() < Double.POSITIVE_INFINITY) { if (event.getTime() > event.getCase().getEndTime()) { return Double.NEGATIVE_INFINITY; } if (first) { throw new RuntimeException("First event is not an infection"); } previouslyInfectious.add(thisCase); } } } double periodsLogProb = 0; for (DurationDistribution category : infectiousCategories) { if (category.hasProbability()) { List<ClinicalCase> relevantCases = new ArrayList<>(); for (ClinicalCase aCase : outbreak.getCases()) { if (getInfectiousCategory(aCase) == category) { relevantCases.add(aCase); } } Double[] infectiousPeriods = new Double[relevantCases.size()]; for (int i = 0; i < infectiousPeriods.length; i++) { infectiousPeriods[i] = relevantCases.get(i).getEndTime() - getInfectiousTime(relevantCases.get(i)); } RealParameter collectionOfValues = new RealParameter(infectiousPeriods); periodsLogProb += category.getLogProbability(collectionOfValues); } } // just reject states where these round to +INF if (transLogProb == Double.POSITIVE_INFINITY) { System.out.println("TransLogProb +INF"); return Double.NEGATIVE_INFINITY; } if (periodsLogProb == Double.POSITIVE_INFINITY) { System.out.println("PeriodsLogProb +INF"); return Double.NEGATIVE_INFINITY; } logP = periodsLogProb + transLogProb; return logP; }
From source file:de.tuebingen.uni.sfs.germanet.api.GermaNet.java
/** * Returns a <code>List</code> of all <code>Synsets</code> in which * <code>orthForm</code> occurs as main orthographical form in one of its * <code>LexUnits</code> -- in case <code>considerAllOrthForms</code> is * true. Else returns a <code>List</code> of all <code>Synsets</code> in * which <code>orthForm</code> occurs as main orthographical form, as * orthographical variant, as old orthographical form, or as old * orthographic variant in one of its <code>LexUnits</code> -- in case * <code>considerAllOrthForms</code> is false. It uses the * <code>ignoreCase</code> flag as set in the constructor. * @param orthForm the <code>orthForm</code> to search for * @param considerMainOrthFormOnly considering main orthographical form only * (<code>true</code>) or all variants (<code>false</code>) * @return a <code>List</code> of all <code>Synsets</code> containing * orthForm. If no <code>Synsets</code> were found, this is a * <code>List</code> containing no <code>Synsets</code> */// w w w. j a va 2s . c o m public List<Synset> getSynsets(String orthForm, boolean considerMainOrthFormOnly) { ArrayList<Synset> rval = new ArrayList<Synset>(); HashMap<String, ArrayList<LexUnit>> map; List<LexUnit> tmpList; String mapForm = orthForm; if (ignoreCase) { mapForm = orthForm.toLowerCase(); } for (WordCategory wc : WordCategory.values()) { if (considerMainOrthFormOnly) { map = wordCategoryMap.get(wc); } else { map = wordCategoryMapAllOrthForms.get(wc); } tmpList = map.get(mapForm); if (tmpList != null) { for (LexUnit lu : tmpList) { if (!rval.contains(lu.getSynset())) { rval.add(lu.getSynset()); } } } } rval.trimToSize(); return rval; }
From source file:edu.cornell.mannlib.vitro.webapp.utils.jena.JenaIngestUtils.java
public void doPermanentURI(String oldModel, String newModel, String oldNamespace, String newNamespace, ModelMaker maker, VitroRequest vreq) { if (newNamespace.isEmpty()) { throw new RuntimeException("new namespace must be specified"); }/*from w w w. ja va 2 s .c o m*/ WebappDaoFactory wdf = vreq.getUnfilteredWebappDaoFactory(); Model m = maker.getModel(oldModel); Model saveModel = maker.getModel(newModel); Model tempModel = ModelFactory.createDefaultModel(); ResIterator rsItr = null; ArrayList<String> urlCheck = new ArrayList<String>(); boolean urlFound = false; if (!oldModel.equals(newModel)) { StmtIterator stmtItr = m.listStatements(); while (stmtItr.hasNext()) { Statement stmt = stmtItr.nextStatement(); tempModel.add(stmt); } rsItr = tempModel.listResourcesWithProperty((Property) null); } else { rsItr = m.listResourcesWithProperty((Property) null); } String uri = null; while (rsItr.hasNext()) { Resource res = rsItr.next(); if (res.getNameSpace().equals(oldNamespace)) { do { uri = getUnusedURI(newNamespace, wdf); if (!urlCheck.contains(uri)) { urlCheck.add(uri); urlFound = true; } } while (!urlFound); urlFound = false; ResourceUtils.renameResource(res, uri); } } boolean statementDone = false; if (!oldModel.equals(newModel)) { StmtIterator stmtItr = tempModel.listStatements(); while (stmtItr.hasNext()) { statementDone = false; Statement stmt = stmtItr.nextStatement(); Resource sRes = stmt.getSubject(); Resource oRes = null; if (sRes.getNameSpace().equals(newNamespace)) { saveModel.add(stmt); statementDone = true; } try { oRes = (Resource) stmt.getObject(); if (oRes.getNameSpace().equals(newNamespace) && !statementDone) { saveModel.add(stmt); statementDone = true; } } catch (Exception e) { continue; } } } }
From source file:com.clust4j.algo.HDBSCAN.java
protected static int[] doLabeling(ArrayList<CompQuadTup<Integer, Integer, Double, Integer>> tree, ArrayList<Integer> clusters, TreeMap<Integer, Integer> clusterMap) { CompQuadTup<Integer, Integer, Double, Integer> quad; int rootCluster, parent, child, n = tree.size(), cluster, i; int[] resultArr, parentArr = new int[n], childArr = new int[n]; UnifiedFinder unionFind;//from www. j ava2s . c o m // [parent, child, lambda, size] int maxParent = Integer.MIN_VALUE; int minParent = Integer.MAX_VALUE; for (i = 0; i < n; i++) { quad = tree.get(i); parentArr[i] = quad.getFirst(); childArr[i] = quad.getSecond(); if (quad.getFirst() < minParent) minParent = quad.getFirst(); if (quad.getFirst() > maxParent) maxParent = quad.getFirst(); } rootCluster = minParent; resultArr = new int[rootCluster]; unionFind = new TreeUnionFind(maxParent + 1); for (i = 0; i < n; i++) { child = childArr[i]; parent = parentArr[i]; if (!clusters.contains(child)) unionFind.union(parent, child); } for (i = 0; i < rootCluster; i++) { cluster = unionFind.find(i); if (cluster <= rootCluster) resultArr[i] = NOISE_CLASS; else resultArr[i] = clusterMap.get(cluster); } return resultArr; }
From source file:br.org.indt.ndg.server.survey.SurveyHandlerBean.java
public QueryInputOutputVO getAllImeisBySurvey(String surveyId, QueryInputOutputVO queryIOVO) throws MSMApplicationException { if (queryIOVO == null) { queryIOVO = new QueryInputOutputVO(); }//from w ww . ja v a2s . c o m String sQuery = "from Transactionlog where transactionType = "; sQuery += "\'"; sQuery += TransactionLogVO.TYPE_SEND_SURVEY; sQuery += "\'"; sQuery += " and survey.idSurvey = :surveyId"; if ((queryIOVO.getFilterText() != null) && (queryIOVO.getFilterFields() != null)) { sQuery += SqlUtil.getFilterCondition(queryIOVO.getFilterText(), queryIOVO.getFilterFields()); } if ((queryIOVO.getSortField() != null) && (queryIOVO.getIsDescending() != null)) { sQuery += SqlUtil.getSortCondition(queryIOVO.getSortField(), queryIOVO.getIsDescending()); } Query q = manager.createQuery(sQuery); q.setParameter("surveyId", surveyId); if ((queryIOVO.getPageNumber() != null) && (queryIOVO.getRecordsPerPage() != null)) { q.setFirstResult((queryIOVO.getPageNumber() - 1) * queryIOVO.getRecordsPerPage()); q.setMaxResults(queryIOVO.getRecordsPerPage()); } ArrayList<Object> ret = new ArrayList<Object>(); ArrayList<Transactionlog> al = (ArrayList<Transactionlog>) q.getResultList(); Iterator<Transactionlog> it = al.iterator(); ArrayList<String> imeiIdListAux = new ArrayList<String>(); while (it.hasNext()) { Transactionlog surveyTransactionLog = (Transactionlog) it.next(); if (imeiIdListAux.contains(surveyTransactionLog.getImei().getImei())) { continue; } imeiIdListAux.add(surveyTransactionLog.getImei().getImei()); Imei imei = null; if (surveyTransactionLog.getImei() != null) { imei = manager.find(Imei.class, surveyTransactionLog.getImei().getImei()); } if (imei != null) { ImeiVO vo = new ImeiVO(); vo.setImei(imei.getImei()); vo.setMsisdn(imei.getMsisdn()); vo.setUserName(imei.getUser().getUsername()); NdgDevice device = imei.getDevice(); DeviceVO devVO = new DeviceVO(); devVO.setIdDevice(device.getIdDevice()); devVO.setDeviceModel(device.getDeviceModel()); vo.setDevice(devVO); vo.setRealImei(imei.getRealImei()); if (!surveyTransactionLog.getTransactionStatus().equals(TransactionLogVO.STATUS_SUCCESS)) { vo.setStatus(TransactionLogVO.STATUS_PENDING); } else { vo.setStatus(surveyTransactionLog.getTransactionStatus()); } StringBuilder builder = new StringBuilder(); builder.append("from Result where idSurvey = '"); builder.append(surveyId); builder.append("' and imei = '"); builder.append(vo.getImei()); builder.append("'"); Query query = manager.createQuery(builder.toString()); vo.setQtdeResults(query.getResultList().size()); ret.add(vo); } } queryIOVO.setRecordCount(ret.size()); queryIOVO.setQueryResult(ret); return queryIOVO; }
From source file:com.hichinaschool.flashcards.async.Connection.java
private Payload doInBackgroundUpgradeDecks(Payload data) { // Enable http request canceller mCancelCallback = new CancelCallback(); String path = (String) data.data[0]; File ankiDir = new File(path); if (!ankiDir.isDirectory()) { data.success = false;// ww w. j a va 2 s. c om data.data = new Object[] { "wrong anki directory" }; return data; } // step 1: gather all .anki files into a zip, without media. // we must store them as 1.anki, 2.anki and provide a map so we don't run into // encoding issues with the zip file. File[] fileList = ankiDir.listFiles(new OldAnkiDeckFilter()); List<String> corruptFiles = new ArrayList<String>(); JSONObject map = new JSONObject(); byte[] buf = new byte[1024]; String zipFilename = path + "/upload.zip"; String colFilename = path + AnkiDroidApp.COLLECTION_PATH; try { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename)); int n = 1; for (File f : fileList) { String deckPath = f.getAbsolutePath(); // set journal mode to delete try { AnkiDb d = AnkiDatabaseManager.getDatabase(deckPath); } catch (SQLiteDatabaseCorruptException e) { // ignore invalid .anki files corruptFiles.add(f.getName()); continue; } finally { AnkiDatabaseManager.closeDatabase(deckPath); } // zip file String tmpName = n + ".anki"; FileInputStream in = new FileInputStream(deckPath); ZipEntry ze = new ZipEntry(tmpName); zos.putNextEntry(ze); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); map.put(tmpName, f.getName()); n++; } // if all .anki files were found corrupted, abort if (fileList.length == corruptFiles.size()) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } ZipEntry ze = new ZipEntry("map.json"); zos.putNextEntry(ze); InputStream in = new ByteArrayInputStream(Utils.jsonToString(map).getBytes("UTF-8")); int len; while ((len = in.read(buf)) >= 0) { zos.write(buf, 0, len); } zos.closeEntry(); zos.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } File zipFile = new File(zipFilename); // step 1.1: if it's over 50MB compressed, it must be upgraded by the user if (zipFile.length() > 50 * 1024 * 1024) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_exceeds) }; return data; } // step 2: upload zip file to upgrade service and get token BasicHttpSyncer h = new BasicHttpSyncer(null, null); // note: server doesn't expect it to be gzip compressed, because the zip file is compressed // enable cancelling publishProgress(R.string.upgrade_decks_upload, null, true); try { HttpResponse resp = h.req("upgrade/upload", new FileInputStream(zipFile), 0, false, null, mCancelCallback); if (resp == null && !isCancelled()) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } String result; String key = null; if (!isCancelled()) { result = h.stream2String(resp.getEntity().getContent()); if (result != null && result.startsWith("ok:")) { key = result.split(":")[1]; } else { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } } while (!isCancelled()) { result = h.stream2String(h.req("upgrade/status?key=" + key).getEntity().getContent()); if (result.equals("error")) { data.success = false; data.data = new Object[] { "error" }; return data; } else if (result.startsWith("waiting:")) { publishProgress(R.string.upgrade_decks_upload, result.split(":")[1]); } else if (result.equals("upgrading")) { publishProgress(new Object[] { R.string.upgrade_decks_upgrade_started }); } else if (result.equals("ready")) { break; } else { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } Thread.sleep(1000); } // step 4: fetch upgraded file. this will return the .anki2 file directly, with // gzip compression if the client says it can handle it if (!isCancelled()) { publishProgress(new Object[] { R.string.upgrade_decks_downloading }); resp = h.req("upgrade/download?key=" + key, null, 6, true, null, mCancelCallback); // uploads/downloads have finished so disable cancelling } publishProgress(R.string.upgrade_decks_downloading, null, false); if (isCancelled()) { return null; } if (resp == null) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) }; return data; } // step 5: check the received file is valid InputStream cont = resp.getEntity().getContent(); if (!h.writeToFile(cont, colFilename)) { data.success = false; data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_sdcard, new File(colFilename).length() / 1048576 + 1) }; (new File(colFilename)).delete(); return data; } // check the received file is ok publishProgress(new Object[] { R.string.sync_check_download_file }); publishProgress(R.string.sync_check_download_file); try { AnkiDb d = AnkiDatabaseManager.getDatabase(colFilename); if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) { data.success = false; data.data = new Object[] { sContext.getResources() }; return data; } } finally { AnkiDatabaseManager.closeDatabase(colFilename); } Collection col = AnkiDroidApp.openCollection(colFilename); ArrayList<String> decks = col.getDecks().allNames(false); ArrayList<String> failed = new ArrayList<String>(); ArrayList<File> mediaDirs = new ArrayList<File>(); for (File f : fileList) { String name = f.getName().replaceFirst("\\.anki$", ""); if (!decks.contains(name)) { failed.add(name); } else { mediaDirs.add(new File(f.getAbsolutePath().replaceFirst("\\.anki$", ".media"))); } } File newMediaDir = new File(col.getMedia().getDir()); // step 6. move media files to new media directory publishProgress(new Object[] { R.string.upgrade_decks_media }); ArrayList<String> failedMedia = new ArrayList<String>(); File curMediaDir = null; for (File mediaDir : mediaDirs) { curMediaDir = mediaDir; // Check if media directory exists and is local if (!curMediaDir.exists() || !curMediaDir.isDirectory()) { // If not try finding it in dropbox 1.2.x curMediaDir = new File(AnkiDroidApp.getDropboxDir(), mediaDir.getName()); if (!curMediaDir.exists() || !curMediaDir.isDirectory()) { // No media for this deck continue; } } // Found media dir, copy files for (File m : curMediaDir.listFiles()) { try { Utils.copyFile(m, new File(newMediaDir, m.getName())); } catch (IOException e) { failedMedia.add(curMediaDir.getName().replaceFirst("\\.media$", ".anki")); break; } } } data.data = new Object[] { failed, failedMedia, newMediaDir.getAbsolutePath() }; data.success = true; return data; } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IllegalStateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { (new File(zipFilename)).delete(); } }
From source file:com.tapjoy.TapjoyConnectCore.java
/** * Initialize data from the device information and application info. * This data is used in our URL connection to the Tapjoy server. */// w w w. j av a2 s . c o m private void init() { PackageManager manager = context.getPackageManager(); try { // ANDROID_ID androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); // Get app version. PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), 0); appVersion = packageInfo.versionName; // Device platform. Same as device type. deviceType = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE; platformName = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE; // Get the device model. deviceModel = android.os.Build.MODEL; deviceManufacturer = android.os.Build.MANUFACTURER; // Get the Android OS Version. deviceOSVersion = android.os.Build.VERSION.RELEASE; // Get the device country and language code. deviceCountryCode = Locale.getDefault().getCountry(); deviceLanguage = Locale.getDefault().getLanguage(); // Tapjoy SDK Library version. libraryVersion = TapjoyConstants.TJC_LIBRARY_VERSION_NUMBER; SharedPreferences settings = context.getSharedPreferences(TapjoyConstants.TJC_PREFERENCE, 0); try { TelephonyManager telephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { deviceID = telephonyManager.getDeviceId(); carrierName = telephonyManager.getNetworkOperatorName(); carrierCountryCode = telephonyManager.getNetworkCountryIso(); // getNetworkOperator() returns MCC + MNC, so make sure it's 5 or 6 digits total. // MCC is 3 digits // MNC is 2 or 3 digits if (telephonyManager.getNetworkOperator() != null && (telephonyManager.getNetworkOperator().length() == 5 || telephonyManager.getNetworkOperator().length() == 6)) { mobileCountryCode = telephonyManager.getNetworkOperator().substring(0, 3); mobileNetworkCode = telephonyManager.getNetworkOperator().substring(3); } } TapjoyLog.i(TAPJOY_CONNECT, "deviceID: " + deviceID); boolean invalidDeviceID = false; //---------------------------------------- // Is the device ID null or empty? //---------------------------------------- if (deviceID == null) { TapjoyLog.e(TAPJOY_CONNECT, "Device id is null."); invalidDeviceID = true; } else //---------------------------------------- // Is this an emulator device ID? //---------------------------------------- if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0")) { TapjoyLog.e(TAPJOY_CONNECT, "Device id is empty or an emulator."); invalidDeviceID = true; } //---------------------------------------- // Valid device ID. //---------------------------------------- else { // Lower case the device ID. deviceID = deviceID.toLowerCase(); } TapjoyLog.i(TAPJOY_CONNECT, "ANDROID SDK VERSION: " + android.os.Build.VERSION.SDK); // Is this at least Android 2.3+? // Then let's get the serial. if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 9) { TapjoyLog.i(TAPJOY_CONNECT, "TRYING TO GET SERIAL OF 2.3+ DEVICE..."); // THIS CLASS IS ONLY LOADED FOR ANDROID 2.3+ TapjoyHardwareUtil hardware = new TapjoyHardwareUtil(); serialID = hardware.getSerial(); // Is there no IMEI or MEID? if (invalidDeviceID) { deviceID = serialID; } TapjoyLog.i(TAPJOY_CONNECT, "===================="); TapjoyLog.i(TAPJOY_CONNECT, "SERIAL: deviceID: [" + deviceID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "===================="); //---------------------------------------- // Is the device ID null or empty? //---------------------------------------- if (deviceID == null) { TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is null."); invalidDeviceID = true; } else //---------------------------------------- // Is this an emulator device ID? //---------------------------------------- if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0") || deviceID.equals("unknown")) { TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is empty or an emulator."); invalidDeviceID = true; } //---------------------------------------- // Valid device ID. //---------------------------------------- else { // Lower case the device ID. deviceID = deviceID.toLowerCase(); invalidDeviceID = false; } } // Is the device ID invalid? This is probably an emulator or pre-production device. if (invalidDeviceID) { StringBuffer buff = new StringBuffer(); buff.append("EMULATOR"); String deviceId = settings.getString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, null); // Do we already have an emulator device id stored for this device? if (deviceId != null && !deviceId.equals("")) { deviceID = deviceId; } // Otherwise generate a deviceID for emulator testing. else { String constantChars = "1234567890abcdefghijklmnopqrstuvw"; for (int i = 0; i < 32; i++) { int randomChar = (int) (Math.random() * 100); int ch = randomChar % 30; buff.append(constantChars.charAt(ch)); } deviceID = buff.toString().toLowerCase(); // Save the emulator device ID in the prefs so we can reuse it. SharedPreferences.Editor editor = settings.edit(); editor.putString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, deviceID); editor.commit(); } } } catch (Exception e) { TapjoyLog.e(TAPJOY_CONNECT, "Error getting deviceID. e: " + e.toString()); deviceID = null; } // Set the userID to the deviceID as the initial value. if (userID.length() == 0) userID = deviceID; // Save the SHA-2 hash of the device id. sha2DeviceID = TapjoyUtil.SHA256(deviceID); // Get screen density, dimensions and layout. try { // This is a backwards compatibility fix for Android 1.5 which has no display metric API. // If this is 1.6 or higher, then load the class, otherwise the class never loads and // no crash occurs. if (Integer.parseInt(android.os.Build.VERSION.SDK) > 3) { TapjoyDisplayMetricsUtil displayMetricsUtil = new TapjoyDisplayMetricsUtil(context); deviceScreenDensity = "" + displayMetricsUtil.getScreenDensity(); deviceScreenLayoutSize = "" + displayMetricsUtil.getScreenLayoutSize(); } } catch (Exception e) { TapjoyLog.e(TAPJOY_CONNECT, "Error getting screen density/dimensions/layout: " + e.toString()); } // Get mac address. try { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { macAddress = wifiInfo.getMacAddress(); if (macAddress != null && macAddress.length() > 0) { macAddress = macAddress.toUpperCase(); sha1MacAddress = TapjoyUtil.SHA1(macAddress); } } } } catch (Exception e) { TapjoyLog.e(TAPJOY_CONNECT, "Error getting device mac address: " + e.toString()); } // Alternate market. if (getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET) != null) { marketName = getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET); // Check for existing/supported market names. ArrayList<String> supportedMarketNames = new ArrayList<String>(); supportedMarketNames.add(TapjoyConnectFlag.MARKET_GFAN); // Warning for undefined market names. if (!supportedMarketNames.contains(marketName)) { Log.w(TAPJOY_CONNECT, "Warning -- undefined ALTERNATE_MARKET: " + marketName); } } // Get the referral URL String tempReferralURL = settings.getString(TapjoyConstants.PREF_REFERRAL_URL, null); if (tempReferralURL != null && !tempReferralURL.equals("")) referralURL = tempReferralURL; // Get the client package name. clientPackage = context.getPackageName(); TapjoyLog.i(TAPJOY_CONNECT, "Metadata successfully loaded"); TapjoyLog.i(TAPJOY_CONNECT, "APP_ID = [" + appID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "ANDROID_ID: [" + androidID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "CLIENT_PACKAGE = [" + clientPackage + "]"); TapjoyLog.i(TAPJOY_CONNECT, "deviceID: [" + deviceID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "sha2DeviceID: [" + sha2DeviceID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_SERIAL_ID + ": [" + serialID + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_MAC_ADDRESS + ": [" + macAddress + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_SHA1_MAC_ADDRESS + ": [" + sha1MacAddress + "]"); TapjoyLog.i(TAPJOY_CONNECT, "deviceName: [" + deviceModel + "]"); TapjoyLog.i(TAPJOY_CONNECT, "deviceManufacturer: [" + deviceManufacturer + "]"); TapjoyLog.i(TAPJOY_CONNECT, "deviceType: [" + deviceType + "]"); TapjoyLog.i(TAPJOY_CONNECT, "libraryVersion: [" + libraryVersion + "]"); TapjoyLog.i(TAPJOY_CONNECT, "deviceOSVersion: [" + deviceOSVersion + "]"); TapjoyLog.i(TAPJOY_CONNECT, "COUNTRY_CODE: [" + deviceCountryCode + "]"); TapjoyLog.i(TAPJOY_CONNECT, "LANGUAGE_CODE: [" + deviceLanguage + "]"); TapjoyLog.i(TAPJOY_CONNECT, "density: [" + deviceScreenDensity + "]"); TapjoyLog.i(TAPJOY_CONNECT, "screen_layout: [" + deviceScreenLayoutSize + "]"); TapjoyLog.i(TAPJOY_CONNECT, "carrier_name: [" + carrierName + "]"); TapjoyLog.i(TAPJOY_CONNECT, "carrier_country_code: [" + carrierCountryCode + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_MOBILE_COUNTRY_CODE + ": [" + mobileCountryCode + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_MOBILE_NETWORK_CODE + ": [" + mobileNetworkCode + "]"); TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_MARKET_NAME + ": [" + marketName + "]"); TapjoyLog.i(TAPJOY_CONNECT, "referralURL: [" + referralURL + "]"); if (connectFlags != null) { TapjoyLog.i(TAPJOY_CONNECT, "Connect Flags:"); TapjoyLog.i(TAPJOY_CONNECT, "--------------------"); Set<Entry<String, String>> entries = connectFlags.entrySet(); Iterator<Entry<String, String>> iterator = entries.iterator(); while (iterator.hasNext()) { Entry<String, String> item = iterator.next(); TapjoyLog.i(TAPJOY_CONNECT, "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue())); } } } catch (Exception e) { TapjoyLog.e(TAPJOY_CONNECT, "Error initializing Tapjoy parameters. e=" + e.toString()); } }
From source file:com.clustercontrol.collect.composite.CollectGraphComposite.java
/** * ???????????//from ww w . j av a 2 s. com * * @param summaryType * @param itemCodeList */ private void setSettingLabel(int summaryType, List<CollectKeyInfoPK> itemCodeList) { ArrayList<String> itemCodeNameList = new ArrayList<>(); for (EndpointUnit unit : EndpointManager.getActiveManagerList()) { for (CollectKeyInfoPK itemCode : itemCodeList) { String displayName = itemCode.getDisplayName(); String itemName = itemCode.getItemName(); if (!displayName.equals("") && !itemName.endsWith("[" + displayName + "]")) { itemName += "[" + displayName + "]"; } String str = itemName + CollectSettingComposite.SEPARATOR_AT + itemCode.getMonitorId() + "(" + unit.getManagerName() + ")"; if (!itemCodeNameList.contains(str)) { itemCodeNameList.add(str); } } } StringBuffer itemCodeStr = new StringBuffer(); for (String itemCodeName : itemCodeNameList) { if (0 < itemCodeStr.length()) { itemCodeStr.append(", "); } itemCodeStr.append(HinemosMessage.replace(itemCodeName)); } if (itemCodeStr.length() > 256) { itemCodeStr = new StringBuffer(itemCodeStr.substring(0, 256)); itemCodeStr.append("..."); } settingLabel.setText( Messages.getString("collection.summary.type") + " : " + SummaryTypeMessage.typeToString(summaryType) + ", " + Messages.getString("collection.display.name") + " : " + itemCodeStr.toString()); }