Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

In this page you can find the example usage for java.util ArrayList remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:org.telegram.android.MessagesController.java

private boolean updatePrintingUsersWithNewMessages(long uid, ArrayList<MessageObject> messages) {
    if (uid > 0) {
        ArrayList<PrintingUser> arr = printingUsers.get(uid);
        if (arr != null) {
            printingUsers.remove(uid);/* ww w . j  av  a  2s . c  o m*/
            return true;
        }
    } else if (uid < 0) {
        ArrayList<Integer> messagesUsers = new ArrayList<>();
        for (MessageObject message : messages) {
            if (!messagesUsers.contains(message.messageOwner.from_id)) {
                messagesUsers.add(message.messageOwner.from_id);
            }
        }

        ArrayList<PrintingUser> arr = printingUsers.get(uid);
        boolean changed = false;
        if (arr != null) {
            for (int a = 0; a < arr.size(); a++) {
                PrintingUser user = arr.get(a);
                if (messagesUsers.contains(user.userId)) {
                    arr.remove(a);
                    a--;
                    if (arr.isEmpty()) {
                        printingUsers.remove(uid);
                    }
                    changed = true;
                }
            }
        }
        if (changed) {
            return true;
        }
    }
    return false;
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private HttpRequest handleRequest(Socket proxySocket) throws IOException {
    HttpRequest request = new HttpRequest();
    BufferedInputStream proxyInStream = new BufferedInputStream(proxySocket.getInputStream());
    byte b = -1;/*from www  .j  a va  2s  .co m*/
    ArrayList<Byte> list = new ArrayList<Byte>(200);
    ArrayList<Byte> listToSend = new ArrayList<Byte>(200);
    int readInt;
    String previousLine = null;
    int lastCRPos = 0;
    int lastSendCRPos = 0;
    boolean hasCompleted = false;
    int lineNo = 0;
    int length = 0;
    while (!isInterrupted && !hasCompleted && (readInt = proxyInStream.read()) != -1) {
        b = (byte) readInt;
        list.add(new Byte(b));
        listToSend.add(new Byte(b));
        if (b == 13) {
            // check for two line breaks without form feed
            if (list.size() > 1) {
                if (list.get(list.size() - 2).equals(new Byte((byte) 13))) {
                    hasCompleted = true;
                } else {
                    // try to analyze the previous line
                    byte[] bytes = new byte[list.size() - lastCRPos - 1];
                    for (int i = lastCRPos; i < list.size() - 1; i++) {
                        bytes[i - lastCRPos] = ((Byte) list.get(i)).byteValue();
                    }
                    // requests are always in ASCII
                    previousLine = new String(bytes, "ISO-8859-1");
                    //logger.debug("request: " + previousLine);
                    if (lineNo == 0) {
                        // we must have here s.th. like 
                        // GET http://server/xyz.html?param=value HTTP/1.0
                        String[] components = previousLine.split(" ");
                        String method = components[0];
                        String urlStr = components[1];
                        String httpVersion = components[2];

                        // now parse the URL
                        URL url = new URL(urlStr);
                        String host = url.getHost();
                        String path = url.getPath();
                        String query = url.getQuery();
                        String port = String.valueOf(url.getPort());
                        if ("-1".equals(port)) {
                            port = "80";
                        }
                        request.setPort(Integer.parseInt(port));
                        request.setHost(host);
                        request.setPath(path);
                        request.setQuery(query);
                        request.setMethod(method);
                        request.setVersion(httpVersion);

                        // now we can reconstruct this line...
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            listToSend = new ArrayList<Byte>();
                            StringBuffer buff = new StringBuffer(100);
                            buff.append(method);
                            buff.append(' ');
                            buff.append(path);
                            if (query != null) {
                                buff.append('?');
                                buff.append(query);
                            }
                            buff.append(' ');
                            buff.append(components[2].substring(0, components[2].length()));
                            String newLine = buff.toString();
                            byte[] newLineBytes = newLine.getBytes("ISO-8859-1");
                            for (int i = 0; i < newLineBytes.length; i++) {
                                listToSend.add(new Byte(newLineBytes[i]));
                            }
                            listToSend.add(new Byte((byte) 13));
                        }
                    }
                    if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) {
                        String lengthStr = previousLine.substring(16, previousLine.length());
                        length = Integer.parseInt(lengthStr);
                        //logger.debug("length: " + length + ", " + lengthStr);
                    }
                    if (previousLine.matches("^[Pp]roxy.+")) {
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            //logger.debug("proxy!!! - " + previousLine);
                            // if not used behind another proxy erase proxy-related headers
                            for (int i = listToSend.size() - 1; i > lastSendCRPos - 2; i--) {
                                listToSend.remove(i);
                            }
                        }
                    }
                    // the CR should be ignored for printing any headerLine
                    lastCRPos = list.size() + 1;
                    lastSendCRPos = listToSend.size() + 1;
                    lineNo++;
                }
            }
        }
        if (b == 10) {
            // check for two line breaks with form feed
            if (list.get(list.size() - 2).equals(new Byte((byte) 13))
                    && list.get(list.size() - 3).equals(new Byte((byte) 10))
                    && list.get(list.size() - 4).equals(new Byte((byte) 13))) {
                //logger.debug("length: " + length);
                if (length == 0) {
                    hasCompleted = true;
                } else {
                    for (int i = 0; i < length; i++) {
                        readInt = proxyInStream.read();
                        b = (byte) readInt;
                        list.add(new Byte(b));
                        listToSend.add(new Byte(b));
                    }
                    list.add(new Byte((byte) '\n'));
                    listToSend.add(new Byte((byte) '\n'));
                    hasCompleted = true;
                }
            }
        }
    }
    // store original request
    byte[] byteArray = getByteArrayFromList(listToSend);
    request.setRequest(byteArray);
    //logger.debug("request: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray));
    return request;
}

