Java Code Examples for java.util.ArrayList#contains()

The following examples show how to use java.util.ArrayList#contains() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Connector.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void joinAGroup(final IAgent agt, final String groupName) {
	if (!this.receivedMessage.keySet().contains(agt)) {
		this.receivedMessage.put(agt, new LinkedList<ConnectorMessage>());
	}

	ArrayList<IAgent> agentBroadcast = this.boxFollower.get(groupName);

	if (agentBroadcast == null) {
		this.subscribeToGroup(agt, groupName);
		agentBroadcast = new ArrayList<>();
		this.boxFollower.put(groupName, agentBroadcast);
	}
	if (!agentBroadcast.contains(agt)) {
		agentBroadcast.add(agt);
		this.subscribeToGroup(agt, groupName);
	}
}
 
Example 2
Source File: AliasManager.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
private void getAliases(ArrayList<Alias> aliases, String propertyValue, String url) {
	StringReader reader = new StringReader(propertyValue);
	BufferedReader bReader = new BufferedReader(reader);
	try {
		String line = bReader.readLine();
		while (line != null) {
			Alias alias = getAlias(line, url);
			if (aliases.contains(alias)) {
				Alias checkAlias = aliases.get(aliases.indexOf(alias));
				if (alias.getRevision() < checkAlias.getRevision()) {
					aliases.remove(checkAlias);
					aliases.add(alias);
				}					
			} else {
				if (alias != null) {
					aliases.add(alias);
				}
			}
			line = bReader.readLine();
		}
		bReader.close();
	} catch (Exception e) {}
}
 
Example 3
Source File: AtlasRenderer.java    From bladecoder-adventure-engine with Apache License 2.0 6 votes vote down vote up
@Override
public String[] getInternalAnimations(AnimationDesc anim) {
	retrieveSource(anim.source);

	TextureAtlas atlas = EngineAssetManager.getInstance().getTextureAtlas(anim.source);

	Array<AtlasRegion> animations = atlas.getRegions();
	ArrayList<String> l = new ArrayList<>();

	for (int i = 0; i < animations.size; i++) {
		AtlasRegion a = animations.get(i);
		if (!l.contains(a.name))
			l.add(a.name);
	}

	return l.toArray(new String[l.size()]);
}
 
Example 4
Source File: ImportLipidModificationsAction.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load the lipid modificatons into the list
 *
 * @param lines CSV lines to parse.
 */
private static LipidModification[] loadLipidModificationsIntoChoices(final String[][] lines,
    final LipidModification[] modifications) {

  // Create a list of lipid modifications.
  final ArrayList<LipidModification> choices =
      new ArrayList<LipidModification>(Arrays.asList(modifications));

  int i = 1;
  for (final String line[] : lines) {
    try {

      // Create new modification and add it to the choices if it's new.
      final LipidModification modification = new LipidModification(line[0], line[1]);
      if (!choices.contains(modification)) {

        choices.add(modification);
      }
    } catch (final NumberFormatException ignored) {

      LOG.warning("Couldn't find lipid modifier in line " + line[0]);
    }
  }

  return choices.toArray(new LipidModification[choices.size()]);
}
 
Example 5
Source File: FatJarRsrcUrlManifestProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void setManifestRsrcClasspath(Manifest ownManifest, JarPackageData jarPackage) {
	ArrayList<String> jarNames= new ArrayList<String>();
	Object[] elements= jarPackage.getElements();
	for (int i= 0; i < elements.length; i++) {
		Object element= elements[i];
		if (element instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) element).isArchive()) {
			String jarName= ((IPackageFragmentRoot) element).getPath().toFile().getName();
			while (jarNames.contains(jarName)) {
				jarName= FatJarPackagerUtil.nextNumberedFileName(jarName);
			}
			jarNames.add(jarName);
		}
	}
	String manifestRsrcClasspath= getManifestRsrcClasspath(jarNames);
	ownManifest.getMainAttributes().putValue(JIJConstants.REDIRECTED_CLASS_PATH_MANIFEST_NAME, manifestRsrcClasspath); 
}
 
