List of usage examples for java.util ArrayList set
public E set(int index, E element)
From source file:org.apache.sysml.yarn.ropt.ResourceOptimizer.java
private static ArrayList<Instruction> annotateMRJobInstructions(ArrayList<Instruction> inst, long cp, long mr) throws DMLRuntimeException { //check for empty instruction lists (e.g., predicates) if (inst == null || !COSTS_MAX_PARALLELISM) return inst; try {//from w ww .j av a 2 s . c om for (int i = 0; i < inst.size(); i++) { Instruction linst = inst.get(i); if (linst instanceof MRJobInstruction) { //copy mr job instruction MRJobResourceInstruction newlinst = new MRJobResourceInstruction((MRJobInstruction) linst); //compute and annotate long maxMemPerNode = (long) YarnClusterAnalyzer.getMaxAllocationBytes(); long nNodes = YarnClusterAnalyzer.getNumNodes(); long totalMem = nNodes * maxMemPerNode; long maxMRTasks = (long) (totalMem - DMLYarnClient.computeMemoryAllocation(cp)) / (long) DMLYarnClient.computeMemoryAllocation(mr); newlinst.setMaxMRTasks(maxMRTasks); //write enhanced instruction back inst.set(i, newlinst); } } } catch (Exception ex) { throw new DMLRuntimeException(ex); } return inst; }
From source file:ch.icclab.cyclops.database.InfluxDBClient.java
public TSDBData getTnovaData(String parameterQuery) { //TODO: connection method url = Loader.getSettings().getInfluxDBSettings().getUrl(); username = Loader.getSettings().getInfluxDBSettings().getUser(); password = Loader.getSettings().getInfluxDBSettings().getPassword(); dbName = Loader.getSettings().getInfluxDBSettings().getDbName(); InfluxDB influxDB = InfluxDBFactory.connect(url, username, password); JSONArray resultArray;//from ww w.j ava2 s . c o m JSONObject resultObj; TSDBData[] dataObj = null; Representation output; ObjectMapper mapper = new ObjectMapper(); int timeIndex = -1; Client client = new Client(Protocol.HTTP); ClientResource cr = new ClientResource(url); Query query = new Query(parameterQuery, dbName); try { resultArray = new JSONArray(influxDB.query(query).getResults()); String sad = resultArray.toString(); if (!resultArray.isNull(0)) { if (resultArray.toString().equals("[{}]")) { //resultArray is an empty JSON string // --> return an empty TSDBData POJO object TSDBData data = new TSDBData(); data.setColumns(new ArrayList<String>()); data.setPoints(new ArrayList<ArrayList<Object>>()); data.setTags(new HashMap()); return data; } else { JSONObject obj = (JSONObject) resultArray.get(0); JSONArray series = (JSONArray) obj.get("series"); //Replace key "values" with key "points" in whole series for (int i = 0; i < series.length(); i++) { String response = series.get(i).toString(); //logger.trace("DATA TSDBData getData(String query): response="+response); response.replaceFirst("values", "points"); response = response.split("values")[0] + "points" + response.split("values")[1]; //logger.trace("DATA TSDBData getData(String query): response="+response); series.put(i, new JSONObject(response)); } dataObj = mapper.readValue(series.toString(), TSDBData[].class); } } //Filter the points to format the date for (int i = 0; i < dataObj.length; i++) { for (int o = 0; o < dataObj[i].getColumns().size(); o++) { if (dataObj[i].getColumns().get(o).equalsIgnoreCase("time")) timeIndex = o; } if (timeIndex > -1) { TreeMap<String, ArrayList> points = new TreeMap<String, ArrayList>(); for (ArrayList point : dataObj[i].getPoints()) { point.set(timeIndex, (String) point.get(timeIndex)); } } } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //TODO new method, parametrization for generate CDR return dataObj[0]; }
From source file:ch.icclab.cyclops.database.InfluxDBClient.java
/** * Fetches the data from InfluxDB via HTTP * The resulting data is a JSON object which is mapped to a POJO class (TSDBData). * <p/>// w w w . j a va 2s . c o m * <p/> * Pseudo Code * 1. Load the login credentials from the configuration object * 2. Create a client instance and set the HTTP protocol, url and auth details * 3. Query the db through its API * 4. Convert the json response into a TSDB java object * * @param parameterQuery A query string * @return TSDBData */ public TSDBData getData(String parameterQuery) { //TODO: connection method url = Loader.getSettings().getInfluxDBSettings().getUrl(); username = Loader.getSettings().getInfluxDBSettings().getUser(); password = Loader.getSettings().getInfluxDBSettings().getPassword(); dbName = Loader.getSettings().getInfluxDBSettings().getDbName(); InfluxDB influxDB = InfluxDBFactory.connect(url, username, password); JSONArray resultArray; JSONObject resultObj; TSDBData[] dataObj = null; Representation output; ObjectMapper mapper = new ObjectMapper(); int timeIndex = -1; Client client = new Client(Protocol.HTTP); ClientResource cr = new ClientResource(url); Query query = new Query(parameterQuery, dbName); try { resultArray = new JSONArray(influxDB.query(query).getResults()); String sad = resultArray.toString(); if (!resultArray.isNull(0)) { if (resultArray.toString().equals("[{}]")) { //resultArray is an empty JSON string // --> return an empty TSDBData POJO object TSDBData data = new TSDBData(); data.setColumns(new ArrayList<String>()); data.setPoints(new ArrayList<ArrayList<Object>>()); data.setTags(new HashMap()); return data; } else { JSONObject obj = (JSONObject) resultArray.get(0); JSONArray series = (JSONArray) obj.get("series"); //Replace key "values" with key "points" in whole series for (int i = 0; i < series.length(); i++) { String response = series.get(i).toString(); //logger.trace("DATA TSDBData getData(String query): response="+response); response.replaceFirst("values", "points"); response = response.split("values")[0] + "points" + response.split("values")[1]; //logger.trace("DATA TSDBData getData(String query): response="+response); series.put(i, new JSONObject(response)); } dataObj = mapper.readValue(series.toString(), TSDBData[].class); } } //Filter the points to format the date for (int i = 0; i < dataObj.length; i++) { for (int o = 0; o < dataObj[i].getColumns().size(); o++) { if (dataObj[i].getColumns().get(o).equalsIgnoreCase("time")) timeIndex = o; } if (timeIndex > -1) { TreeMap<String, ArrayList> points = new TreeMap<String, ArrayList>(); for (ArrayList point : dataObj[i].getPoints()) { point.set(timeIndex, formatDate((String) point.get(timeIndex))); } } } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //TODO new method, parametrization for generate CDR return dataObj[0]; }
From source file:com.clustercontrol.notify.composite.NotifyListComposite.java
/** * ????<BR>//from w w w . j a v a 2 s . c o m * ??????? * * @see com.clustercontrol.notify.action.GetNotify#getNotifyList() */ @Override public void update() { // ??? Map<String, List<NotifyInfo>> dispDataMap = null; ArrayList<ArrayList<Object>> listInput = new ArrayList<ArrayList<Object>>(); if (this.isSelect) { if (this.ownerRoleId == null || this.ownerRoleId.equals("")) { m_log.info("ownerRole=" + ownerRoleId); return; } try { dispDataMap = new GetNotify().getNotifyListByOwnerRole(this.managerName, this.ownerRoleId); } catch (InvalidRole_Exception e) { // ??????? setShowFlg(false); return; } } else { dispDataMap = new GetNotify().getNotifyList(this.managerName); } for (Map.Entry<String, List<NotifyInfo>> entrySet : dispDataMap.entrySet()) { List<NotifyInfo> list = null; list = entrySet.getValue(); if (list == null) { //???????? list = new ArrayList<NotifyInfo>(); } for (NotifyInfo info : list) { ArrayList<Object> a = new ArrayList<Object>(); if (this.isSelect) { a.add(false); //a.add(entrySet.getKey()); a.add(info.isValidFlg()); a.add(info.getNotifyId()); a.add(info.getDescription()); a.add(info.getNotifyType()); } else { a.add(entrySet.getKey()); a.add(info.getNotifyId()); a.add(info.getDescription()); a.add(info.getNotifyType()); a.add(info.isValidFlg()); } a.add(info.getOwnerRoleId()); a.add(info.getCalendarId()); a.add(info.getRegUser()); a.add(info.getRegDate() == null ? null : new Date(info.getRegDate())); a.add(info.getUpdateUser()); a.add(info.getUpdateDate() == null ? null : new Date(info.getUpdateDate())); a.add(null); listInput.add(a); } if (notify == null) { //???????notify?? notify = new ArrayList<NotifyRelationInfo>(); } if (isSelect) { //????????????? String tableNotifyId; boolean flg = false; //?????? Iterator<NotifyRelationInfo> it = notify.iterator(); NotifyRelationInfo nri = null; ArrayList<NotifyRelationInfo> removeNotifyList = new ArrayList<NotifyRelationInfo>(); while (it.hasNext()) { nri = it.next(); nri.setNotifyGroupId(null); flg = false; for (int i = 0; i < list.size(); i++) { NotifyInfo info = list.get(i); ArrayList<Object> objList = listInput.get(i); tableNotifyId = info.getNotifyId(); if (tableNotifyId.equals(nri.getNotifyId())) { objList.set(GetNotifyTableDefineCheckBox.SELECTION, true); flg = true; } objList.set(GetNotifyTableDefineCheckBox.VALID_FLG, info.isValidFlg()); objList.set(GetNotifyTableDefineCheckBox.NOTIFY_ID, info.getNotifyId()); objList.set(GetNotifyTableDefineCheckBox.DESCRIPTION, info.getDescription()); objList.set(GetNotifyTableDefineCheckBox.NOTIFY_TYPE, info.getNotifyType()); objList.set(GetNotifyTableDefineCheckBox.OWNER_ROLE, info.getOwnerRoleId()); objList.set(GetNotifyTableDefineCheckBox.CALENDAR_ID, info.getCalendarId()); objList.set(GetNotifyTableDefineCheckBox.CREATE_USER, info.getRegUser()); objList.set(GetNotifyTableDefineCheckBox.CREATE_TIME, new Date(info.getRegDate())); objList.set(GetNotifyTableDefineCheckBox.UPDATE_USER, info.getUpdateUser()); objList.set(GetNotifyTableDefineCheckBox.UPDATE_TIME, new Date(info.getUpdateDate())); objList.set(GetNotifyTableDefineCheckBox.DUMMY, null); listInput.set(i, objList); } if (!flg) { //??????? removeNotifyList.add(nri); } } notify.removeAll(removeNotifyList); } else { // ? String[] args = { String.valueOf(listInput.size()) }; String message = null; if (this.condition == null) { message = Messages.getString("records", args); } else { message = Messages.getString("filtered.records", args); } this.totalLabel.setText(message); } } // this.tableViewer.setInput(listInput); }
From source file:SE.HtmlGner.java
public ArrayList<String> Get_Noty(int num_of_noty, int n, User user) { DB_controller Db = DB_controller.Get_DB_controller(); Service_Management ser = Service_Management.Get_Serive_Management(); System_manage sys = System_manage.Get_System_manage(); String Filed = ""; String returned = ""; ArrayList<String> html = new ArrayList<>(); html.add(""); html.add(""); if (n == 1) { Filed = Get_filed_Html(14);/* w w w .ja va 2 s . com*/ Customer cus = null; if (user.getType_id() != 5) return html; cus = (Customer) user; cus.Load_Notify(); ArrayList<Notify> MyNotifys = cus.Get_notify(); html.set(0, Integer.toString(MyNotifys.size())); int i; if (MyNotifys.size() == 0) return html; if (num_of_noty == 0 || num_of_noty > MyNotifys.size()) i = MyNotifys.size(); else i = num_of_noty; String used = ""; Request req = null; for (int l = i - 1; l >= 0; l--) { Notify o = MyNotifys.get(l); used = Filed.replace("<muted>2 Minutes Ago", "<muted>" + o.getTime() + " " + sys.Get_this_date(o.getDate_id())); used = used.replace(" subscribed to your newsletter.<br/>", o.getContent() + "<br/>Branch : " + o.getBranch_id()); returned += used; } html.set(1, returned); return html; } if (n == 2) { Filed = Get_filed_Html(10); user.Load_inbox(); ArrayList<Massage> massage = user.getInbox(); int i; if (massage.size() == 0) return html; html.set(0, Integer.toString(massage.size())); System.err.println(massage.size()); if (num_of_noty == 0 || num_of_noty > massage.size()) i = massage.size(); else i = num_of_noty; String used = ""; for (int l = i - 1; l >= 0; l--) { General_massge o = (General_massge) massage.get(l); User u = (User) sys.Search_user_by_id(o.getSender_id()); used = Filed.replace("Dj Sherman", u.getF_name() + " " + u.getL_name()); used = used.replace("index.html#", "ShowMessage.jsp?chars=" + l + "&id=" + o.getId()); used = used.replace("<span class=\"time\">4 hrs.", "<span class=\"time\">" + sys.Get_this_date(o.getDate_id())); used = used.replace("Please, answer asap.", o.getTime()); returned += used; } html.set(1, returned); return html; } return new ArrayList<>(); }
From source file:android.databinding.tool.util.XmlEditor.java
public static String strip(File f, String newTag) throws IOException { ANTLRInputStream inputStream = new ANTLRInputStream(new FileReader(f)); XMLLexer lexer = new XMLLexer(inputStream); CommonTokenStream tokenStream = new CommonTokenStream(lexer); XMLParser parser = new XMLParser(tokenStream); XMLParser.DocumentContext expr = parser.document(); XMLParser.ElementContext root = expr.element(); if (root == null || !"layout".equals(nodeName(root))) { return null; // not a binding layout }/*from w ww . j a va2 s. co m*/ List<? extends ElementContext> childrenOfRoot = elements(root); List<? extends XMLParser.ElementContext> dataNodes = filterNodesByName("data", childrenOfRoot); if (dataNodes.size() > 1) { L.e("Multiple binding data tags in %s. Expecting a maximum of one.", f.getAbsolutePath()); } ArrayList<String> lines = new ArrayList<>(); lines.addAll(FileUtils.readLines(f, "utf-8")); for (android.databinding.parser.XMLParser.ElementContext it : dataNodes) { replace(lines, toPosition(it.getStart()), toEndPosition(it.getStop()), ""); } List<? extends XMLParser.ElementContext> layoutNodes = excludeNodesByName("data", childrenOfRoot); if (layoutNodes.size() != 1) { L.e("Only one layout element and one data element are allowed. %s has %d", f.getAbsolutePath(), layoutNodes.size()); } final XMLParser.ElementContext layoutNode = layoutNodes.get(0); ArrayList<Pair<String, android.databinding.parser.XMLParser.ElementContext>> noTag = new ArrayList<>(); recurseReplace(layoutNode, lines, noTag, newTag, 0); // Remove the <layout> Position rootStartTag = toPosition(root.getStart()); Position rootEndTag = toPosition(root.content().getStart()); replace(lines, rootStartTag, rootEndTag, ""); // Remove the </layout> ImmutablePair<Position, Position> endLayoutPositions = findTerminalPositions(root, lines); replace(lines, endLayoutPositions.left, endLayoutPositions.right, ""); StringBuilder rootAttributes = new StringBuilder(); for (AttributeContext attr : attributes(root)) { rootAttributes.append(' ').append(attr.getText()); } Pair<String, XMLParser.ElementContext> noTagRoot = null; for (Pair<String, XMLParser.ElementContext> pair : noTag) { if (pair.getRight() == layoutNode) { noTagRoot = pair; break; } } if (noTagRoot != null) { ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>( noTagRoot.getLeft() + rootAttributes.toString(), layoutNode); int index = noTag.indexOf(noTagRoot); noTag.set(index, newRootTag); } else { ImmutablePair<String, XMLParser.ElementContext> newRootTag = new ImmutablePair<>( rootAttributes.toString(), layoutNode); noTag.add(newRootTag); } //noinspection NullableProblems Collections.sort(noTag, new Comparator<Pair<String, XMLParser.ElementContext>>() { @Override public int compare(Pair<String, XMLParser.ElementContext> o1, Pair<String, XMLParser.ElementContext> o2) { Position start1 = toPosition(o1.getRight().getStart()); Position start2 = toPosition(o2.getRight().getStart()); int lineCmp = Integer.compare(start2.line, start1.line); if (lineCmp != 0) { return lineCmp; } return Integer.compare(start2.charIndex, start1.charIndex); } }); for (Pair<String, android.databinding.parser.XMLParser.ElementContext> it : noTag) { XMLParser.ElementContext element = it.getRight(); String tag = it.getLeft(); Position endTagPosition = endTagPosition(element); fixPosition(lines, endTagPosition); String line = lines.get(endTagPosition.line); String newLine = line.substring(0, endTagPosition.charIndex) + " " + tag + line.substring(endTagPosition.charIndex); lines.set(endTagPosition.line, newLine); } return StringUtils.join(lines, System.getProperty("line.separator")); }
From source file:org.apache.appharness.AppHarnessUI.java
private void setPluginEntries(Set<String> pluginIdWhitelist, Uri configXmlUri) { CordovaActivity activity = (CordovaActivity) cordova.getActivity(); // Extract the <feature> from CADT's config.xml, and filter out unwanted plugins. ConfigXmlParser parser = new ConfigXmlParser(); parser.parse(activity);/*from w w w. ja v a2 s .c o m*/ ArrayList<PluginEntry> pluginEntries = new ArrayList<PluginEntry>(parser.getPluginEntries()); for (int i = 0; i < pluginEntries.size();) { PluginEntry p = pluginEntries.get(i); if (!pluginIdWhitelist.contains(p.service)) { pluginEntries.remove(p); continue; } else if (WhitelistPlugin.class.getCanonicalName().equals(p.pluginClass)) { pluginEntries.set(i, new PluginEntry(p.service, createWhitelistPlugin(configXmlUri))); } ++i; } slaveWebView.getPluginManager().setPluginEntries(pluginEntries); // This is added by cordova-android in code, so we need to re-add it likewise. // Note that we re-route navigator.app.exitApp() in JS to close the webview rather than close the Activity. slaveWebView.getPluginManager().addService("CoreAndroid", "org.apache.cordova.CoreAndroid"); }
From source file:org.droidparts.persist.sql.EntityManager.java
protected void putToContentValues(ContentValues cv, String key, Class<?> valueType, Class<?> arrCollItemType, Object value) throws IllegalArgumentException { if (value == null) { cv.putNull(key);//from w ww .j av a 2 s. c o m } else if (isBoolean(valueType)) { cv.put(key, ((Boolean) value)); } else if (isByte(valueType)) { cv.put(key, (Byte) value); } else if (isByteArray(valueType)) { cv.put(key, (byte[]) value); } else if (isDouble(valueType)) { cv.put(key, (Double) value); } else if (isFloat(valueType)) { cv.put(key, (Float) value); } else if (isInteger(valueType)) { cv.put(key, (Integer) value); } else if (isLong(valueType)) { cv.put(key, (Long) value); } else if (isShort(valueType)) { cv.put(key, (Short) value); } else if (isString(valueType)) { cv.put(key, (String) value); } else if (isUUID(valueType)) { cv.put(key, value.toString()); } else if (isDate(valueType)) { cv.put(key, ((Date) value).getTime()); } else if (isBitmap(valueType)) { Bitmap bm = (Bitmap) value; ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(CompressFormat.PNG, 0, baos); cv.put(key, baos.toByteArray()); } else if (isEnum(valueType)) { cv.put(key, value.toString()); } else if (isJsonObject(valueType) || isJsonArray(valueType)) { cv.put(key, value.toString()); } else if (isEntity(valueType)) { Long id = value != null ? ((Entity) value).id : null; cv.put(key, id); } else if (isArray(valueType) || isCollection(valueType)) { final ArrayList<Object> list = new ArrayList<Object>(); if (isArray(valueType)) { list.addAll(Arrays.asList(toObjectArr(value))); } else { list.addAll((Collection<?>) value); } if (isDate(arrCollItemType)) { for (int i = 0; i < list.size(); i++) { Long timestamp = ((Date) list.get(i)).getTime(); list.set(i, timestamp); } } String val = Strings.join(list, SEP, null); cv.put(key, val); } else { throw new IllegalArgumentException("Need to manually put " + valueType.getName() + " to cursor."); } }
From source file:org.openmeetings.app.remote.ChatService.java
/** * sends a message to all connected users * @param SID// w w w . ja v a 2 s . c om * @param newMessage * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public int sendMessageToOverallChat(Object newMessage) { try { IConnection current = Red5.getConnectionLocal(); RoomClient currentClient = this.clientListManager.getClientByStreamId(current.getClient().getId()); //log.error(newMessage.getClass().getName()); ArrayList messageMap = (ArrayList) newMessage; //adding delimiter space, cause otherwise an emoticon in the last string would not be found String messageText = messageMap.get(4).toString() + " "; //log.error("messageText"+messageText); //add server time messageMap.set(1, parseDateAsTimeString()); LinkedList<String[]> parsedStringObjects = ChatString.getInstance().parseChatString(messageText); //log.error("parsedStringObjects"+parsedStringObjects.size()); log.debug("size:" + messageMap.size()); messageMap.add(parsedStringObjects); newMessage = messageMap; HashMap<String, Object> hsm = new HashMap<String, Object>(); hsm.put("client", currentClient); hsm.put("message", newMessage); List<HashMap<String, Object>> myChatList = myChats.get(overallChatRoomName); if (myChatList == null) myChatList = new LinkedList<HashMap<String, Object>>(); if (myChatList.size() == chatRoomHistory) myChatList.remove(0); myChatList.add(hsm); myChats.put(overallChatRoomName, myChatList); log.debug("SET CHATROOM: " + overallChatRoomName); scopeApplicationAdapter.syncMessageToCurrentScope("sendVarsToOverallChat", hsm, true); } catch (Exception err) { log.error("[ChatService sendMessageToOverallChat] ", err); return -1; } return 1; }
From source file:mx.itdurango.rober.siitdocentes.ActivityAlumnos.java
/** * Lee un archivo, lo procesa y asigna las calificaciones de cada alumno en su correspondiente lugar de la vista y arreglo. * * @param m_chosen ruta absoluta hacia el archivo *///from w w w . j a v a 2 s .co m private void LoadFile(String m_chosen) { File file = new File(m_chosen); try { Reader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String line = ""; bufferedReader.readLine(); //la primer lnea no interesa ya que es el encabezado. int j = 0; //Se lee lnea por lnea el archivo while ((line = bufferedReader.readLine()) != null) { //Log.i("ARCHIVO", line); //separar la lnea que se lee mediante la coma String datos[] = line.split(","); ArrayList<String> calificaciones = gcs.get(j).getCalificaciones(); //recorrer los datos de la lnea ya separada a partir de la columna 2 (la columna 0 es el numero de control y al 1 el nombre) for (int i = 2; i < datos.length; i++) { //se reemplaza la calificacion correspondiente calificaciones.set(i - 2, datos[i]); //Log.i("CALIF", "[" + j + "][" + i + "]=" + datos[i]); } //se almacenan los cambios en el listado principal. gcs.get(j).setCalificaciones(calificaciones); j++; } //se recargan las calificaciones en el listado para que se vean reflejados los cambios cambiaCalificaciones(0); } catch (java.io.IOException e) { Toast.makeText(this, getString(R.string.error_cargaCalif), Toast.LENGTH_LONG).show(); e.printStackTrace(); } }