From source file:DAO.DataAccessObject.java

/**
 * Methode zum ndern der Positionen./*  ww  w . ja v a  2 s. c o m*/
 * Diese Methode sollte nur in der Methode "aendereAuftrag" aufgerufen werden!
 * @param Auftrag Auftragskopf-Objekt
 * @param artikel HashMap: Key = Artikel-ID, Value = Menge
 * @throws ApplicationException wenn zu den bergebenen IDs keine passenden
 *                              Objekte gefunden werden knnen
 */
private void aenderePositionen(Auftragskopf Auftrag, HashMap<Long, Integer> artikel)
        throws ApplicationException {

    //Positionsliste aus dem Auftrag holen und zwischenspeichern
    ArrayList<Auftragsposition> positionsliste = Auftrag.getPositionsliste();

    //Artikel-IDs aus der HashMap holen
    Set<Long> artikelSet = artikel.keySet();

    //Fr jede Artikel-ID im Set...
    for (long ID : artikelSet) {

        //...wird der entsprechende Artikel in der Datenbank gesucht
        Artikel artikelObj = em.find(Artikel.class, ID);

        //Wenn der Artikel nicht gefunden werden kann
        if (artikelObj == null) {
            throw new ApplicationException("Fehler",
                    "Der Artikel mit der ID " + ID + " konnte nicht gefunden" + " werden.");
        }

        /*
        ...wird, zusammen mit der Auftrags-ID, versucht eine 
        Auftragsposition zu finden.
        Wird keine gefunden, gibt die Methode "null" zurck
        */
        Auftragsposition ap = this.gibAuftragspositionNachArtikel(Auftrag.getAuftragskopfID(), ID);

        //Wurde eine Auftragsposition gefunden...
        if (ap != null) {

            //...wird geprft, ob die Position vorher bereits existiert hat
            //aber gelscht wurde
            if (ap.isLKZ()) {
                //WEnn ja, wird vor dem ndern das LKZ entfernt
                ap.setLKZ(false);
            }

            //Suche die Auftragsposition in der Positionsliste
            int index = Auftrag.getPositionsliste().indexOf(ap);
            //Setze den Artikel in der Position
            Auftrag.getPositionsliste().get(index).setArtikel(artikelObj);
            //Setze die Menge in der Position
            Auftrag.getPositionsliste().get(index).setMenge(artikel.get(ID));
            //Lsche die Position aus der zwischengespeicherten Positionsliste
            positionsliste.remove(ap);

            //Wenn in der Datenbank keine Position zu den IDs gefunden wurde...
        } else {

            //...wird eine neue Position erzeugt und der Positionsliste
            //hinzugefgt
            Auftrag.addPosition(artikelObj, artikel.get(ID));
        }
    }

    //Alle Position die am Ende der Schleife noch in der zwischengespeicherten
    //Positionsliste vorkommen, hat der Benutzer in der GUI gelscht
    for (Auftragsposition ap : positionsliste) {

        //Fr diese Positionen wird das LKZ gesetzt
        this.loeschePosition(Auftrag.getAuftragskopfID(), ap.getPositionsnummer());

    }

}

From source file:com.krawler.workflow.module.dao.ModuleBuilderDaoImpl.java