Example 6
Source File: EcrfProgressOverviewBean.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
public ECRFFieldStatusQueueCountVO getSummaryFieldStatusCount(TrialOutVO trialVO, String queues) {
	TrialECRFProgressSummaryVO trialProgressSummary = getCachedEcrfProgressSummary(trialVO);
	ECRFFieldStatusQueueCountVO result = null;
	if (trialProgressSummary != null && trialProgressSummary.getEcrfStatusEntryCount() > 0l) {
		ArrayList<Enum<ECRFFieldStatusQueue>> queuesToInclude = WebUtil.getEnumList(queues, ECRFFieldStatusQueue.class);
		result = new ECRFFieldStatusQueueCountVO();
		Iterator<ECRFFieldStatusQueueCountVO> it = trialProgressSummary.getEcrfFieldStatusQueueCounts().iterator();
		while (it.hasNext()) {
			ECRFFieldStatusQueueCountVO queueCount = it.next();
			if (queuesToInclude.contains(queueCount.getQueue())) {
				result.setInitial(result.getInitial() + queueCount.getInitial());
				result.setUpdated(result.getUpdated() + queueCount.getUpdated());
				result.setProposed(result.getProposed() + queueCount.getProposed());
				result.setResolved(result.getResolved() + queueCount.getResolved());
				result.setUnresolved(result.getUnresolved() + queueCount.getUnresolved());
			}
			result.setTotal(result.getTotal() + queueCount.getTotal());
		}
	}
	return result;
}
 
Example 7
Source File: GameMap.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
public void addChest(Chest chest, ChestPlacementType cpt) {
	ArrayList<CoordLoc> list;
	if (cpt == ChestPlacementType.NORMAL) {
		list = chests;
	} else {
		list = centerChests;
	}
	InventoryHolder ih = chest.getInventory().getHolder();
       if (ih instanceof DoubleChest) {
       	DoubleChest dc = (DoubleChest) ih;
		Chest left = (Chest) dc.getLeftSide();
		Chest right = (Chest) dc.getRightSide();
		CoordLoc locLeft = new CoordLoc(left.getX(), left.getY(), left.getZ());
		CoordLoc locRight = new CoordLoc(right.getX(), right.getY(), right.getZ());
		if (!(list.contains(locLeft) || list.contains(locRight))) {
			addChest(locLeft, cpt, true);
		}
       } else {
       	CoordLoc loc = new CoordLoc(chest.getX(), chest.getY(), chest.getZ());
           if (!list.contains(loc)){
			addChest(loc, cpt, true);
           }
       }
}
 
Example 8
Source File: ContentFragment.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
private void addTo(final List<LayoutElement> items, final ArrayList<BaseFile> baseFiles) {
			//final ArrayList<LayoutElement> items = new ArrayList<>();

			final ArrayList<String> hiddenfiles = dataUtils.getHiddenfiles();
			for (BaseFile baseFile : baseFiles) {
				//final BaseFile baseFile = baseFiles.get(i);
				//File f = new File(ele.getPath());

				if (!hiddenfiles.contains(baseFile.getPath())) {
					final LayoutElement layoutElement = new LayoutElement(baseFile);
					layoutElement.setMode(openMode);//baseFile.getMode());
					items.add(layoutElement);
//					if (baseFile.isDirectory()) {
//						folder_count++;
//					} else {
//						file_count++;
//					}
				}
			}
			//return items;
		}
 
Example 9
Source File: PluginManager.java    From odo with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a string array of the methods loaded for a class
 *
 * @param pluginClass name of class
 * @return string array of the methods loaded for the class
 * @throws Exception exception
 */
