List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:com.compomics.util.experiment.identification.psm_scoring.psm_scores.HyperScore.java
/** * Returns the e-value corresponding to a list of scores in a map. If not * enough scores are present or if they are not spread the method returns * null./* w w w . j a va 2s . co m*/ * * @param hyperScores the different scores * @param useCache if true the interpolation values will be stored in the * histograms in cache * * @return the e-values corresponding to the given scores */ public HashMap<Double, Double> getEValueMap(ArrayList<Double> hyperScores, boolean useCache) { HashMap<Integer, Integer> histogram = new HashMap<Integer, Integer>(); Double maxScore = 0.0; Double minScore = Double.MAX_VALUE; for (Double score : hyperScores) { Integer intValue = score.intValue(); if (intValue > 0) { Integer nScores = histogram.get(intValue); if (nScores == null) { nScores = 1; } else { nScores++; } histogram.put(intValue, nScores); if (score > maxScore) { maxScore = score; } if (score < minScore) { minScore = score; } } } Integer lowestBin = minScore.intValue(); Integer highestBin = maxScore.intValue(); Integer secondEmptybin = highestBin; Integer firstEmptybin = highestBin; boolean emptyBin = false; for (Integer bin = lowestBin; bin <= highestBin; bin++) { if (!histogram.containsKey(bin)) { if (!emptyBin) { emptyBin = true; firstEmptybin = bin; } else { secondEmptybin = bin; break; } } } ArrayList<Integer> bins = new ArrayList<Integer>(histogram.keySet()); for (Integer bin : bins) { if (bin > secondEmptybin) { histogram.remove(bin); } else if (bin > firstEmptybin) { histogram.put(bin, 1); } } double[] ab = getInterpolationValues(histogram, useCache); if (ab == null) { return null; } return getInterpolation(hyperScores, ab[0], ab[1]); }
From source file:org.geworkbench.engine.ccm.ComponentConfigurationManager.java
/** * Removes the component with resourceName. * /* w w w.j av a 2s . c o m*/ * @param folderName * @param ccmFileName * @return Returns false if component was not successfully removed, else * true. */ @SuppressWarnings("unchecked") public boolean removeComponent(String folderName, String filename) { /* * Container Summary: * * ComponentRegistry Section listeners = new TypeMap<List>(); * acceptors = new HashMap<Class, List<Class>>(); * synchModels = new HashMap<Class, SynchModel>(); * components = new ArrayList(); * idToDescriptor = new HashMap<String, PluginDescriptor>(); * nameToComponentResource = new HashMap<String, ComponentResource>(); */ ComponentRegistry componentRegistry = ComponentRegistry.getRegistry(); /* validation */ if (StringUtils.isEmpty(folderName)) { log.error("Input resource is null. Returning ..."); return false; } List<String> list = Arrays.asList(files); if (!list.contains(folderName)) { return false; } // FIXME why parse again? can't we get this info another way? /* parse the ccm.xml file */ PluginComponent ccmComponent = null; if (filename.endsWith(COMPONENT_DESCRIPTOR_EXTENSION)) { ccmComponent = getPluginsFromFile(new File(filename)); } else { return false; } if (ccmComponent == null) return false; /* GET THE VARIOUS MAPS/VECTORS FROM THE PLUGIN REGISTRY */ /* plugin registry component vector */ Vector<PluginDescriptor> componentVector = PluginRegistry.getComponentVector(); /* plugin registry visual area map */ HashMap<PluginDescriptor, String> visualAreaMap = PluginRegistry.getVisualAreaMap(); /* plugin registry used ids */ Vector<String> usedIds = PluginRegistry.getUsedIds(); // FIXME Can't we get the PluginDesriptor we want other than from the // ccm.xml file? // beginning of processing the plugin final String pluginClazzName = ccmComponent.getClazz(); PluginDescriptor pluginDescriptor = PluginRegistry.getPluginDescriptor(ccmComponent.getPluginId()); if (pluginDescriptor != null) { /* START THE REMOVAL PROCESS IN THE PLUGIN REGISTRY */ /* PluginRegistry.visualAreaMap */ for (Entry<PluginDescriptor, String> entry : visualAreaMap.entrySet()) { Object pluginDescriptor1 = entry.getKey(); Class<?> clazz = pluginDescriptor1.getClass(); String proxiedClazzName = clazz.getName(); // TODO Replace $$ parse methods with clazzName = clazz.getSuperclass() String[] temp = StringUtils.split(proxiedClazzName, "$$"); String clazzName = temp[0]; if (StringUtils.equals(pluginClazzName, clazzName)) { visualAreaMap.remove(entry.getKey()); break; } } /* PluginRegistry.visualAreaMap */ String id = ccmComponent.getPluginId(); if (PluginDescriptor.idExists(id)) { usedIds.remove(id); } /* PluginRegistry.compontentVector */ if (componentVector.contains(pluginDescriptor)) { componentVector.remove(pluginDescriptor); } /* START THE REMOVAL PROCESS IN THE COMPONENT REGISTRY */ componentRegistry.removeComponent(pluginClazzName); componentRegistry.removePlugin(ccmComponent.getPluginId()); } // end of processing the plugin /* ComponentRegistry.idToDescriptor */ /* If other Plugins are using the same Component Resource, don't remove the Resource */ int foldersInUse = 0; for (int i = 0; i < componentVector.size(); i++) { PluginDescriptor pd = componentVector.get(i); if (pd == null) { continue; } ComponentResource componentResource = pd.getResource(); if (componentResource == null) { continue; } String name = componentResource.getName(); if (name == null) { continue; } if (name.equalsIgnoreCase(folderName)) { foldersInUse++; } } if (foldersInUse < 1) { componentRegistry.removeComponentResource(folderName); } return true; }
From source file:com.trellmor.berrymotes.sync.SubredditEmoteDownloader.java
public void updateEmotes(List<EmoteImage> emotes) throws RemoteException, OperationApplicationException, InterruptedException { checkInterrupted();/*from w w w . j a va 2s . c om*/ Log.debug("Updating emote database"); // Build map of entries HashMap<String, EmoteImage> emoteHash = new HashMap<String, EmoteImage>(); for (EmoteImage emote : emotes) { emoteHash.put(emote.getHash(), emote); } checkInterrupted(); Cursor c = mContentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT, new String[] { EmotesContract.Emote._ID, EmotesContract.Emote.COLUMN_NAME, EmotesContract.Emote.COLUMN_HASH }, EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { mSubreddit }, null); if (c != null) { ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); if (c.moveToFirst()) { final int POS_ID = c.getColumnIndex(EmotesContract.Emote._ID); final int POS_NAME = c.getColumnIndex(EmotesContract.Emote.COLUMN_NAME); final int POS_HASH = c.getColumnIndex(EmotesContract.Emote.COLUMN_HASH); do { String hash = c.getString(POS_HASH); String name = c.getString(POS_NAME); EmoteImage emote = emoteHash.get(hash); if (emote != null) { if (emote.getNames().contains(name)) { emote.getNames().remove(name); if (emote.getNames().size() == 0) { // Already in db, no need to insert emoteHash.remove(hash); emotes.remove(emote); } } else { Log.debug("Removing " + name + " (" + hash + ") from DB"); Uri deleteUri = EmotesContract.Emote.CONTENT_URI.buildUpon() .appendPath(Integer.toString(c.getInt(POS_ID))).build(); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); } } } while (c.moveToNext()); } c.close(); // Delete all emotes that no longer exist Log.debug("Removing emotes names from DB"); checkInterrupted(); applyBatch(batch); mSyncResult.stats.numDeletes += batch.size(); Log.info("Removed " + Integer.toString(batch.size()) + " emotes names from DB"); } // Generate batch insert checkInterrupted(); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); String baseDir = mBaseDir.getAbsolutePath() + File.separator; for (EmoteImage emote : emotes) { for (String name : emote.getNames()) { Log.debug("Adding " + name + " to DB"); batch.add(ContentProviderOperation.newInsert(EmotesContract.Emote.CONTENT_URI) .withValue(EmotesContract.Emote.COLUMN_NAME, name) .withValue(EmotesContract.Emote.COLUMN_NSFW, (emote.isNsfw() ? 1 : 0)) .withValue(EmotesContract.Emote.COLUMN_APNG, (emote.isApng() ? 1 : 0)) .withValue(EmotesContract.Emote.COLUMN_IMAGE, baseDir + emote.getImage()) .withValue(EmotesContract.Emote.COLUMN_HASH, emote.getHash()) .withValue(EmotesContract.Emote.COLUMN_INDEX, emote.getIndex()) .withValue(EmotesContract.Emote.COLUMN_DELAY, emote.getDelay()) .withValue(EmotesContract.Emote.COLUMN_SUBREDDIT, emote.getSubreddit()).build()); } } Log.debug("Adding emotes names to DB"); checkInterrupted(); applyBatch(batch); mSyncResult.stats.numInserts += batch.size(); Log.info("Added " + Integer.toString(batch.size()) + " emotes names to DB"); }
From source file:com.jaxio.celerio.output.FileTracker.java
public HashSet<FileMetaData> deleteGeneratedFileIfIdentical(File projectDir, List<String> excludedPatterns) throws IOException { SCMStatus scmStatus = getSCMStatus(projectDir); HashSet<FileMetaData> scmFiles = newHashSet(); HashSet<FileMetaData> deletedFiles = newHashSet(); HashSet<FileMetaData> notFoundFiles = newHashSet(); File xmlFileMetaDatas = new File(projectDir, getFilename()); if (!xmlFileMetaDatas.exists()) { info("CANNOT FIND FILE TRACKER METADATA " + xmlFileMetaDatas.getAbsolutePath()); return deletedFiles; }// w w w .j av a2s . co m HashMap<String, FileMetaData> filesToScan = loadFromProjectDir(projectDir); for (Entry<String, FileMetaData> entry : filesToScan.entrySet()) { FileMetaData oldFmd = entry.getValue(); String relativePath = entry.getKey(); File oldFile = new File(projectDir, relativePath); if (oldFile.exists()) { if (scmStatus.isUnderSCM(relativePath)) { info("skip delete (file now under SCM): " + entry.getKey()); scmFiles.add(oldFmd); continue; } if (oldFmd.isBootstrapFile()) { info("skip file generated during bootstrap: " + entry.getKey()); continue; } FileMetaData recentFmd = new FileMetaData(null, null, entry.getKey(), oldFile); // info("recent: " +recentFmd.toString()); // info("old: " + oldFmd.toString()); if (oldFmd.equals(recentFmd)) { if (mustExcludeFile(relativePath, excludedPatterns)) { info("skip delete (present in excludedFiles): " + entry.getKey()); } else { info("delete: " + entry.getKey()); oldFile.delete(); ioUtil.pruneEmptyDirs(oldFile); deletedFiles.add(recentFmd); } } else { info("skip delete (potential user modifications): " + entry.getKey()); } } else { info("skip delete (no longer exists): " + entry.getKey()); notFoundFiles.add(oldFmd); } } for (FileMetaData fmd : scmFiles) { filesToScan.remove(fmd.getFileRelativePath()); } for (FileMetaData fmd : deletedFiles) { filesToScan.remove(fmd.getFileRelativePath()); } for (FileMetaData fmd : notFoundFiles) { filesToScan.remove(fmd.getFileRelativePath()); } info("rewrite file tracker metadata: " + getFilename()); saveToProjectDir(filesToScan, projectDir); return deletedFiles; }
From source file:pe.gob.mef.gescon.web.ui.ConsultaMB.java
public void reporte() { HashMap parametrosReporte = new HashMap(); HashMap parametrosJasper = new HashMap(); File archivo;/* w ww . ja v a 2 s. c o m*/ List<HashMap<String, Object>> listaDatosReporte; HashMap filter = new HashMap(); try { filter.put("fCategoria", this.getCategoriesFilter()); filter.put("fFromDate", this.getFechaInicio()); filter.put("fToDate", this.getFechaFin()); filter.put("fType", this.getTypesFilter()); if (StringUtils.isNotBlank(this.getSearchText())) { HashMap map = Indexador.search(this.getSearchText()); filter.put("fCodesBL", (String) map.get("codesBL")); filter.put("fCodesPR", (String) map.get("codesPR")); filter.put("fCodesC", (String) map.get("codesC")); } else { filter.remove("fCodesBL"); filter.remove("fCodesPR"); filter.remove("fCodesC"); } filter.put("order", this.getOrdenpor()); ConsultaService service = (ConsultaService) ServiceFinder.findBean("ConsultaService"); listaDatosReporte = service.listarReporte(filter); archivo = new File(JSFUtils.getServletContext().getRealPath("/pages/reportes/reporteConsulta.jasper")); String rutaImagen = JSFUtils.getServletContext().getRealPath("/resources/images/logogescon2.png"); String rutaBanner = JSFUtils.getServletContext().getRealPath("/resources/images/banner.png"); parametrosJasper.put("P_IMAGEN", rutaImagen); parametrosJasper.put("P_BANNER", rutaBanner); List<HashMap<String, Object>> listaDatos = listaDatosReporte; JRDataSource fuenteDatos = new JRBeanCollectionDataSource(listaDatos); JasperReport reporteJasper = (JasperReport) JRLoader.loadObjectFromFile(archivo.getPath()); //JasperReport reporteJasper = JasperCompileManager.compileReport(archivo.getPath()); JasperPrint documentoPdf = JasperFillManager.fillReport(reporteJasper, parametrosJasper, fuenteDatos); HttpServletResponse response = JSFUtils.getResponse(); if (documentoPdf != null) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=" + "ReporteConsulta" + ".pdf"); ServletOutputStream ouputStream = response.getOutputStream(); JRPdfExporter pdfExporter = new JRPdfExporter(); pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, documentoPdf); pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream); pdfExporter.exportReport(); FacesContext.getCurrentInstance().responseComplete(); } } catch (JRException e) { e.getMessage(); e.printStackTrace(); } catch (IOException e) { e.getMessage(); e.printStackTrace(); } }
From source file:com.microsoft.azure.storage.table.CEKReturn.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in JSON format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * /* w w w .j a va 2 s . com*/ * @param parser * The <code>JsonParser</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param options * A {@link TableRequestOptions} object that specifies execution options such as retry policy and timeout * settings for the operation. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * @throws IOException * if an error occurs while accessing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. * @throws JsonParseException * if an error occurs while parsing the stream. */ private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser, final Class<T> clazzType, HashMap<String, PropertyPair> classProperties, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws JsonParseException, IOException, StorageException, InstantiationException, IllegalAccessException { final TableResult res = new TableResult(); HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>(); if (!parser.hasCurrentToken()) { parser.nextToken(); } JsonUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); // get all metadata, if present while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) { final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length()); // get the value token parser.nextToken(); if (name.equals(ODataConstants.ETAG)) { String etag = parser.getValueAsString(); res.setEtag(etag); } // get the key token parser.nextToken(); } if (resolver == null && clazzType == null) { return res; } // get object properties while (parser.getCurrentToken() != JsonToken.END_OBJECT) { String key = Constants.EMPTY_STRING; String val = Constants.EMPTY_STRING; EdmType edmType = null; // checks if this property is preceded by an OData property type annotation if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata && parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) { parser.nextToken(); edmType = EdmType.parse(parser.getValueAsString()); parser.nextValue(); key = parser.getCurrentName(); val = parser.getValueAsString(); } else { key = parser.getCurrentName(); parser.nextToken(); val = parser.getValueAsString(); edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString()); } final EntityProperty newProp = new EntityProperty(val, edmType); newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); properties.put(key, newProp); parser.nextToken(); } String partitionKey = null; String rowKey = null; Date timestamp = null; String etag = null; // Remove core properties from map and set individually EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY); if (tempProp != null) { partitionKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.ROW_KEY); if (tempProp != null) { rowKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.TIMESTAMP); if (tempProp != null) { tempProp.setDateBackwardCompatibility(false); timestamp = tempProp.getValueAsDate(); if (res.getEtag() == null) { etag = getETagFromTimestamp(tempProp.getValueAsString()); res.setEtag(etag); } } // Deserialize the metadata property value to get the names of encrypted properties so that they can be parsed correctly below. Key cek = null; Boolean isJavaV1 = true; EncryptionData encryptionData = new EncryptionData(); HashSet<String> encryptedPropertyDetailsSet = null; if (options.getEncryptionPolicy() != null) { EntityProperty propertyDetailsProperty = properties .get(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS); EntityProperty keyProperty = properties.get(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS); if (propertyDetailsProperty != null && !propertyDetailsProperty.getIsNull() && keyProperty != null && !keyProperty.getIsNull()) { // Decrypt the metadata property value to get the names of encrypted properties. CEKReturn cekReturn = options.getEncryptionPolicy().decryptMetadataAndReturnCEK(partitionKey, rowKey, keyProperty, propertyDetailsProperty, encryptionData); cek = cekReturn.key; isJavaV1 = cekReturn.isJavaV1; properties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS, propertyDetailsProperty); encryptedPropertyDetailsSet = parsePropertyDetails(propertyDetailsProperty); } else { if (options.requireEncryption() != null && options.requireEncryption()) { throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null); } } } // do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && (options.getPropertyResolver() != null || clazzType != null)) { for (final Entry<String, EntityProperty> property : properties.entrySet()) { if (Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS.equals(property.getKey())) { // This and the following check are required because in JSON no-metadata, the type information for // the properties are not returned and users are not expected to provide a type for them. So based // on how the user defined property resolvers treat unknown properties, we might get unexpected results. final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.STRING); properties.put(property.getKey(), newProp); } else if (Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS .equals(property.getKey())) { if (options.getEncryptionPolicy() == null) { final EntityProperty newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.BINARY); properties.put(property.getKey(), newProp); } } else if (options.getPropertyResolver() != null) { final String key = property.getKey(); final String value = property.getValue().getValueAsString(); EdmType edmType; // try to use the property resolver to get the type try { edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value); } catch (Exception e) { throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW, Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } // try to create a new entity property using the returned type try { final EntityProperty newProp = new EntityProperty(value, isEncrypted(encryptedPropertyDetailsSet, key) ? EdmType.BINARY : edmType); newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); properties.put(property.getKey(), newProp); } catch (IllegalArgumentException e) { throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE, String.format(SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType), Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } } else if (clazzType != null) { if (classProperties == null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } PropertyPair propPair = classProperties.get(property.getKey()); if (propPair != null) { EntityProperty newProp; if (isEncrypted(encryptedPropertyDetailsSet, property.getKey())) { newProp = new EntityProperty(property.getValue().getValueAsString(), EdmType.BINARY); } else { newProp = new EntityProperty(property.getValue().getValueAsString(), propPair.type); } newProp.setDateBackwardCompatibility(options.getDateBackwardCompatibility()); properties.put(property.getKey(), newProp); } } } } // set the result properties, now that they are appropriately parsed if (options.getEncryptionPolicy() != null && cek != null) { // decrypt properties, if necessary properties = options.getEncryptionPolicy().decryptEntity(properties, encryptedPropertyDetailsSet, partitionKey, rowKey, cek, encryptionData, isJavaV1); } res.setProperties(properties); // use resolver if provided, else create entity based on clazz type if (resolver != null) { res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, properties, res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(properties, opContext); res.setResult(entity); } return res; }
From source file:it.cnr.icar.eric.client.ui.thin.RegistryObjectBean.java
@SuppressWarnings("unused") private Map<?, ?> removeUnwantedTypes(Map<?, ?> refLookup) { HashMap<Object, Object> refLookupCopy = new HashMap<Object, Object>(refLookup); Set<?> keys = refLookup.keySet(); Iterator<?> keyItr = keys.iterator(); while (keyItr.hasNext()) { synchronized (this) { String key = (String) keyItr.next(); if (key.indexOf("Association\n") != -1) { refLookupCopy.remove(key); }//from w w w . j ava 2s . com } } return refLookupCopy; }
From source file:uk.ac.horizon.ug.exploding.client.Client.java
/** poll * @throws JSONException *///from w w w. j av a2 s . com public List<Message> poll(int toFollow) throws IOException { log("poll"); Message msg = new Message(); msg.setSeqNo(seqNo++); msg.setType(MessageType.POLL.name()); if (toFollow > 0) msg.setToFollow(toFollow); //msg.setToFollow(0); synchronized (ackSeqs) { int ackSeqsInt[] = new int[ackSeqs.size()]; for (int i = 0; i < ackSeqs.size(); i++) ackSeqsInt[i] = ackSeqs.get(i); ackSeqs.clear(); msg.setAckSeqs(ackSeqsInt); } QueuedMessage qm = new QueuedMessage(); qm.message = msg; List<Message> messages = sendQueuedMessageInternal(qm); if (messages == null) { if (qm.messageStatus != MessageStatusType.OK) throw new IOException(qm.errorMessage != null ? qm.errorMessage : qm.messageStatus.toString()); return messages; } Set<String> changedTypes = new HashSet<String>(); synchronized (facts) { for (Message message : messages) { // selective ack if (message.getSeqNo() > 0) { synchronized (ackSeqs) { ackSeqs.add(message.getSeqNo()); } } MessageType messageType = MessageType.valueOf(message.getType()); if (messageType == MessageType.FACT_EX || messageType == MessageType.FACT_ADD) { Object val = message.getNewVal(); String typeName = val.getClass().getName(); HashMap<Object, Object> typeFacts = facts.get(typeName); if (typeFacts == null) { typeFacts = new HashMap<Object, Object>(); facts.put(typeName, typeFacts); } typeFacts.put(getFactID(val), val); Log.d(TAG, "Add fact " + val); log("addFact", "newVal", val.toString()); if (!changedTypes.contains(typeName)) changedTypes.add(typeName); checkSpecialCaseUpdates(val); } else if (messageType == MessageType.FACT_UPD || messageType == MessageType.FACT_DEL) { Object val = message.getOldVal(); String typeName = val.getClass().getName(); HashMap<Object, Object> typeFacts = facts.get(typeName); if (typeFacts == null) { typeFacts = new HashMap<Object, Object>(); facts.put(typeName, typeFacts); } Object key = getFactID(val); boolean found = typeFacts.containsKey(key); if (found) { typeFacts.remove(key); Log.i(TAG, "Removing/update old fact " + val); if (messageType == MessageType.FACT_DEL) log("deleteFact", "oldVal", val.toString()); if (!changedTypes.contains(typeName)) changedTypes.add(typeName); } else { log("deleteFact.notfound", "oldVal", val.toString()); Log.i(TAG, "Did not find old fact to remove: " + val); } if (messageType == MessageType.FACT_UPD) { val = message.getNewVal(); log("updateFact", "newVal", val.toString()); if (!val.getClass().getName().equals(typeName)) Log.e(TAG, "Nominal Update from class " + typeName + " to " + val.getClass().getName()); typeFacts = facts.get(typeName); if (typeFacts == null) { typeFacts = new HashMap<Object, Object>(); facts.put(typeName, typeFacts); } Object newKey = getFactID(val); if (!key.equals(newKey)) Log.e(TAG, "Nominal Update from ID " + key + " to " + newKey + " for " + val); typeFacts.put(newKey, val); Log.i(TAG, "Update new fact " + val); if (!changedTypes.contains(typeName)) changedTypes.add(typeName); checkSpecialCaseUpdates(val); } } } } // BackgroundThread.cachedStateChanged(this, changedTypes); return messages; }
From source file:com.frostwire.gui.components.slides.YouTubeStreamURLExtractor.java
public String getYoutubeStreamURL() throws Exception { this.possibleconverts = new HashMap<DestinationFormat, ArrayList<Info>>(); String decryptedLink = null;/*from www . j a v a 2s. c om*/ String param = youtubePageUrl; String parameter = param.toString().replace("watch#!v", "watch?v"); parameter = parameter.replaceFirst("(verify_age\\?next_url=\\/?)", ""); parameter = parameter.replaceFirst("(%3Fv%3D)", "?v="); parameter = parameter.replaceFirst("(watch\\?.*?v)", "watch?v"); parameter = parameter.replaceFirst("/embed/", "/watch?v="); parameter = parameter.replaceFirst("https", "http"); Browser br = new Browser(); br.setFollowRedirects(true); br.setCookiesExclusive(true); br.clearCookies("youtube.com"); if (parameter.contains("watch#")) { parameter = parameter.replace("watch#", "watch?"); } if (parameter.contains("v/")) { String id = new Regex(parameter, "v/([a-z\\-_A-Z0-9]+)").getMatch(0); if (id != null) parameter = "http://www.youtube.com/watch?v=" + id; } boolean prem = false; try { final HashMap<Integer, String[]> LinksFound = this.getLinks(parameter, prem, br, 0); String error = br.getRegex( "<div id=\"unavailable\\-message\" class=\"\">[\t\n\r ]+<span class=\"yt\\-alert\\-vertical\\-trick\"></span>[\t\n\r ]+<div class=\"yt\\-alert\\-message\">([^<>\"]*?)</div>") .getMatch(0); if (error == null) error = br.getRegex("<div class=\"yt\\-alert\\-message\">(.*?)</div>").getMatch(0); if ((LinksFound == null || LinksFound.isEmpty()) && error != null) { //logger.info("Video unavailable: " + parameter); //logger.info("Reason: " + error.trim()); return decryptedLink; } if (LinksFound == null || LinksFound.isEmpty()) { if (br.getURL().toLowerCase(Locale.getDefault()).indexOf("youtube.com/get_video_info?") != -1 && !prem) { throw new IOException("DecrypterException.ACCOUNT"); } throw new IOException("Video no longer available"); } /* First get the filename */ String YT_FILENAME = ""; if (LinksFound.containsKey(-1)) { YT_FILENAME = LinksFound.get(-1)[0]; LinksFound.remove(-1); } final boolean fast = false;//cfg.getBooleanProperty("FAST_CHECK2", false); //final boolean mp3 = cfg.getBooleanProperty("ALLOW_MP3", true); final boolean mp4 = true;//cfg.getBooleanProperty("ALLOW_MP4", true); //final boolean webm = cfg.getBooleanProperty("ALLOW_WEBM", true); //final boolean flv = cfg.getBooleanProperty("ALLOW_FLV", true); //final boolean threegp = cfg.getBooleanProperty("ALLOW_3GP", true); /* http://en.wikipedia.org/wiki/YouTube */ final HashMap<Integer, Object[]> ytVideo = new HashMap<Integer, Object[]>() { /** * */ private static final long serialVersionUID = -3028718522449785181L; { // **** FLV ***** // if (mp3) { // this.put(0, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" }); // this.put(5, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Stereo" }); // this.put(6, new Object[] { DestinationFormat.VIDEOFLV, "H.263", "MP3", "Mono" }); // } // if (flv) { // this.put(34, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" }); // this.put(35, new Object[] { DestinationFormat.VIDEOFLV, "H.264", "AAC", "Stereo" }); // } // **** 3GP ***** // if (threegp) { // this.put(13, new Object[] { DestinationFormat.VIDEO3GP, "H.263", "AMR", "Mono" }); // this.put(17, new Object[] { DestinationFormat.VIDEO3GP, "H.264", "AAC", "Stereo" }); // } // **** MP4 ***** if (mp4) { this.put(18, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" }); this.put(22, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" }); this.put(37, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" }); //this.put(38, new Object[] { DestinationFormat.VIDEOMP4, "H.264", "AAC", "Stereo" }); } // **** WebM ***** // if (webm) { // this.put(43, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" }); // this.put(45, new Object[] { DestinationFormat.VIDEOWEBM, "VP8", "Vorbis", "Stereo" }); // } } }; /* check for wished formats first */ String dlLink = ""; String vQuality = ""; DestinationFormat cMode = null; for (final Integer format : LinksFound.keySet()) { if (ytVideo.containsKey(format)) { cMode = (DestinationFormat) ytVideo.get(format)[0]; vQuality = "(" + LinksFound.get(format)[1] + "_" + ytVideo.get(format)[1] + "-" + ytVideo.get(format)[2] + ")"; } else { cMode = DestinationFormat.UNKNOWN; vQuality = "(" + LinksFound.get(format)[1] + "_" + format + ")"; /* * we do not want to download unknown formats at the * moment */ continue; } dlLink = LinksFound.get(format)[0]; try { if (fast) { this.addtopos(cMode, dlLink, 0, vQuality, format); } else if (br.openGetConnection(dlLink).getResponseCode() == 200) { this.addtopos(cMode, dlLink, br.getHttpConnection().getLongContentLength(), vQuality, format); } } catch (final Throwable e) { LOG.error("Error in youtube decrypt logic", e); } finally { try { br.getHttpConnection().disconnect(); } catch (final Throwable e) { } } } int lastFmt = 0; for (final Entry<DestinationFormat, ArrayList<Info>> next : this.possibleconverts.entrySet()) { final DestinationFormat convertTo = next.getKey(); for (final Info info : next.getValue()) { final HttpDownloadLink thislink = new HttpDownloadLink(info.link); //thislink.setBrowserUrl(parameter); //thislink.setFinalFileName(YT_FILENAME + info.desc + convertTo.getExtFirst()); thislink.setSize(info.size); String name = null; if (convertTo != DestinationFormat.AUDIOMP3) { name = YT_FILENAME + info.desc + convertTo.getExtFirst(); name = FileUtils.getValidFileName(name); thislink.setFileName(name); } else { /* * because demuxer will fail when mp3 file already * exists */ //name = YT_FILENAME + info.desc + ".tmp"; //thislink.setProperty("name", name); } //thislink.setProperty("convertto", convertTo.name()); //thislink.setProperty("videolink", parameter); //thislink.setProperty("valid", true); //thislink.setProperty("fmtNew", info.fmt); //thislink.setProperty("LINKDUPEID", name); if (lastFmt < info.fmt) { decryptedLink = thislink.getUrl(); } } } } catch (final IOException e) { br.getHttpConnection().disconnect(); //logger.log(java.util.logging.Level.SEVERE, "Exception occurred", e); return null; } return decryptedLink; }
From source file:pe.gob.mef.gescon.web.ui.ConsultaMB.java
public void filtrar(ActionEvent event) { HashMap filter = new HashMap(); try {/*from www .j ava 2s . com*/ filter.put("fCategoria", this.getCategoriesFilter()); filter.put("fFromDate", this.getFechaInicio()); filter.put("fToDate", this.getFechaFin()); filter.put("fType", this.getTypesFilter()); if (StringUtils.isNotBlank(this.getSearchText())) { HashMap map = Indexador.search(this.getSearchText()); filter.put("fCodesBL", (String) map.get("codesBL")); filter.put("fCodesPR", (String) map.get("codesPR")); filter.put("fCodesC", (String) map.get("codesC")); filter.put("fText", this.getSearchText().trim()); } else { filter.remove("fCodesBL"); filter.remove("fCodesPR"); filter.remove("fCodesC"); filter.remove("fText"); } filter.put("order", this.getOrdenpor()); ConsultaService service = (ConsultaService) ServiceFinder.findBean("ConsultaService"); this.setListaConsulta(service.getQueryFilter(filter)); } catch (Exception e) { e.getMessage(); e.printStackTrace(); } }