public String getGridData(HttpServletRequest request, Hashtable coldata, Object id, String pTable) {
    String result = "{data:[],count : 0}";
    try {/*  w w w.ja v a 2s. co  m*/
        //            int start = Integer.parseInt(request.getParameter("start"));
        //            int limit = Integer.parseInt(request.getParameter("limit"));
        String tName = coldata.get("reftable").toString();
        String reportid = reportDao.getReportIdFromTable(tName);
        String query = null;
        Configuration cfg = getConfig();
        java.util.Iterator itr = cfg.getTableMappings();
        HashMap<String, Table> tableObj = new HashMap<String, Table>();
        while (itr.hasNext()) {
            Table table = (Table) itr.next();
            tableObj.put(PropsValues.PACKAGE_PATH + "." + table.getName(), table);
        }
        //Fetch all reference tables in report
        mb_reportlist report = (mb_reportlist) get(mb_reportlist.class, reportid);
        query = "Select distinct mb_gridconfig.reftable as tablename from " + PropsValues.PACKAGE_PATH
                + ".mb_gridconfig as mb_gridconfig where mb_gridconfig.reportid = ? and mb_gridconfig.countflag = ? ";
        List ls = find(query, new Object[] { report, false });
        java.util.Iterator ite = ls.iterator();
        String str = "";
        ArrayList<String> refTableList1 = new ArrayList<String>();
        HashMap<String, String> shortTableNames = new HashMap<String, String>();
        while (ite.hasNext()) {
            String reftablename = (String) ite.next();
            if (!StringUtil.isNullOrEmpty(reftablename)) {
                refTableList1.add(PropsValues.PACKAGE_PATH + "." + reftablename);
                shortTableNames.put(PropsValues.PACKAGE_PATH + "." + reftablename, reftablename);
            }
        }
        //If new table created not present in arraylist then it is added forcefully
        String reportTName = reportDao.getReportTableName(reportid);
        if (!StringUtil.isNullOrEmpty(reportTName)
                && !refTableList1.contains(PropsValues.PACKAGE_PATH + "." + reportTName)) {
            refTableList1.add(PropsValues.PACKAGE_PATH + "." + reportTName);
            shortTableNames.put(PropsValues.PACKAGE_PATH + "." + reportTName, reportTName);
        }

        ArrayList<String> refTableList = new ArrayList<String>();
        ArrayList<String> primaryTableList = new ArrayList<String>();
        HashMap<String, ArrayList<String>> parentTableObj = new HashMap<String, ArrayList<String>>();
        HashMap<String, ArrayList<String>> colNameObj = new HashMap<String, ArrayList<String>>();
        //Make list of reference tables which does not have any relationship with another ref. tables
        //Sort all reference tables in relationship order i.e. form child - parent
        for (int i = 0; i < refTableList1.size(); i++) {
            String reftablename = refTableList1.get(i);
            Table tb = tableObj.get(reftablename);
            Iterator FkIte = tb.getForeignKeyIterator();
            if (FkIte.hasNext()) {
                boolean flg = false;
                ArrayList<String> parentTName1 = new ArrayList<String>();
                ArrayList<String> colName1 = new ArrayList<String>();
                while (FkIte.hasNext()) { //Always keep foreign key name = parent tablename + primary column name
                    ForeignKey obj = (ForeignKey) FkIte.next();
                    String parentTName = obj.getReferencedEntityName();
                    Column col = (Column) obj.getColumns().iterator().next();
                    String colName = col.getName();
                    if (refTableList1.contains(parentTName)) {
                        if (primaryTableList.contains(parentTName)) {
                            primaryTableList.remove(parentTName);
                        }
                        if (refTableList.contains(parentTName)) {
                            refTableList.remove(parentTName);
                            if (!refTableList.contains(reftablename)) {
                                refTableList.add(reftablename);
                            }
                            refTableList.add(parentTName);
                        } else if (!refTableList.contains(reftablename)) {
                            refTableList.add(reftablename);
                        }
                        parentTName1.add(parentTName);
                        colName1.add(colName);

                        flg = true;
                    } else {
                        if (!refTableList.contains(reftablename)) {
                            refTableList.add(reftablename);
                            flg = true;
                        }
                        continue;
                    }
                }

                parentTableObj.put(reftablename, parentTName1);
                colNameObj.put(reftablename, colName1);

                if (!flg) {
                    primaryTableList.add(reftablename);
                }
            } else if (!FkIte.hasNext()) {
                //Check whether reference table is already part of parentTableObj.
                //If yes then not to add in primaryList
                boolean flg = true;
                Iterator temp = parentTableObj.keySet().iterator();
                while (temp.hasNext()) {
                    ArrayList<String> ttemp = (ArrayList<String>) parentTableObj.get(temp.next());
                    for (int l = 0; l < ttemp.size(); l++) {
                        if (ttemp.contains(reftablename)) {
                            flg = false;
                            break;
                        }
                    }
                    if (!flg) {
                        break;
                    }
                }
                if (flg) {
                    primaryTableList.add(reftablename);
                }
            }
        }

        String delQuery = "";
        for (int i = 0; i < refTableList.size(); i++) {
            String reftablename = refTableList.get(i);
            ArrayList<String> parentTName = parentTableObj.get(reftablename);
            ArrayList<String> colName = colNameObj.get(reftablename);

            for (int j = 0; j < parentTName.size(); j++) {
                String shortRefTName = shortTableNames.get(reftablename);
                String shortParentTName = shortTableNames.get(parentTName.get(j));
                if (StringUtil.isNullOrEmpty(str)) {
                    str += reftablename + " as " + shortRefTName + " inner join " + shortRefTName + "."
                            + colName.get(j) + " as " + shortParentTName;
                    delQuery += shortRefTName + ".deleteflag = 0 and " + shortParentTName + ".deleteflag = 0 ";
                } else if (str.contains(shortRefTName)) {
                    //if reference table is already part of query then use alias
                    str += " inner join " + shortRefTName + "." + colName.get(j) + " as " + shortParentTName;
                    if (!delQuery.contains(shortParentTName)) {
                        delQuery += " and " + shortParentTName + ".deleteflag = 0 ";
                    }
                } else {
                    //otherwise use full path
                    str += " inner join " + reftablename + "." + colName.get(j) + " as " + shortParentTName;
                    if (!delQuery.contains(shortParentTName)) {
                        delQuery += " and " + shortParentTName + ".deleteflag = 0 ";
                    }
                }
            }
        }

        String primaryTableQuery = "";
        for (int i = 0; i < primaryTableList.size(); i++) {
            String reftablename = primaryTableList.get(i);
            String shortRefTName = shortTableNames.get(reftablename);

            if (StringUtil.isNullOrEmpty(delQuery)) {
                delQuery += shortRefTName + ".deleteflag = 0 ";
            } else if (!delQuery.contains(shortRefTName)) {
                delQuery += " and " + shortRefTName + ".deleteflag = 0 ";
            }

            if (StringUtil.isNullOrEmpty(primaryTableQuery)) {
                primaryTableQuery += " from " + reftablename + " as " + shortRefTName;
            } else {
                primaryTableQuery += " , " + reftablename + " as " + shortRefTName;
            }
        }
        String finalQuery = "";
        if (!StringUtil.isNullOrEmpty(primaryTableQuery)) {
            finalQuery += primaryTableQuery;
        }
        if (!StringUtil.isNullOrEmpty(str)) {
            if (StringUtil.isNullOrEmpty(finalQuery)) {
                finalQuery = " from " + str;
            } else {
                finalQuery = ", " + str;
            }
        }

        //Fetch all display columns
        String SELECT_QUERY = "select mb_gridconfig.name, mb_gridconfig.xtype, mb_gridconfig.combogridconfig, mb_gridconfig.countflag, mb_gridconfig.reftable from com.krawler.esp.hibernate.impl.mb_gridconfig as mb_gridconfig"
                + " where mb_gridconfig.reportid = ?";
        List list = find(SELECT_QUERY, new Object[] { report });
        ite = list.iterator();
        String fieldQuery = "";
        ArrayList<String> fieldNameArray = new ArrayList<String>();
        ArrayList<String> countFieldNameArray = new ArrayList<String>();
        while (ite.hasNext()) {
            Object[] row = (Object[]) ite.next();
            String fieldName = row[0].toString();
            String xtype = row[1].toString();
            String combogridconfig = "-1";
            if (row[2] != null) {
                combogridconfig = row[2].toString();
            }
            //Check for count flag
            if (row[3] != null && Boolean.parseBoolean(row[3].toString())) {//countFlag
                countFieldNameArray.add(row[4].toString());
            } else {
                fieldNameArray.add(fieldName);
                String className = "";
                if (xtype.equals("Combobox") && combogridconfig.equals("-1")) {
                    className = fieldName.split(PropsValues.REPORT_HARDCODE_STR)[0];
                    fieldName = className + "." + getPrimaryColName(className);
                } else {
                    fieldName = fieldName.replaceAll(PropsValues.REPORT_HARDCODE_STR, ".");
                }
                fieldQuery += fieldName + ",";
            }
        }

        if (StringUtil.isNullOrEmpty(fieldQuery)) {
            fieldQuery = "Select * ";
        } else {
            fieldQuery = "Select " + fieldQuery.substring(0, fieldQuery.length() - 1);
        }

        //Check for mapping filter
        String filtertablename = PropsValues.PACKAGE_PATH + "." + pTable;
        Class modcl = Class.forName(filtertablename);
        Object modObj = get(modcl, id.toString());
        String filterQry = " where " + tName + "." + pTable + "id=?";
        if (!StringUtil.isNullOrEmpty(delQuery)) {
            if (!StringUtil.isNullOrEmpty(filterQry)) {
                delQuery = filterQry + " and " + delQuery;
            } else {
                delQuery = " where " + delQuery;
            }
        }

        //Check for comments
        SELECT_QUERY = "select mb_moduleConfigMap.configid.configid from com.krawler.esp.hibernate.impl.mb_moduleConfigMap "
                + "as mb_moduleConfigMap where mb_moduleConfigMap.moduleid = ? ";
        List configlist = find(SELECT_QUERY, new Object[] { report });
        ite = configlist.iterator();
        boolean commentFlag = false;
        boolean docFlag = false;
        while (ite.hasNext()) {
            int configid = (Integer) ite.next();
            if (configid == 1) { // Comments
                commentFlag = true;
            }
            if (configid == 2) { // Documents
                commentFlag = true;
            }
        }

        //Generate rules filter query for report grid
        String ruleFilterQuery = "";
        //            ArrayList permArray = AuthHandler.getRealRoleids(request);
        //            for(int i = 0; i < permArray.size(); i++) {
        //                int roleid = Integer.parseInt(permArray.get(i).toString());
        //                String res = ModuleBuilderController.checkFilterRulesQuery(session, report, roleid, 0, "");
        //                if(!StringUtil.isNullOrEmpty(res)) {
        //                    res = "("+res +")";
        //                    if(!StringUtil.isNullOrEmpty(ruleFilterQuery))
        //                        ruleFilterQuery = res + " or " + ruleFilterQuery;
        //                    else
        //                        ruleFilterQuery = res;
        //                }
        //            }
        if (!StringUtil.isNullOrEmpty(ruleFilterQuery))
            ruleFilterQuery = " and " + ruleFilterQuery;

        String searchFilter = "";
        String sortQuery = "";

        JSONObject jobj = new JSONObject();
        Object[] paramArray = new Object[] { modObj };
        if (!StringUtil.isNullOrEmpty(finalQuery)) {
            //Get implementation class object and call before dataLoad method.
            //Check for reportTName is null;
            String className = reportTName;
            if (StringUtil.isNullOrEmpty(className)) {
                className = "rb_" + reportDao.toLZ(report.getReportkey(), 3) + "_"
                        + report.getReportname().replace(" ", "").toLowerCase();
            }
            Class cl1 = Class.forName(PropsValues.PACKAGE_PATH + ".impl_" + className);
            java.lang.reflect.Constructor co1 = cl1.getConstructor();
            Object invoker1 = co1.newInstance();
            Class arguments1[] = new Class[] { HibernateTemplate.class, HttpServletRequest.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    ArrayList.class, ArrayList.class, Boolean.class, Boolean.class, JSONObject.class,
                    Boolean.class, Object[].class };

            java.lang.reflect.Method objMethod1 = cl1.getMethod("beforeGridLoadData", arguments1);
            Object[] obj1 = new Object[] { getHibernateTemplate(), request, finalQuery, fieldQuery, delQuery,
                    searchFilter, ruleFilterQuery, sortQuery, reportTName, fieldNameArray, countFieldNameArray,
                    commentFlag, docFlag, jobj, false, paramArray };
            Object result11 = objMethod1.invoke(invoker1, obj1);
        }
        if (jobj.has("data")) {
            //                jobj.put("count", count);
            result = jobj.toString();
        } else {
            result = "{data:[]}";
        }

    } catch (HibernateException e) {
        logger.warn(e.getMessage(), e);
        result = "{data:[]}";
        throw ServiceException.FAILURE("reportMethods.loadData", e);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        result = "{data:[]}";
        throw ServiceException.FAILURE("reportMethods.loadData", e);
    } finally {
        return result;
    }
}