public String[] getMethods(String pluginClass) throws Exception {
    ArrayList<String> methodNames = new ArrayList<String>();

    Method[] methods = getClass(pluginClass).getDeclaredMethods();
    for (Method method : methods) {
        logger.info("Checking {}", method.getName());

        com.groupon.odo.proxylib.models.Method methodInfo = this.getMethod(pluginClass, method.getName());
        if (methodInfo == null) {
            continue;
        }

        // check annotations
        Boolean matchesAnnotation = false;
        if (methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_CLASS) ||
            methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_V2_CLASS)) {
            matchesAnnotation = true;
        }

        if (!methodNames.contains(method.getName()) && matchesAnnotation) {
            methodNames.add(method.getName());
        }
    }

    return methodNames.toArray(new String[0]);
}
 
Example 10
Source File: CheckDupFlavor.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args){
    PrintService defService = PrintServiceLookup.lookupDefaultPrintService();
    PrintService[] pservice;
    if (defService == null) {
        pservice = PrintServiceLookup.lookupPrintServices(null, null);
        if (pservice.length == 0) {
            throw new RuntimeException("No printer found.  TEST ABORTED");
        }
        defService = pservice[0];
    }

    System.out.println("PrintService = "+defService);

    DocFlavor[] flavors = defService.getSupportedDocFlavors();
    if (flavors==null) {
        System.out.println("No flavors supported. Test PASSED.");
        return;
    }


    ArrayList flavorList = new ArrayList();
    for (int i=0; i<flavors.length; i++) {
        if (flavors[i] == null) {
             throw new RuntimeException("Null flavor. Test FAILED.");
        } else if (flavorList.contains(flavors[i])) {
             throw new RuntimeException("\n\tDuplicate flavor found : "+flavors[i]+" : Test FAILED.");
        } else {
            flavorList.add(flavors[i]);
        }
    }
    System.out.println("No duplicate found. Test PASSED.");
}
 
Example 11
Source File: IssueTimelinePresenter.java    From OpenHub with GNU General Public License v3.0 5 votes vote down vote up
public ArrayList<String> getIssueUsersExceptMe(){
    if(timeline == null) return null;
    ArrayList<String> users = new ArrayList<String>();
    for(IssueEvent event : timeline){
        String userLoginId = event.getUser() == null ? event.getActor().getLogin() : event.getUser().getLogin();
        if(!AppData.INSTANCE.getLoggedUser().getLogin().equals(userLoginId)
                && !users.contains(userLoginId)){
            users.add(userLoginId);
        }
    }
    return users;
}
 
Example 12
Source File: DictionaryGenerator.java    From Kylin with Apache License 2.0 5 votes vote down vote up
private static Dictionary buildDateStrDict(List<byte[]> values, int baseId, int nSamples, ArrayList samples) {
    final int BAD_THRESHOLD = 2;
    String matchPattern = null;

    for (String ptn : DATE_PATTERNS) {
        matchPattern = ptn; // be optimistic
        int badCount = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(ptn);
        for (byte[] value : values) {
            if (value.length == 0)
                continue;

            String str = Bytes.toString(value);
            try {
                sdf.parse(str);
                if (samples.size() < nSamples && samples.contains(str) == false)
                    samples.add(str);
            } catch (ParseException e) {
                logger.info("Unrecognized datetime value: " + str);
                badCount++;
                if (badCount > BAD_THRESHOLD) {
                    matchPattern = null;
                    break;
                }
            }
        }
        if (matchPattern != null)
            return new DateStrDictionary(matchPattern, baseId);
    }
    throw new IllegalStateException("Unrecognized datetime value");
}
 
