List of usage examples for java.util LinkedHashMap size
int size();
From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYBarChart.java
/** * A line chart creator basing on series made up two values per row. More series, independing * one from the other are supported./*w ww .ja va 2 s. c o m*/ * * @param chartValues - a hashmap containing as keys the name of the series and as values the * double[][] representing the data. Important: the data matrix has to be passed as two * rows (not two columns) * @param barwidth */ public JGrassXYBarChart(LinkedHashMap<String, double[][]> chartValues, double barwidth) { chartSeries = new XYSeries[chartValues.size()]; // extrapolate the data from the Hashmap and convert it to a XYSeries // Collection Iterator<String> it = chartValues.keySet().iterator(); int count = 0; while (it.hasNext()) { String key = it.next(); double[][] values = chartValues.get(key); chartSeries[count] = new XYSeries(key); for (int i = 0; i < values[0].length; i++) { // important: the data matrix has to be passed as two rows (not // two columns) double val = values[1][i]; if (isNovalue(val)) continue; chartSeries[count].add(values[0][i], val); } count++; } barDataset = new XYSeriesCollection(); for (int i = 0; i < chartSeries.length; i++) { barDataset.addSeries(chartSeries[i]); } dataset = new XYBarDataset(barDataset, barwidth); }
From source file:ru.crazycoder.plugins.tabdir.SameFilenameTitleProvider.java
private String titleWithDiffs(final Project project, final VirtualFile file, final FolderConfiguration configuration) { Collection<VirtualFile> similarFiles = FileBasedIndex.getInstance().getContainingFiles(FilenameIndex.NAME, file.getName(), ProjectScope.getProjectScope(project)); if (similarFiles.size() < 2) { return file.getPresentableName(); }/*from w w w . ja va 2 s. c o m*/ if (configuration.isRemoveDuplicates()) { LinkedHashMap<String, Set<String>> prefixesWithNeighbours = calculatePrefixesWithoutDuplicates(file, similarFiles); if (prefixesWithNeighbours.size() > 0) { return TitleFormatter.format(prefixesWithNeighbours, file.getPresentableName(), configuration); } } else { List<String> prefixes = calculatePrefixes(file, similarFiles); if (prefixes.size() > 0) { return TitleFormatter.format(prefixes, file.getPresentableName(), configuration); } } return null; }
From source file:com.grarak.kerneladiutor.utils.database.ProfileDB.java
public void putProfile(String name, LinkedHashMap<String, String> commands) { try {// w ww . j a va 2 s . c o m JSONObject items = new JSONObject(); items.put("name", name); JSONArray commandArray = new JSONArray(); for (int i = 0; i < commands.size(); i++) { JSONObject item = new JSONObject(); item.put("path", commands.keySet().toArray()[i]); item.put("command", commands.values().toArray()[i]); commandArray.put(item); } items.put("commands", commandArray); items.put("id", UUID.randomUUID()); putItem(items); } catch (JSONException e) { e.printStackTrace(); } }
From source file:edu.csun.ecs.cs.multitouchj.ui.event.ObjectEventManager.java
protected void handleEvent() { setRunning(true);//from w ww .j av a2s .c o m for (ObjectType objectType : ObjectType.values()) { eventsCleaned.put(objectType, true); } while (isRunning()) { synchronized (activeObjects) { // check for "started" or "moved" if (isUpdated()) { for (ObjectType objectType : activeObjects.keySet()) { LinkedHashMap<Integer, ObjectObserverEvent> objects = activeObjects.get(objectType); if (objects.size() > 0) { LinkedList<ObjectObserverEvent> ooes = new LinkedList<ObjectObserverEvent>( objects.values()); ObjectEvent objectEvent = null; if (ObjectType.Floated.equals(objectType)) { objectEvent = new FloatEvent(this, ooes.getLast(), ooes, (eventsCleaned.get(objectType)) ? ObjectEvent.Status.Started : ObjectEvent.Status.Moved); } else { objectEvent = new TouchEvent(this, ooes.getLast(), ooes, (eventsCleaned.get(objectType)) ? ObjectEvent.Status.Started : ObjectEvent.Status.Moved); } notifyEventListeners(objectEvent); eventsCleaned.put(objectType, false); } } setUpdated(false); } // check for "ended" for (ObjectType objectType : activeObjects.keySet()) { LinkedHashMap<Integer, ObjectObserverEvent> objects = activeObjects.get(objectType); if (objects.size() > 0) { LinkedList<ObjectObserverEvent> ooes = new LinkedList<ObjectObserverEvent>( objects.values()); // check for ones expired long currentTime = (new Date()).getTime(); LinkedList<Integer> deletedIds = new LinkedList<Integer>(); for (ObjectObserverEvent ooe : ooes) { if ((currentTime - ooe.getTime()) >= CLEAN_UP_TIME) { deletedIds.add(ooe.getId()); } } for (int deletedId : deletedIds) { objects.remove(deletedId); } // check if all expired if (objects.size() == 0) { ObjectEvent objectEvent = null; if (ObjectType.Floated.equals(objectType)) { objectEvent = new FloatEvent(this, ooes.getLast(), ooes, ObjectEvent.Status.Ended); } else { objectEvent = new TouchEvent(this, ooes.getLast(), ooes, ObjectEvent.Status.Ended); } notifyEventListeners(objectEvent); eventsCleaned.put(objectType, true); } } } } try { Thread.sleep(15); } catch (Exception exception) { } } }
From source file:com.ikanow.infinit.e.harvest.extraction.document.file.XmlToMetadataParser.java
static public LinkedHashMap<String, Object> convertJsonObjectToLinkedHashMap(JSONObject json, boolean bHtmlUnescape) { LinkedHashMap<String, Object> list = new LinkedHashMap<String, Object>(); String[] names = JSONObject.getNames(json); if (null == names) { // (empty object) return null; }// w w w .j a v a2s.co m for (String name : names) { JSONObject rec = null; JSONArray jarray = null; try { jarray = json.getJSONArray(name); list.put(name, handleJsonArray(jarray, bHtmlUnescape)); } catch (JSONException e2) { try { rec = json.getJSONObject(name); list.put(name, convertJsonObjectToLinkedHashMap(rec, bHtmlUnescape)); } catch (JSONException e) { try { if (bHtmlUnescape) { list.put(name, StringEscapeUtils.unescapeHtml(json.getString(name))); } else { list.put(name, json.getString(name)); } } catch (JSONException e1) { e1.printStackTrace(); } } } } if (list.size() > 0) { return list; } return null; }
From source file:com.datatorrent.stram.engine.OperatorThread.java
private void setupNode(OperatorDeployInfo ndi) { //failedNodes.remove(ndi.id); //final Node<?> node = nodes.get(ndi.id); node.setup(node.context);/*from ww w . j a v a2 s . c o m*/ /* setup context for all the input ports */ LinkedHashMap<String, PortContextPair<InputPort<?>>> inputPorts = node .getPortMappingDescriptor().inputPorts; LinkedHashMap<String, Operators.PortContextPair<InputPort<?>>> newInputPorts = new LinkedHashMap<>( inputPorts.size()); for (OperatorDeployInfo.InputDeployInfo idi : ndi.inputs) { InputPort<?> port = inputPorts.get(idi.portName).component; PortContext context = new PortContext(idi.contextAttributes, node.context); newInputPorts.put(idi.portName, new PortContextPair<>(port, context)); port.setup(context); } inputPorts.putAll(newInputPorts); /* setup context for all the output ports */ LinkedHashMap<String, PortContextPair<OutputPort<?>>> outputPorts = node .getPortMappingDescriptor().outputPorts; LinkedHashMap<String, PortContextPair<OutputPort<?>>> newOutputPorts = new LinkedHashMap<>( outputPorts.size()); for (OperatorDeployInfo.OutputDeployInfo odi : ndi.outputs) { OutputPort<?> port = outputPorts.get(odi.portName).component; PortContext context = new PortContext(odi.contextAttributes, node.context); newOutputPorts.put(odi.portName, new PortContextPair<>(port, context)); port.setup(context); } outputPorts.putAll(newOutputPorts); /* This introduces need for synchronization on processNodeRequest which was solved by adding deleted field in StramToNodeRequest */ cContext.processNodeRequests(false); node.activate(); cContext.publish(new ContainerEvent.NodeActivationEvent(node)); }
From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java
@Override public void onStart(Intent intent, final int startId) { super.onStart(intent, startId); if (!sending.compareAndSet(false, true)) { Log.i(TAG, "Send already in progress, skipping intent"); }//from ww w .j a v a 2s . c o m final TiAnalyticsService self = this; Thread t = new Thread(new Runnable() { public void run() { Log.i(TAG, "Analytics Service Started"); try { if (connectivityManager == null) { Log.w(TAG, "Connectivity manager not available."); stopSelf(startId); return; } TiAnalyticsModel model = new TiAnalyticsModel(self); if (!model.hasEvents()) { Log.d(TAG, "No events to send.", Log.DEBUG_MODE); stopSelf(startId); return; } while (model.hasEvents()) { if (canSend()) { LinkedHashMap<Integer, JSONObject> events = model .getEventsAsJSON(BUCKET_SIZE_FAST_NETWORK); int len = events.size(); int[] eventIds = new int[len]; Iterator<Integer> keys = events.keySet().iterator(); JSONArray records = new JSONArray(); // build up data to send and records to delete on success for (int i = 0; i < len; i++) { int id = keys.next(); // ids are kept even on error JSON to prevent unrestrained growth // and a queue blocked by bad records. eventIds[i] = id; records.put(events.get(id)); if (Log.isDebugModeEnabled()) { JSONObject obj = events.get(id); Log.d(TAG, "Sending event: type = " + obj.getString("type") + ", timestamp = " + obj.getString("ts")); } } boolean deleteEvents = true; if (records.length() > 0) { if (Log.isDebugModeEnabled()) { Log.d(TAG, "Sending " + records.length() + " analytics events."); } try { String jsonData = records.toString() + "\n"; String postUrl = TiApplication.getInstance() == null ? ANALYTICS_URL : ANALYTICS_URL + TiApplication.getInstance().getAppGUID(); HttpPost httpPost = new HttpPost(postUrl); StringEntity entity = new StringEntity(jsonData); entity.setContentType("text/json"); httpPost.setEntity(entity); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); //TODO use property //HttpConnectionParams.setSoTimeout(httpParams, 15000); //TODO use property HttpClient client = new DefaultHttpClient(httpParams); ResponseHandler<String> responseHandler = new BasicResponseHandler(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); @SuppressWarnings("unused") String response = client.execute(httpPost, responseHandler); } catch (Throwable t) { Log.e(TAG, "Error posting events: " + t.getMessage(), t); deleteEvents = false; records = null; break; } } records = null; if (deleteEvents) { model.deleteEvents(eventIds); } events.clear(); } else { Log.w(TAG, "Network unavailable, can't send analytics"); //TODO reset alarm? break; } } Log.i(TAG, "Stopping Analytics Service"); stopSelf(startId); } catch (Throwable t) { Log.e(TAG, "Unhandled exception in analytics thread: ", t); stopSelf(startId); } finally { if (!sending.compareAndSet(true, false)) { Log.w(TAG, "Expected to be in a sending state. Sending was already false.", Log.DEBUG_MODE); } } } }); t.setPriority(Thread.MIN_PRIORITY); t.start(); }
From source file:org.deri.iris.rules.compiler.RuleCompiler.java
/** * Compile a rule body (or query). The literals are compiled in the order * given. However, if one literal can not be compiled, because one or more * of its variables are not bound from the proceeding literal, then it is * skipped an re-tried later.//from ww w. ja v a2 s . c o m * * @param bodyLiterals The list of literals to compile * @return The compiled rule elements. * @throws EvaluationException If a rule construct can not be compiled (e.g. * a built-in has constructed terms) */ private LinkedHashMap<RuleElement, ILiteral> compileBody(Collection<ILiteral> bodyLiterals) throws EvaluationException { List<ILiteral> literals = new ArrayList<ILiteral>(bodyLiterals); LinkedHashMap<RuleElement, ILiteral> elements = new LinkedHashMap<RuleElement, ILiteral>(); List<IVariable> previousVariables = new ArrayList<IVariable>(); while (elements.size() < bodyLiterals.size()) { EvaluationException lastException = null; boolean added = false; for (int l = 0; l < literals.size(); ++l) { ILiteral literal = literals.get(l); IAtom atom = literal.getAtom(); boolean positive = literal.isPositive(); RuleElement element; try { if (atom instanceof IBuiltinAtom) { IBuiltinAtom builtinAtom = (IBuiltinAtom) atom; boolean constructedTerms = false; for (ITerm term : atom.getTuple()) { if (term instanceof IConstructedTerm) { constructedTerms = true; break; } } if (constructedTerms) element = new BuiltinForConstructedTermArguments(previousVariables, builtinAtom, positive, mEquivalentTerms, mConfiguration); else element = new Builtin(atom.getPredicate(), atom.getTuple(), previousVariables, builtinAtom, positive, mEquivalentTerms, mConfiguration); } else { IPredicate predicate = atom.getPredicate(); IRelation relation = mFacts.get(predicate); ITuple viewCriteria = atom.getTuple(); if (positive) { if (previousVariables.size() == 0) { // First sub-goal element = new FirstSubgoal(predicate, relation, viewCriteria, mEquivalentTerms, mConfiguration); } else { element = new Joiner(previousVariables, predicate, relation, viewCriteria, mEquivalentTerms, mConfiguration.indexFactory, mConfiguration.relationFactory); } } else { // This *is* allowed to be the first literal for // rules such as: // p('a') :- not q('b') // or even: // p('a') :- not q(?X) element = new Differ(previousVariables, relation, viewCriteria, mEquivalentTerms, mConfiguration); } } previousVariables = element.getOutputVariables(); elements.put(element, literals.get(l)); literals.remove(l); added = true; break; } catch (EvaluationException e) { // Oh dear. Store the exception and try the next literal. lastException = e; } } if (!added) { // No more literals, so the last error really was serious. throw lastException; } } if (elements.size() > 0) { RuleElement lastElement = null; for (RuleElement element : elements.keySet()) { lastElement = element; } assert lastElement != null; RuleElement element = new EquivalenceResolver(lastElement.getOutputVariables(), mEquivalentTerms, mConfiguration); elements.put(element, null); } return elements; }
From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYTimeLineChart.java
/** * A line chart creator basing on series made up two values per row. More series, independing * one from the other are supported./*w w w. j av a 2 s . c om*/ * * @param chartValues - a hashmap containing as keys the name of the series and as values the * double[][] representing the data. In this case the x value is assumed to ge a date. * Important: the data matrix has to be passed as two rows (not two columns) */ public JGrassXYTimeLineChart(LinkedHashMap<String, double[][]> chartValues, Class<RegularTimePeriod> timeClass) { try { chartSeries = new TimeSeries[chartValues.size()]; constructor = timeClass.getConstructor(Date.class); final Iterator<String> it = chartValues.keySet().iterator(); int count = 0; while (it.hasNext()) { final String key = it.next(); final double[][] values = chartValues.get(key); chartSeries[count] = new TimeSeries(key, timeClass); for (int i = 0; i < values[0].length; i++) { // important: the data matrix has to be passed as two rows (not // two columns) double val = values[1][i]; if (isNovalue(val)) continue; chartSeries[count].add(constructor.newInstance(new Date((long) values[0][i])), val); } count++; } lineDataset = new TimeSeriesCollection(); for (int i = 0; i < chartSeries.length; i++) { lineDataset.addSeries(chartSeries[i]); } lineDataset.setXPosition(TimePeriodAnchor.MIDDLE); } catch (Exception e) { ChartPlugin.log("ChartPlugin problem", e); //$NON-NLS-1$ } }
From source file:com.smartbear.collab.client.Client.java
public JsonrpcResponse sendRequest(List<JsonrpcCommand> methods) { JsonrpcResponse result = new JsonrpcResponse(); List<LinkedHashMap<String, LinkedHashMap<String, String>>> results = new ArrayList<LinkedHashMap<String, LinkedHashMap<String, String>>>(); ObjectMapper mapper = new ObjectMapper(); try {/*from w ww .j ava 2 s . c o m*/ logger.info(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(methods)); } catch (JsonProcessingException jpe) { } results = target.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(methods, MediaType.APPLICATION_JSON_TYPE), List.class); try { logger.info(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(results)); } catch (JsonProcessingException jpe) { } List<JsonrpcCommandResponse> commandResponses = new ArrayList<JsonrpcCommandResponse>(); for (LinkedHashMap commandResultMap : results) { JsonrpcCommandResponse commandResponse = new JsonrpcCommandResponse(); if (commandResultMap.get("result") != null) { JsonrpcResult commandResult = new JsonrpcResult(); LinkedHashMap<String, String> commandResultValue = (LinkedHashMap<String, String>) commandResultMap .get("result"); if (commandResultValue.size() > 0) { commandResult.setCommand(commandResultValue.keySet().iterator().next()); commandResult.setValue(commandResultValue.get(commandResult.getCommand())); commandResponse.setResult(commandResult); } } if (commandResultMap.get("errors") != null) { List<LinkedHashMap<String, String>> errors = (List<LinkedHashMap<String, String>>) commandResultMap .get("errors"); List<JsonrpcError> jsonrpcErrors = new ArrayList<JsonrpcError>(); for (LinkedHashMap<String, String> error : errors) { JsonrpcError jsonrpcError = new JsonrpcError(); jsonrpcError.setCode(error.get("code")); jsonrpcError.setMessage(error.get("message")); jsonrpcErrors.add(jsonrpcError); } commandResponse.setErrors(jsonrpcErrors); } commandResponses.add(commandResponse); } result.setResults(commandResponses); return result; }