From source file:net.droidsolutions.droidcharts.core.plot.XYPlot.java

/**
 * Removes a marker for a specific dataset/renderer and, if requested, sends
 * a {@link PlotChangeEvent} to all registered listeners.
 * /*ww w  .  ja v a 2s .c  o m*/
 * @param index
 *            the dataset/renderer index.
 * @param marker
 *            the marker.
 * @param layer
 *            the layer (foreground or background).
 * @param notify
 *            notify listeners?
 * 
 * @return A boolean indicating whether or not the marker was actually
 *         removed.
 * 
 * @since 1.0.10
 */
public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) {
    ArrayList markers;
    if (layer == Layer.FOREGROUND) {
        markers = (ArrayList) this.foregroundDomainMarkers.get(new Integer(index));
    } else {
        markers = (ArrayList) this.backgroundDomainMarkers.get(new Integer(index));
    }
    if (markers == null) {
        return false;
    }
    boolean removed = markers.remove(marker);
    if (removed && notify) {
        // fireChangeEvent();
    }
    return removed;
}

From source file:net.droidsolutions.droidcharts.core.plot.XYPlot.java

/**
 * Removes a marker for a specific dataset/renderer and sends a
 * {@link PlotChangeEvent} to all registered listeners.
 * //w  w w .  j a  v a  2s  . c om
 * @param index
 *            the dataset/renderer index.
 * @param marker
 *            the marker.
 * @param layer
 *            the layer (foreground or background).
 * @param notify
 *            notify listeners?
 * 
 * @return A boolean indicating whether or not the marker was actually
 *         removed.
 * 
 * @since 1.0.10
 */