Example 13
Source File: CFGridWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private long processTransformationVars(ArrayList<Variable> varList, ArrayList<String> varNameList, NetcdfDataset ncd,
    ucar.nc2.dt.GridDataset gds, GridDatatype grid, Range timeRange, Range zRangeUse, Range yRange, Range xRange,
    int z_stride, int y_stride, int x_stride) throws InvalidRangeException {

  long varsSize = 0L;
  List<CoordinateTransform> cctt = grid.getCoordinateSystem().getCoordinateTransforms();
  for (CoordinateTransform ct : cctt) {
    Parameter param = ct.findParameterIgnoreCase(CF.FORMULA_TERMS);

    if (param != null) {
      String[] varStrings = param.getStringValue().split(" ");
      for (int i = 1; i < varStrings.length; i += 2) {
        Variable paramVar = ncd.findVariable(varStrings[i].trim());

        if (!varNameList.contains(varStrings[i]) && (null != paramVar)) {

          if (gds.findGridDatatype(paramVar.getFullName()) != null) {
            // Subset if needed
            if ((null != timeRange) || (zRangeUse != null) || (x_stride > 1 && y_stride > 1)
                || (yRange != null || xRange != null)) {
              GridDatatype complementaryGrid = gds.findGridDatatype(paramVar.getFullName());
              complementaryGrid = complementaryGrid.makeSubset(null, null, timeRange, zRangeUse, yRange, xRange);
              paramVar = complementaryGrid.getVariable();
            }
          } else {
            // Also have to subset the var if it is not a grid but has vertical dimension (the dimensionless vars in
            // the formula) and zRangeUse != null
            if (zRangeUse != null && paramVar.getRank() == 1) {
              List<Range> ranges = new ArrayList<Range>();
              ranges.add(zRangeUse);
              paramVar = paramVar.section(ranges);
            }
          }
          varNameList.add(paramVar.getFullName());
          varsSize += paramVar.getSize() * paramVar.getElementSize();
          varList.add(paramVar);
        }

      }
    }
  }

  return varsSize;

}
 
Example 14
Source File: SunFontManager.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * In some cases windows may have fonts in the fonts folder that
 * don't show up in the registry or in the GDI calls to enumerate fonts.
 * The only way to find these is to list the directory. We invoke this
 * only in getAllFonts/Families, so most searches for a specific
 * font that is satisfied by the GDI/registry calls don't take the
 * additional hit of listing the directory. This hit is small enough
 * that its not significant in these 'enumerate all the fonts' cases.
 * The basic approach is to cross-reference the files windows found
 * with the ones in the directory listing approach, and for each
 * in the latter list that is missing from the former list, register it.
 */
private synchronized void checkForUnreferencedFontFiles() {
    if (haveCheckedUnreferencedFontFiles) {
        return;
    }
    haveCheckedUnreferencedFontFiles = true;
    if (!FontUtilities.isWindows) {
        return;
    }
    /* getFontFilesFromPath() returns all lower case names.
     * To compare we also need lower case
     * versions of the names from the registry.
     */
    ArrayList<String> registryFiles = new ArrayList<String>();
    for (String regFile : fontToFileMap.values()) {
        registryFiles.add(regFile.toLowerCase());
    }

    /* To avoid any issues with concurrent modification, create
     * copies of the existing maps, add the new fonts into these
     * and then replace the references to the old ones with the
     * new maps. ConcurrentHashmap is another option but its a lot
     * more changes and with this exception, these maps are intended
     * to be static.
     */
    HashMap<String,String> fontToFileMap2 = null;
    HashMap<String,String> fontToFamilyNameMap2 = null;
    HashMap<String,ArrayList<String>> familyToFontListMap2 = null;;

    for (String pathFile : getFontFilesFromPath(false)) {
        if (!registryFiles.contains(pathFile)) {
            if (FontUtilities.isLogging()) {
                FontUtilities.getLogger()
                             .info("Found non-registry file : " + pathFile);
            }
            PhysicalFont f = registerFontFile(getPathName(pathFile));
            if (f == null) {
                continue;
            }
            if (fontToFileMap2 == null) {
                fontToFileMap2 = new HashMap<String,String>(fontToFileMap);
                fontToFamilyNameMap2 =
                    new HashMap<String,String>(fontToFamilyNameMap);
                familyToFontListMap2 = new
                    HashMap<String,ArrayList<String>>(familyToFontListMap);
            }
            String fontName = f.getFontName(null);
            String family = f.getFamilyName(null);
            String familyLC = family.toLowerCase();
            fontToFamilyNameMap2.put(fontName, family);
            fontToFileMap2.put(fontName, pathFile);
            ArrayList<String> fonts = familyToFontListMap2.get(familyLC);
            if (fonts == null) {
                fonts = new ArrayList<String>();
            } else {
                fonts = new ArrayList<String>(fonts);
            }
            fonts.add(fontName);
            familyToFontListMap2.put(familyLC, fonts);
        }
    }
    if (fontToFileMap2 != null) {
        fontToFileMap = fontToFileMap2;
        familyToFontListMap = familyToFontListMap2;
        fontToFamilyNameMap = fontToFamilyNameMap2;
    }
}
 