public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) {
    if (marker == null) {
        throw new IllegalArgumentException("Null 'marker' argument.");
    }
    ArrayList markers;
    if (layer == Layer.FOREGROUND) {
        markers = (ArrayList) this.foregroundRangeMarkers.get(new Integer(index));
    } else {
        markers = (ArrayList) this.backgroundRangeMarkers.get(new Integer(index));
    }
    if (markers == null) {
        return false;
    }
    boolean removed = markers.remove(marker);
    if (removed && notify) {
        // fireChangeEvent();
    }
    return removed;
}

From source file:com.clustercontrol.jobmanagement.factory.SelectJob.java

/**
 * ??????//ww  w .  j  a  va 2s.  c  o  m
 * <p>
 *
 * @param property 
 * @param limit ?
 * @return ??
 * @throws JobInfoNotFound
 * @throws InvalidRole
 * @throws HinemosUnknown
 */
public ArrayList<JobApprovalInfo> getApprovalJobList(JobApprovalFilter property, int limit)
        throws JobInfoNotFound, InvalidRole, HinemosUnknown {
    m_log.debug("getApprovalJobList()");
    ArrayList<JobApprovalInfo> list = new ArrayList<JobApprovalInfo>();
    List<String> roleIdList = null;
    ArrayList<Integer> statuslist = null;
    Boolean isPending = null;

    Boolean isAdministrator = (Boolean) HinemosSessionContext.instance()
            .getProperty(HinemosSessionContext.IS_ADMINISTRATOR);
    String loginUser = (String) HinemosSessionContext.instance()
            .getProperty(HinemosSessionContext.LOGIN_USER_ID);
    boolean isApprovalPrivilege = UserRoleCache.isSystemPrivilege(loginUser,
            new SystemPrivilegeInfo(FunctionConstant.JOBMANAGEMENT, SystemPrivilegeMode.APPROVAL));
    roleIdList = UserRoleCache.getRoleIdList(loginUser);
    if (m_log.isDebugEnabled()) {
        if (roleIdList != null && !roleIdList.isEmpty()) {
            for (String role : roleIdList) {
                m_log.debug("roleIdList():" + role);
            }
        }
    }

    //"?"?DB??"?"??????????????????
    //??"?"/"?"???????/SQL??????
    if (property.getStatusList() != null && property.getStatusList().length > 0) {
        statuslist = new ArrayList<Integer>();
        statuslist.addAll(Arrays.asList(property.getStatusList()));

        boolean isShowPending = statuslist.contains(JobApprovalStatusConstant.TYPE_PENDING);
        boolean isShowStill = statuslist.contains(JobApprovalStatusConstant.TYPE_STILL);

        //SQL????/?(?)/?(?)?????
        //"?"/"?"??????????????("?"/"?"???)
        //???????"?"???????????("?"/"?"???)
        if (isShowPending && !isShowStill) {
            isPending = true;
        } else if (!isShowPending && isShowStill) {
            isPending = false;
        }

        //ADMINISTRATORS????"?"(??)???????"?"(???)???????????
        if (isAdministrator || !isApprovalPrivilege) {
            isPending = null;
        }

        //?SQL??????????
        if (isPending != null) {
            //"?"??"?"????SQL???????????????
            statuslist.remove(Integer.valueOf(JobApprovalStatusConstant.TYPE_PENDING));
            statuslist.remove(Integer.valueOf(JobApprovalStatusConstant.TYPE_STILL));
        } else {
            //DB??"?"??????"?"??????????
            //?????????????"?"???
            statuslist.remove(Integer.valueOf(JobApprovalStatusConstant.TYPE_STILL));
            if (!isShowPending && isShowStill) {
                //"?"??"?"????"?"????
                statuslist.add(Integer.valueOf(JobApprovalStatusConstant.TYPE_PENDING));
            }
            if (isAdministrator && (!isShowPending && isShowStill)) {
                //ADMINISTRATORS????"?"(???)???????
                //?"?"??"?"????"?"??
                statuslist.remove(Integer.valueOf(JobApprovalStatusConstant.TYPE_PENDING));
            }
            if (!isApprovalPrivilege && (isShowPending && !isShowStill)) {
                //???????"?"(??)???????
                //?"?"??"?"????"?"??
                statuslist.remove(Integer.valueOf(JobApprovalStatusConstant.TYPE_PENDING));
            }
            if (statuslist.size() == 0) {
                //????????????????
                return list;
            }
        }
    }

    //?+1???
    TypedQuery<?> typedQuery = getApprovalFilterQuery(property, statuslist, isPending, roleIdList, loginUser,
            Integer.valueOf(limit + 1));
    @SuppressWarnings("unchecked")
    List<JobInfoEntity> joblist = (List<JobInfoEntity>) typedQuery.getResultList();

    m_log.debug("approval job  num:" + joblist.size());

    for (JobInfoEntity job : joblist) {

        JobSessionJobEntity sessionJob = QueryUtil.getJobSessionJobPK(job.getId().getSessionId(),
                job.getId().getJobunitId(), job.getId().getJobId());
        //???
        List<JobSessionNodeEntity> nodeList = sessionJob.getJobSessionNodeEntities();
        JobSessionNodeEntity sessionNode = null;
        // ?????1??
        if (nodeList != null && nodeList.size() == 1) {
            //?
            sessionNode = nodeList.get(0);
        } else {
            // ????????????
            continue;
        }

        Integer status = sessionNode.getApprovalStatus();
        //??????????
        //ADMINISTRATORS??????????/????
        if (status == JobApprovalStatusConstant.TYPE_PENDING && !isAdministrator) {
            //?????????????/??????????????"?"?
            if (!isApprovalPrivilege || (roleIdList != null && !roleIdList.contains(job.getApprovalReqRoleId()))
                    || (job.getApprovalReqUserId() != null && (!job.getApprovalReqUserId().equals("*")
                            && !job.getApprovalReqUserId().equals(loginUser)))) {
                status = JobApprovalStatusConstant.TYPE_STILL;
            }
        }

        if (m_log.isDebugEnabled()) {
            m_log.debug("jobinfo:" + job.getId().getSessionId() + " " + job.getId().getJobunitId() + " "
                    + job.getId().getJobId());
            m_log.debug("appreqinfo:" + job.getApprovalReqRoleId() + " " + job.getApprovalReqUserId()
                    + " status:" + status);
            m_log.debug("userinfo:" + loginUser + " isAdmin:" + isAdministrator + " isPrivilege:"
                    + isApprovalPrivilege);
        }

        //????
        JobApprovalInfo info = new JobApprovalInfo(null, status,
                sessionNode.getApprovalResult() == null ? null : sessionNode.getApprovalResult(),
                job.getId().getSessionId(), job.getId().getJobunitId(), job.getId().getJobId(),
                job.getJobName(), sessionNode.getApprovalRequestUser(), sessionNode.getApprovalUser(),
                sessionNode.getStartDate() == null ? null : sessionNode.getStartDate(),
                sessionNode.getEndDate() == null ? null : sessionNode.getEndDate(),
                job.getApprovalReqSentence(), sessionNode.getApprovalComment());
        list.add(info);
    }
    return list;
}