Example 15
Source File: SaiyTextToSpeech.java    From Saiy-PS with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Process a Text to Speech utterance request, considering API versions, sound effects, silence
 * and other possibilities.
 *
 * @param text        the utterance
 * @param queueMode   one of {@link #QUEUE_ADD} or {@link #QUEUE_FLUSH}
 * @param params      the {@link SelfAwareParameters} object
 * @param utteranceId the utterance id
 * @return one of {@link #SUCCESS} or {@link Error}
 */
public int speak(@NonNull CharSequence text, final int queueMode,
                 @NonNull final SelfAwareParameters params, @NonNull final String utteranceId) {

    if (SoundEffectHelper.pSOUND_EFFECT.matcher(text).matches()) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "speak: have sound effect");
        }

        final Gender gender;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            final SaiyVoice voice = getBoundSaiyVoice();

            if (voice != null) {
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "speak: have sound effect: voice.getGender(): " + voice.getGender().name());
                }
                gender = voice.getGender();
            } else {
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "speak: have sound effect: voice null");
                }
                gender = Gender.UNDEFINED;
            }
        } else {
            gender = Gender.UNDEFINED;
        }

        final SoundEffectHelper helper = new SoundEffectHelper(text, utteranceId, gender);
        helper.sort();
        final ArrayList<SoundEffectItem> items = helper.getArray();
        final ArrayList<String> addedItems = SoundEffectHelper.getAddedItems();

        int result = ERROR;
        for (final SoundEffectItem item : items) {

            params.setUtteranceId(item.getUtteranceId());

            if (DEBUG) {
                MyLog.i(CLS_NAME, "item getText: " + item.getText());
                MyLog.i(CLS_NAME, "item getItemType: " + item.getItemType());
                MyLog.i(CLS_NAME, "item getUtteranceId: " + item.getUtteranceId());
            }

            switch (item.getItemType()) {

                case SoundEffectItem.SOUND:

                    if (addedItems.contains(item.getText())) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            result = playEarcon(item.getText(), QUEUE_ADD, params.getBundle(), item.getUtteranceId());
                        } else {
                            result = playEarcon(item.getText(), QUEUE_ADD, params);
                        }
                    } else {
                        if (DEBUG) {
                            MyLog.w(CLS_NAME, "No valid sound effect: " + item.getText());
                        }
                        result = ERROR;
                    }

                    break;
                case SoundEffectItem.SPEECH:

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        result = speak21(item.getText(), QUEUE_ADD, params, item.getUtteranceId());
                    } else {
                        result = speak(item.getText(), QUEUE_ADD, params);
                    }
                    break;
                case SoundEffectItem.SILENCE:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        result = playSilentUtterance(SoundEffect.SILENCE_DURATION, QUEUE_ADD,
                                item.getUtteranceId());
                    } else {
                        result = playSilence(SoundEffect.SILENCE_DURATION, QUEUE_ADD, params);
                    }
                    break;
            }
        }

        return result;
    } else {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return speak21(text, queueMode, params, utteranceId);
        } else {
            return speak(text.toString(), queueMode, params);
        }
    }
}
 
Example 16
Source File: SugiyamaLayoutAlgorithm.java    From gef with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Returns the number of crosses between the two nodes and those
 * connected to them.
 * 
 * @param nodeA
 * @param nodeB
 * @return
 */