From source file:com.cohort.util.String2.java

/**
 * Given an arrayList which alternates attributeName (a String) and 
 * attributeValue (an object), this either removes the attribute
 * (if value == null), adds the attribute and value (if it isn't in the list),
 * or changes the value (if the attriubte is in the list).
 *
 * @param arrayList //  w w w .  ja v  a2  s  .c o  m
 * @param attributeName
 * @param value the value associated with the attributeName
 * @return the previous value for the attribute (or null)
 * @throws RuntimeException of trouble (e.g., if arrayList is null)
 */
public static Object alternateSetValue(ArrayList arrayList, String attributeName, Object value) {
    if (arrayList == null)
        throw new SimpleException(ERROR + " in String2.alternateSetValue: arrayList is null.");
    int n = arrayList.size();
    for (int i = 0; i < n; i += 2) {
        if (arrayList.get(i).toString().equals(attributeName)) {
            Object oldValue = arrayList.get(i + 1);
            if (value == null) {
                arrayList.remove(i + 1); //order of removal is important
                arrayList.remove(i);
            } else
                arrayList.set(i + 1, value);
            return oldValue;
        }
    }

    //attributeName not found? 
    if (value == null)
        return null;
    else {
        //add it
        arrayList.add(attributeName);
        arrayList.add(value);
        return null;
    }
}

From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerReader.java

@Override
public List<ArtifactState> getChangedArtifacts(Document syncInfo) {
    String repositoryKey = this.getRepositoryKey(syncInfo);
    String repositoryId = this.getSourceRepositoryId(syncInfo);
    String lastShippedArtifactId = this.getLastSourceArtifactId(syncInfo);
    Date lastModifiedDate = this.getLastModifiedDate(syncInfo);
    long fromTimeLong = lastModifiedDate.getTime();
    fromTimeLong = fromTimeLong < 0 ? 0 : fromTimeLong;
    String fromTime = Long.toString(fromTimeLong);
    String artifactTypeDisplayName = repositoryId.substring(repositoryId.lastIndexOf(":") + 1);
    Set<String> artifactTypes = new HashSet<String>();

    TrackerWebServicesClient twsclient = null;
    TrackerArtifactType trackerArtifactType = metadataHelper.getTrackerArtifactType(repositoryKey);
    ArrayList<ArtifactState> artifactStatesDuplicate = new ArrayList<ArtifactState>();
    ArrayList<ArtifactState> artifactStatesNew = new ArrayList<ArtifactState>();
    boolean duplicateDetected = false;
    HashMap<String, ArtifactState> artifactIdStateMap = new HashMap<String, ArtifactState>();
    try {/*  w  ww  .ja  v a  2 s.  c  o  m*/
        twsclient = this.getConnection(syncInfo);
        if (trackerArtifactType == null) {
            trackerArtifactType = metadataHelper.getTrackerArtifactType(repositoryKey, artifactTypeDisplayName,
                    twsclient, true);
        }

        if (trackerArtifactType == null) {
            throw new CCFRuntimeException("Artifact type for repository " + repositoryKey
                    + " unknown, cannot synchronize repository.");
        }
        String namespace = trackerArtifactType.getNamespace();
        String tagname = trackerArtifactType.getTagName();
        String artifactTypeFullyQualifiedName = "{" + namespace + "}" + tagname;

        artifactTypes.add(artifactTypeFullyQualifiedName);
        // String[] changedArtifacts = twsclient.getChangedArtifacts(
        // artifactTypes, fromTime);
        HistoryTransactionList transactionList = twsclient.getArtifactChanges(artifactTypes, fromTime);
        if (transactionList != null) {
            HistoryTransaction[] transactions = transactionList.getHistoryTransaction();
            if (transactions != null) {
                for (HistoryTransaction transaction : transactions) {
                    if (transaction == null)
                        continue;
                    long modifiedOn = transaction.getModifiedOn();
                    if (modifiedOn == 32503622400000L) {
                        // fix if modified date is not set correctly
                        log.error("Invalid last modified date detected!");
                        continue;
                    }

                    HistoryActivity[] historyActivities = transaction.getHistoryActivity();
                    if (historyActivities != null) {
                        for (HistoryActivity historyActivity : historyActivities) {
                            if (historyActivity != null) {
                                String activityType = historyActivity.getType();
                                if ("DependencyAdded".equals(activityType)
                                        || "DependencyDeleted".equals(activityType)) {
                                    continue;
                                }
                                String historyArtifactId = artifactTypeFullyQualifiedName + ":"
                                        + historyActivity.getArtifactId();
                                if (historyArtifactId.equals(lastShippedArtifactId)
                                        && fromTimeLong == modifiedOn) {
                                    duplicateDetected = true;
                                    continue;
                                }

                                Date modifiedOnDate = new Date(modifiedOn);
                                if (lastModifiedDate.after(modifiedOnDate)) {
                                    log.warn("lastModified from synchronization status table ("
                                            + lastModifiedDate + ") is after last modified date of artifact "
                                            + historyArtifactId + " (" + modifiedOnDate + ").");
                                }

                                ArtifactState state = null;
                                if (artifactIdStateMap.containsKey(historyArtifactId)) {
                                    state = artifactIdStateMap.get(historyArtifactId);
                                    state.setArtifactLastModifiedDate(modifiedOnDate);
                                    state.setArtifactVersion(modifiedOn);
                                    if (!duplicateDetected) {
                                        artifactStatesDuplicate.remove(state);
                                        artifactStatesDuplicate.add(state);
                                    } else {
                                        artifactStatesNew.remove(state);
                                        artifactStatesNew.add(state);
                                    }
                                } else {
                                    state = new ArtifactState();
                                    state.setArtifactId(historyArtifactId);
                                    state.setArtifactLastModifiedDate(new Date(modifiedOn));
                                    state.setArtifactVersion(modifiedOn);
                                    artifactIdStateMap.put(historyArtifactId, state);
                                    if (!duplicateDetected) {
                                        artifactStatesDuplicate.add(state);
                                    } else {
                                        artifactStatesNew.add(state);
                                    }
                                }
                                /*
                                 * if (this.isIgnoreConnectorUserUpdates())
                                 * { if
                                 * (modifiedBy.equalsIgnoreCase(this.getUsername
                                 * ())) { state =
                                 * artifactIdStateMap.get(historyArtifactId
                                 * );
                                 * artifactIdStateMap.remove(historyArtifactId
                                 * ); if (!duplicateDetected) {
                                 * artifactStatesDuplicate.remove(state); }
                                 * else { artifactStatesNew.remove(state); }
                                 * } }
                                 */
                            }
                        }
                    }
                }
            }
        }
    } catch (WSException e1) {
        String message = "Web Service Exception while getting the changed artifacts";
        log.error(message, e1);
        throw new CCFRuntimeException(message, e1);
    } catch (RemoteException e1) {
        String message = "Remote Exception while getting the changed artifacts";
        log.error(message, e1);
        throw new CCFRuntimeException(message, e1);
    } catch (ServiceException e1) {
        String message = "Service Exception while getting the changed artifacts";
        log.error(message, e1);
        throw new CCFRuntimeException(message, e1);
    } catch (Exception e) {
        String message = "Exception while getting the changed artifacts";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } finally {
        if (twsclient != null) {
            getConnectionManager().releaseConnection(twsclient);
        }
    }
    if (duplicateDetected) {
        return artifactStatesNew;
    } else {
        return artifactStatesDuplicate;
    }
}