private int numberOfCrosses(NodeWrapper nodeA, NodeWrapper nodeB) {
	int numOfCrosses = 0;
	if (nodeA.equals(nodeB))
		return 0;

	// Filter nodes connected with bidirectional edges
	ArrayList<Node> adjacentNodesOfA = unionOfNodes(
			nodeA.node.getPredecessorNodes(),
			nodeA.node.getSuccessorNodes());
	ArrayList<Node> adjacentNodesOfB = unionOfNodes(
			nodeB.node.getPredecessorNodes(),
			nodeB.node.getSuccessorNodes());

	for (Node aNode : adjacentNodesOfA) {
		ArrayList<Integer> alreadyCrossed = new ArrayList<>();
		NodeWrapper aNodeWrapper = map.get(aNode);
		for (int i = 0; i < adjacentNodesOfB.size(); i++) {
			NodeWrapper nw = map.get(adjacentNodesOfB.get(i));
			if (!alreadyCrossed.contains(i) && nw != null) {
				// only if on the same side
				if ((nw.layer > nodeA.layer
						&& aNodeWrapper.layer > nodeA.layer)
						|| (nw.layer < nodeA.layer
								&& aNodeWrapper.layer < nodeA.layer)) {
					if (nodeA.index < nodeB.index) {
						if (aNodeWrapper.index > nw.index) {
							numOfCrosses++;
							alreadyCrossed.add(i);
						} else if (nw.index == aNodeWrapper.index) {
							if (nodeA.index >= nw.index) {
								// implies nodeB.index > nw.index
								if ((aNodeWrapper.layer > nw.layer
										&& nodeA.layer < nw.layer)
										|| (aNodeWrapper.layer < nw.layer
												&& nw.layer < nodeA.layer)) {
									// top-left or bottom-left quarter
									numOfCrosses++;
									alreadyCrossed.add(i);
								}
							} else if (nodeB.index <= nw.index) {
								// implies nodeA.index < nw.index
								if ((aNodeWrapper.layer > nw.layer
										&& aNodeWrapper.layer < nodeB.layer)
										|| (aNodeWrapper.layer < nw.layer
												&& aNodeWrapper.layer > nodeB.layer)) {
									// top-right or bottom-right quarter
									numOfCrosses++;
									alreadyCrossed.add(i);
								}
							}
						}
					} else if (nodeA.index > nodeB.index) {
						if (aNodeWrapper.index < nw.index) {
							numOfCrosses++;
							alreadyCrossed.add(i);
						} else if (nw.index == aNodeWrapper.index) {
							if (nodeB.index >= nw.index) {
								// implies nodeB.index > nw.index
								if ((aNodeWrapper.layer > nw.layer
										&& nodeB.layer > aNodeWrapper.layer)
										|| (aNodeWrapper.layer < nw.layer
												&& aNodeWrapper.layer > nodeB.layer)) {
									// top-left or bottom-left quarter
									numOfCrosses++;
									alreadyCrossed.add(i);
								}
							} else if (nodeA.index <= nw.index) {
								// implies nodeA.index < nw.index
								if ((aNodeWrapper.layer > nw.layer
										&& nw.layer > nodeA.layer)
										|| (aNodeWrapper.layer < nw.layer
												&& nw.layer < nodeA.layer)) {
									// top-right or bottom-right quarter
									numOfCrosses++;
									alreadyCrossed.add(i);
								}
							}
						}
					}
				}
			}
		}
	}

	return numOfCrosses;
}
 
Example 17
Source File: IabHelper.java    From Sensor-Disabler with MIT License 4 votes vote down vote up
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
        throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        for (String sku : moreSkus) {
            if (!skuList.contains(sku)) {
                skuList.add(sku);
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    Bundle querySkus = new Bundle();
    querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList);
    Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(),
            itemType, querySkus);

    if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
        int response = getResponseCodeFromBundle(skuDetails);
        if (response != BILLING_RESPONSE_RESULT_OK) {
            logDebug("getSkuDetails() failed: " + getResponseDesc(response));
            return response;
        } else {
            logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
            return IABHELPER_BAD_RESPONSE;
        }
    }

    ArrayList<String> responseList = skuDetails.getStringArrayList(
            RESPONSE_GET_SKU_DETAILS_LIST);

    for (String thisResponse : responseList) {
        SkuDetails d = new SkuDetails(itemType, thisResponse);
        logDebug("Got sku details: " + d);
        inv.addSkuDetails(d);
    }
    return BILLING_RESPONSE_RESULT_OK;
}
 
Example 18
Source File: LauncherProvider.java    From LaunchEnr with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Recreates workspace table and migrates data to the new table.
 */
boolean recreateWorkspaceTable(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
                new String[] {LauncherSettings.WorkspaceScreens._ID},
                null, null, null, null,
                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
        ArrayList<Long> sortedIDs = new ArrayList<Long>();
        long maxId = 0;
        try {
            while (c.moveToNext()) {
                Long id = c.getLong(0);
                if (!sortedIDs.contains(id)) {
                    sortedIDs.add(id);
                    maxId = Math.max(maxId, id);
                }
            }
        } finally {
            c.close();
        }

        db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
        addWorkspacesTable(db, false);

        // Add all screen ids back
        int total = sortedIDs.size();
        for (int i = 0; i < total; i++) {
            ContentValues values = new ContentValues();
            values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
            values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
            addModifiedTime(values);
            db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
        mMaxScreenId = maxId;
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        ex.printStackTrace();
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}
 
Example 19
Source File: IabHelper.java    From SystemUITuner2 with MIT License 4 votes vote down vote up
@SuppressWarnings("WeakerAccess")
int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
        throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        for (String sku : moreSkus) {
            if (!skuList.contains(sku)) {
                skuList.add(sku);
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    // Split the sku list in blocks of no more than 20 elements.
    ArrayList<ArrayList<String>> packs = new ArrayList<>();
    ArrayList<String> tempList;
    int n = skuList.size() / 20;
    int mod = skuList.size() % 20;
    for (int i = 0; i < n; i++) {
        tempList = new ArrayList<>();
        tempList.addAll(skuList.subList(i * 20, i * 20 + 20));
        packs.add(tempList);
    }
    if (mod != 0) {
        tempList = new ArrayList<>();
        tempList.addAll(skuList.subList(n * 20, n * 20 + mod));
        packs.add(tempList);
    }

    for (ArrayList<String> skuPartList : packs) {
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuPartList);
        Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(),
                itemType, querySkus);

        if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
            int response = getResponseCodeFromBundle(skuDetails);
            if (response != BILLING_RESPONSE_RESULT_OK) {
                logDebug("getSkuDetails() failed: " + getResponseDesc(response));
                return response;
            } else {
                logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
                return IABHELPER_BAD_RESPONSE;
            }
        }

        ArrayList<String> responseList = skuDetails.getStringArrayList(
                RESPONSE_GET_SKU_DETAILS_LIST);

        for (String thisResponse : responseList != null ? responseList : new ArrayList<String>()) {
            SkuDetails d = new SkuDetails(itemType, thisResponse);
            logDebug("Got sku details: " + d);
            inv.addSkuDetails(d);
        }
    }

    return BILLING_RESPONSE_RESULT_OK;
}
 
Example 20
Source File: Table.java    From sqlitemagic with Apache License 2.0 3 votes vote down vote up
/**
 * This method gives table class the opportunity to perfect selection at select statement
 * build time.
 *
 * @param observedTables      Tables that are being selected
 * @param tableGraphNodeNames Selection graph node names
 * @param columnPositions     Column positions in the selection
 * @return Whether selection should be deep.
 */
boolean perfectSelection(@NonNull ArrayList<String> observedTables,
                         @Nullable SimpleArrayMap<String, String> tableGraphNodeNames,
                         @Nullable SimpleArrayMap<String, Integer> columnPositions) {
  if (!observedTables.contains(name)) {
    observedTables.add(name);
  }
  return false;
}