Example usage for java.util LinkedList removeLast

List of usage examples for java.util LinkedList removeLast

Introduction

In this page you can find the example usage for java.util LinkedList removeLast.

Prototype

public E removeLast() 

Source Link

Document

Removes and returns the last element from this list.

Usage

From source file:org.apache.axis2.deployment.util.Utils.java

/**
 * Normalize a uri containing ../ and ./ paths.
 *
 * @param uri The uri path to normalize//from  ww  w .  ja v a 2  s. com
 * @return The normalized uri
 */
public static String normalize(String uri) {
    if ("".equals(uri)) {
        return uri;
    }
    int leadingSlashes;
    for (leadingSlashes = 0; leadingSlashes < uri.length()
            && uri.charAt(leadingSlashes) == '/'; ++leadingSlashes) {
        // FIXME: this block is empty!!
    }
    boolean isDir = (uri.charAt(uri.length() - 1) == '/');
    StringTokenizer st = new StringTokenizer(uri, "/");
    LinkedList clean = new LinkedList();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if ("..".equals(token)) {
            if (!clean.isEmpty() && !"..".equals(clean.getLast())) {
                clean.removeLast();
                if (!st.hasMoreTokens()) {
                    isDir = true;
                }
            } else {
                clean.add("..");
            }
        } else if (!".".equals(token) && !"".equals(token)) {
            clean.add(token);
        }
    }
    StringBuffer sb = new StringBuffer();
    while (leadingSlashes-- > 0) {
        sb.append('/');
    }
    for (Iterator it = clean.iterator(); it.hasNext();) {
        sb.append(it.next());
        if (it.hasNext()) {
            sb.append('/');
        }
    }
    if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
        sb.append('/');
    }
    return sb.toString();
}

From source file:gsn.http.DataDownload.java

/**
 * List of the parameters for the requests:
 * url : /data/*from   w  w w .  j a  v a 2  s  .  com*/
 * Example: Getting all the data in CSV format => http://localhost:22001/data?vsName=memoryusage4&fields=heap&display=CSV
 * another example: http://localhost:22001/data?vsName=memoryusage4&fields=heap&fields=timed&display=CSV&delimiter=other&otherdelimiter=,
 * <p/>
 * param-name: vsName : the name of the virtual sensor we need.
 * param-name: fields [there can be multiple parameters with this name pointing to different fields in the stream element].
 * param-name: commonReq (always true !)
 * param-name: display , if there is a value it should be CSV.
 * param-name: delimiter, useful for CSV output (can be "tab","space","other")
 * param-name: otherdelimiter useful in the case of having delimiter=other
 * param-name: groupby can point to one of the fields in the stream element. In case groupby=timed then the parameter groupbytimed points to the period for which data should be aggregated [in milliseconds].
 * param-name: nb give the maximum number of elements to be outputed (most recent values first).
 * param-name:
 */
public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, java.io.IOException {

    //
    HttpSession session = req.getSession();
    User user = (User) session.getAttribute("user");

    res.setHeader("Cache-Control", "no-store");
    res.setDateHeader("Expires", 0);
    res.setHeader("Pragma", "no-cache");
    //

    PrintWriter respond = res.getWriter();
    DataEnumerator result = null;
    try {
        SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());
        SimpleDateFormat sdf_from_ui = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        TimeZone timeZone = GregorianCalendar.getInstance().getTimeZone();
        boolean responseCVS = false;
        boolean wantTimeStamp = false;
        boolean wantPk = false;
        boolean commonReq = true;
        boolean groupByTimed = false;

        String vsName = HttpRequestUtils.getStringParameter("vsName", null, req);
        if (vsName == null)
            vsName = HttpRequestUtils.getStringParameter("vsname", null, req);
        if (vsName == null) {
            res.sendError(WebConstants.MISSING_VSNAME_ERROR, "The virtual sensor name is missing");
            return;
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        Date currentDate = Calendar.getInstance().getTime();
        String filename = vsName + "_" + dateFormat.format(currentDate);

        if (Main.getContainerConfig().isAcEnabled() == true) {
            if (user != null) // meaning, that a login session is active, otherwise we couldn't get there
                if (user.hasReadAccessRight(vsName) == false && user.isAdmin() == false) // ACCESS_DENIED
                {
                    res.sendError(WebConstants.ACCESS_DENIED,
                            "Access denied to the specified virtual sensor .");
                    return;
                }
        }

        if (req.getParameter("display") != null && req.getParameter("display").equals("CSV")) {
            responseCVS = true;
            res.setContentType("text/csv");
            //res.setContentType("text/html");
        } else {
            res.setContentType("text/xml");
        }
        if (req.getParameter("commonReq") != null && req.getParameter("commonReq").equals("false")) {
            commonReq = false;
        }
        String separator = ";";
        if (req.getParameter("delimiter") != null && !req.getParameter("delimiter").equals("")) {
            String reqSeparator = req.getParameter("delimiter");
            if (reqSeparator.equals("tab")) {
                separator = "\t";
            } else if (reqSeparator.equals("space")) {
                separator = " ";
            } else if (reqSeparator.equals("other") && req.getParameter("otherdelimiter") != null
                    && !req.getParameter("otherdelimiter").equals("")) {
                separator = req.getParameter("otherdelimiter");
            }
        }
        String generated_request_query = "";
        String expression = "";
        String line = "";
        String groupby = "";
        String[] fields = req.getParameterValues("fields");
        if (commonReq) {
            if (req.getParameter("fields") != null) {
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("timed")) {
                        wantTimeStamp = true;
                    }
                    if ("pk".equalsIgnoreCase(fields[i]))
                        wantPk = true;
                    generated_request_query += ", " + fields[i];
                }
                if (!wantPk)
                    generated_request_query += ", pk";
            }
        } else {
            if (req.getParameter("fields") == null) {
                respond.println("Request ERROR");
                return;
            } else {
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].equals("timed")) {
                        wantTimeStamp = true;
                    }
                    if ("pk".equalsIgnoreCase(fields[i]))
                        wantPk = true;
                    generated_request_query += ", " + fields[i];
                }
                if (!wantPk)
                    generated_request_query += ", pk";
            }
            if (req.getParameter("groupby") != null) {
                if (req.getParameter("groupby").equals("timed")) {
                    groupByTimed = true;
                    int periodmeasure = 1;
                    if (req.getParameter("groupbytimed") != null) {
                        periodmeasure = new Integer(req.getParameter("groupbytimed"));
                        periodmeasure = java.lang.Math.max(periodmeasure, 1);
                    }
                    generated_request_query += ", Min(timed), FLOOR(timed/" + periodmeasure + ") period ";
                    groupby = "GROUP BY period";
                } else {
                    groupby = "GROUP BY " + req.getParameter("groupby");
                }
            }
        }

        String where = "";
        if (req.getParameter("critfield") != null) {
            try {
                String[] critJoin = req.getParameterValues("critJoin");
                String[] neg = req.getParameterValues("neg");
                String[] critfields = req.getParameterValues("critfield");
                String[] critop = req.getParameterValues("critop");
                String[] critval = req.getParameterValues("critval");
                for (int i = 0; i < critfields.length; i++) {
                    if (critop[i].equals("LIKE")) {
                        if (i > 0) {
                            where += " " + critJoin[i - 1] + " " + neg[i] + " " + critfields[i] + " LIKE '%"; // + critval[i] + "%'";
                        } else {
                            where += neg[i] + " " + critfields[i] + " LIKE '%"; // + critval[i] + "%'";
                        }
                        if (critfields[i].equals("timed")) {
                            try {
                                //Date d = sdf.parse(critval[i]);
                                Date d = sdf_from_ui.parse(critval[i]);
                                where += d.getTime();
                            } catch (Exception e) {
                                where += "0";
                            }
                        } else {
                            where += critval[i];
                        }
                        where += "%'";
                    } else {
                        if (i > 0) {
                            where += " " + critJoin[i - 1] + " " + neg[i] + " " + critfields[i] + " "
                                    + critop[i] + " "; //critval[i];
                        } else {
                            where += neg[i] + " " + critfields[i] + " " + critop[i] + " "; //critval[i];
                        }
                        if (critfields[i].equals("timed")) {
                            try {
                                //Date d = sdf.parse(critval[i]);
                                Date d = sdf_from_ui.parse(critval[i]);
                                where += d.getTime();
                            } catch (Exception e) {
                                where += "0";
                            }
                        } else {
                            where += critval[i];
                        }
                    }
                }
                where = " WHERE " + where;
            } catch (NullPointerException npe) {
                where = " ";
            }
        }

        if (!generated_request_query.equals("")) {
            generated_request_query = generated_request_query.substring(2);
            if (!commonReq) {
                expression = generated_request_query;
            }
            generated_request_query = "select " + generated_request_query + " from " + vsName + where
                    + "  order by timed DESC  ";
            if (commonReq)
                if (req.getParameter("nb") != null && req.getParameter("nb") != "") {
                    int nb = new Integer(req.getParameter("nb"));
                    if (nb < 0)
                        nb = 0;
                    String limit = "";
                    if (Main.getStorage(vsName).isH2() || Main.getStorage(vsName).isMysqlDB()) {
                        if (nb >= 0)
                            limit = "LIMIT " + nb + "  offset 0";
                        generated_request_query += limit;
                    } else if (Main.getStorage(vsName).isOracle()) {
                        generated_request_query = "select * from (" + generated_request_query
                                + " ) where rownum <" + (nb + 1);
                    }
                }

            generated_request_query += " " + groupby;
            generated_request_query += ";";

            if (req.getParameter("sql") != null) {
                res.setContentType("text/html");
                respond.println("# " + generated_request_query);
                return;
            }

            try {
                result = Main.getStorage(vsName).streamedExecuteQuery(generated_request_query, true);
            } catch (SQLException e) {
                logger.error("ERROR IN EXECUTING, query: " + generated_request_query + " from "
                        + req.getRemoteAddr() + "- " + req.getRemoteHost() + ": " + e.getMessage());
                return;
            }
            if (!result.hasMoreElements()) {
                res.setContentType("text/html");
                respond.println("No data corresponds to your request");
                return;
            }

            //get units in hash map
            Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs();
            HashMap<String, String> fieldToUnitMap = new HashMap<String, String>();
            VSensorConfig sensorConfig = null;
            while (vsIterator.hasNext()) {
                VSensorConfig senConfig = vsIterator.next();
                if (vsName.equalsIgnoreCase(senConfig.getName())) {
                    sensorConfig = senConfig;
                    DataField[] dataFieldArray = senConfig.getOutputStructure();
                    for (DataField df : dataFieldArray) {
                        String unit = df.getUnit();
                        if (unit == null || unit.trim().length() == 0)
                            unit = "";

                        fieldToUnitMap.put(df.getName().toLowerCase(), unit);
                    }
                    break;
                }
            }

            line = "";
            int nbFields = 0;
            if (responseCVS) {
                boolean firstLine = true;
                res.setHeader("content-disposition", "attachment; filename=" + filename + ".csv");
                respond.println("# " + generated_request_query);
                for (KeyValue df : sensorConfig.getAddressing()) {
                    respond.println(
                            "# " + df.getKey().toString().toLowerCase() + ":" + df.getValue().toString());
                }
                respond.println("# description:" + sensorConfig.getDescription());
                LinkedList<StreamElement> streamElements = new LinkedList<StreamElement>();
                while (result.hasMoreElements()) {
                    streamElements.add(result.nextElement());
                }
                while (!streamElements.isEmpty()) {
                    StreamElement se = streamElements.removeLast();
                    if (firstLine) {
                        nbFields = se.getFieldNames().length;
                        if (groupByTimed) {
                            nbFields--;
                        }
                        if (wantTimeStamp) {
                            line += separator + "time";
                        }
                        for (int i = 0; i < nbFields; i++)
                            //line += delimiter + se.getFieldNames()[i].toString();
                            if ((!groupByTimed) || (i != fields.length)) {
                                line += separator + fields[i];
                            } else {
                                line += separator + "time";
                            }

                        firstLine = false;
                        respond.println(line.substring(separator.length()));

                        line = "";

                        //units (second line)
                        if (wantTimeStamp) {
                            line += separator + "";
                        }
                        for (int i = 0; i < nbFields; i++) {
                            if ((!groupByTimed) || (i != fields.length)) {
                                line += separator + fieldToUnitMap.get(fields[i].toLowerCase());
                            } else {
                                line += separator + "";
                            }
                        }
                        respond.println(line.substring(separator.length()));
                    }

                    line = "";
                    if (wantTimeStamp) {
                        Date d = new Date(se.getTimeStamp());
                        line += separator + sdf.format(d);
                    }
                    for (int i = 0; i < nbFields; i++)
                        //line += delimiter+se.getData( )[ i ].toString( );

                        if (!commonReq && ((i >= fields.length) || (fields[i].contains("timed")))) {
                            line += separator + sdf.format(se.getData()[i]);
                        } else {
                            line += separator + se.getData()[i].toString();
                        }
                    respond.println(line.substring(separator.length()));
                }
            } else {
                boolean firstLine = true;
                res.setHeader("content-disposition", "attachment; filename=" + filename + ".xml");
                for (KeyValue df : sensorConfig.getAddressing()) {
                    respond.println(
                            "\t<!-- " + StringEscapeUtils.escapeXml(df.getKey().toString().toLowerCase()) + ":"
                                    + StringEscapeUtils.escapeXml(df.getValue().toString()) + " -->");
                }
                respond.println("\t<!-- description:"
                        + StringEscapeUtils.escapeXml(sensorConfig.getDescription()) + " -->");
                respond.println("<data>");
                LinkedList<StreamElement> streamElements = new LinkedList<StreamElement>();
                while (result.hasMoreElements()) {
                    streamElements.add(result.nextElement());
                }
                while (!streamElements.isEmpty()) {
                    StreamElement se = streamElements.removeLast();
                    if (firstLine) {
                        respond.println("\t<line>");
                        nbFields = se.getFieldNames().length;
                        if (groupByTimed) {
                            nbFields--;
                        }
                        if (wantTimeStamp) {
                            respond.println("\t\t<field unit=\"\">time</field>");
                        }
                        for (int i = 0; i < nbFields; i++) {
                            if ((!groupByTimed) || (i != fields.length)) {
                                respond.print(
                                        "\t\t<field unit=\"" + fieldToUnitMap.get(fields[i].toLowerCase()));
                                respond.println("\">" + fields[i] + "</field>");
                            } else {
                                respond.println("\t\t<field unit=\"\">time</field>");
                            }
                        }
                        //} else {
                        //    out.println("\t\t<field>"+expression+"</field>");
                        //}
                        respond.println("\t</line>");
                        firstLine = false;
                    }
                    line = "";
                    respond.println("\t<line>");
                    if (wantTimeStamp) {
                        Date d = new Date(se.getTimeStamp());
                        respond.println("\t\t<field>" + sdf.format(d) + "</field>");
                    }
                    for (int i = 0; i < nbFields; i++) {

                        //if ( !commonReq && expression.contains("timed")) {
                        if (!commonReq && ((i >= fields.length) || (fields[i].contains("timed")))) {
                            respond.println("\t\t<field>" + sdf.format(se.getData()[i]) + "</field>");
                        } else {
                            if (se.getData()[i] == null)
                                respond.println("\t\t<field>Null</field>");
                            else
                                respond.println("\t\t<field>" + se.getData()[i].toString() + "</field>");
                        }
                    }
                    respond.println("\t</line>");
                }
                respond.println("</data>");
            }
        }
        //*/
        else {
            res.setContentType("text/html");
            respond.println("Please select some fields");
        }
    } finally {
        if (result != null)
            result.close();
        respond.flush();
    }
}

From source file:pl.otros.logview.gui.actions.ShowCallHierarchyAction.java

protected void findCallHierarchyEvents(int selected, LogDataTableModel model,
        Collection<Integer> listEntryEvents, Collection<Integer> listOfEvents2) {
    LogData ld = model.getLogData(selected);
    String thread = ld.getThread();
    LinkedList<LogData> stack = new LinkedList<LogData>();
    HashMap<Integer, ArrayList<Integer>> allEventsInCallHierarchyMap = new HashMap<Integer, ArrayList<Integer>>();

    int rowCount = model.getRowCount();
    for (int i = 0; i < rowCount; i++) {
        LogData logData = model.getLogData(i);
        if (!logData.getThread().equals(thread)) {
            continue;
        }//from  www  . j ava2  s  .  c  o  m
        Message m = new Message(logData.getMessage());
        Integer stackSize = stack.size();
        if (!allEventsInCallHierarchyMap.containsKey(stackSize)) {
            allEventsInCallHierarchyMap.put(stackSize, new ArrayList<Integer>());
        }
        ArrayList<Integer> tempListOfEvents = allEventsInCallHierarchyMap.get(stackSize);
        if (m.getType().equals(MessageType.TYPE_ENTRY)) {
            stack.addLast(logData);
        } else if (m.getType().equals(MessageType.TYPE_EXIT) && theSameLogMethod(stack.getLast(), logData)) {
            stack.removeLast();
            tempListOfEvents.clear();
        } else {
            tempListOfEvents.add(logData.getId());
        }
        if (logData.getId() == ld.getId()) {
            break;
        }
    }

    for (ArrayList<Integer> list : allEventsInCallHierarchyMap.values()) {
        listOfEvents2.addAll(list);
    }

    for (LogData aStack : stack) {
        listEntryEvents.add(Integer.valueOf(aStack.getId()));
    }
}

From source file:gov.nih.nci.ncicb.cadsr.ocbrowser.struts.actions.ObjectClassRelationshipAction.java

/**
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 *
 * @return/*from www.ja v a 2s  .c om*/
 *
 * @throws IOException
 * @throws ServletException
 */
public ActionForward navigateOCR(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {

    DynaActionForm dynaForm = (DynaActionForm) form;
    String obcIdSeq = (String) dynaForm.get(OC_IDSEQ);
    String ocrIndex = (String) dynaForm.get(OCR_INDEX);
    String direction = (String) dynaForm.get(OCR_DIRECTION);
    Integer crumbsIndex = (Integer) dynaForm.get(OCR_BR_CRUMBS_INDEX);
    if (log.isDebugEnabled()) {
        log.info("ocr for With object class " + obcIdSeq);
        log.info("ocr index " + ocrIndex);
        log.info("direction " + direction);
    }

    try {

        //Get ocr navigation crumbs
        LinkedList crumbs = (LinkedList) getSessionObject(request, OCR_NAVIGATION_BEAN);
        if (crumbs == null) {
            crumbs = new LinkedList();
            setSessionObject(request, OCR_NAVIGATION_BEAN, crumbs, true);
        }
        if (crumbs.isEmpty()) {
            OCRNavigationBean bean = new OCRNavigationBean();
            ObjectClass currObjectClass = (ObjectClass) getSessionObject(request, OBJECT_CLASS);
            bean.setObjectClass(currObjectClass);
            crumbs.add(bean);
        } else {
            //Set the OCR_NAVIGATION_BEAN to current navigation path
            int currSize = crumbs.size();
            int currIndex = crumbsIndex.intValue();
            boolean nodesRemoved = false;
            for (int i = currIndex; i < currSize - 1; ++i) {
                crumbs.removeLast();
                nodesRemoved = true;
            }
            if (nodesRemoved) {
                OCRNavigationBean newLastNavBean = (OCRNavigationBean) crumbs.getLast();
                newLastNavBean.setOcr(null);
                newLastNavBean.setShowDirection(false);
            }
        }
        OCRNavigationBean lastNavBean = (OCRNavigationBean) crumbs.getLast();
        //Make sure same object is not navigated // need review
        if (lastNavBean.getObjectClass().getId() != obcIdSeq) {
            //get the list of ocrs depending on the direction clicked
            List oldList = (List) getSessionObject(request, direction);
            ObjectClassRelationship navigatedOCR = (ObjectClassRelationship) oldList
                    .get(Integer.parseInt(ocrIndex));

            OCBrowserService service = this.getApplicationServiceLocator().findOCBrowserService();

            ObjectClass objClass = service.getObjectClass(obcIdSeq);
            List ocrs = service.getAssociationsForOC(obcIdSeq);
            //Set the current OCRID
            dynaForm.set(CURR_OCR_IDSEQ, navigatedOCR.getId());

            Map ocrMap = OCUtils.sortByOCRTypes(ocrs, obcIdSeq);

            setSessionObject(request, OBJECT_CLASS, objClass, true);
            setSessionObject(request, OUT_GOING_OCRS, ocrMap.get(OUT_GOING_OCRS), true);
            setSessionObject(request, IN_COMMING_OCRS, ocrMap.get(IN_COMMING_OCRS), true);
            setSessionObject(request, BIDIRECTIONAL_OCRS, ocrMap.get(BIDIRECTIONAL_OCRS), true);

            //Update old bean
            lastNavBean.setOcr(navigatedOCR);
            lastNavBean.setDirection(direction);
            lastNavBean.setShowDirection(true);

            //Add new link
            OCRNavigationBean bean = new OCRNavigationBean();
            bean.setObjectClass(objClass);
            crumbs.add(bean);
            //set the crumbs index
            dynaForm.set(OCR_BR_CRUMBS_INDEX, new Integer(crumbs.size() - 1));
        }
    } catch (ServiceLocatorException exp) {
        if (log.isErrorEnabled()) {
            log.error("Exception on getObjectClassRelationships obid= " + obcIdSeq);
        }
        return mapping.findForward(FAILURE);
    }
    return mapping.findForward(SUCCESS);
}

From source file:com.multimedia.service.wallpaper.CmsWallpaperService.java

@Override
public long uploadWallpapers(User uploader, Long id_pages, StatusBean usb) {
    File upload_dir = new File(wallpaper_service.getUploadPath());
    OnlyFilesFilter filenameFilter = new OnlyFilesFilter();
    usb.setDone(0);//from   ww w  . j a  v  a 2  s . co  m
    usb.setTotal(scanFolder(upload_dir));
    //logger.debug("starting upload process id_pages="+id_pages);
    if (upload_dir.exists()) {
        File description_file;
        Long id_pages_cur;
        boolean pre_uploaded;
        Wallpaper wallpaper;
        LinkedList<File> files = new LinkedList<File>();
        files.addLast(upload_dir);

        Set<String> dimmensions_set = wallpaper_service.getDimmensions().keySet();

        int restart_count = 0;

        while (!files.isEmpty()) {
            File f = files.removeLast();
            pre_uploaded = false;
            //logger.debug("test file: '"+f.getAbsolutePath()+"'");
            if (f.isDirectory()) {
                //search for DESCRIPTION_FILE
                description_file = new File(f, DESCRIPTION_FILE);
                if (description_file.exists()) {
                    id_pages_cur = null;
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(new FileInputStream(description_file), "UTF-8"));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("id=")) {
                                id_pages_cur = Long.parseLong(line.substring(3), 10);
                            } else if (line.startsWith("pre_uploaded=true")) {
                                //means that this folder contains subfolders with pre uploaded images
                                //i.e. wallpapers are allready resized and are stored in an appropriate folders
                                //but they still must be checked
                                pre_uploaded = true;
                            }
                        }
                    } catch (IOException ex) {
                        logger.error("", ex);
                    }
                } else {
                    id_pages_cur = id_pages;
                }
                File[] files_temp = f.listFiles();
                for (File tmp : files_temp) {
                    if (tmp.isFile()) {
                        if (!tmp.getName().equals(DESCRIPTION_FILE) && id_pages_cur != null) {
                            wallpaper = new Wallpaper();
                            wallpaper.setUser(uploader);
                            wallpaper.setId_pages(id_pages_cur);
                            wallpaper.setActive(Boolean.TRUE);
                            wallpaper.setContent_file(tmp);

                            usb.setCur_name(tmp.getAbsolutePath());
                            logger.debug("normal file uploading: '" + tmp.getAbsolutePath() + "'");

                            if (insert(wallpaper)) {
                                tmp.delete();
                                usb.increaseDone(1);
                                restart_count++;
                                if (restart_count == UPLOAD_RESTART_COUNT) {
                                    restart_count = 0;
                                    wallpaper_service.restartTransaction();
                                }
                            }
                        } //else error
                    } else if (!pre_uploaded) {
                        files.addLast(tmp);
                    }
                }
                if (pre_uploaded) {
                    //uploading pre_uploaded files if any
                    File pre_uploaded_folder = new File(f, Utils.FULL_DIMMENSION_NAME);
                    if (pre_uploaded_folder.exists() && pre_uploaded_folder.isDirectory()) {
                        files_temp = pre_uploaded_folder.listFiles(filenameFilter);
                        for (File tmp : files_temp) {
                            wallpaper = new Wallpaper();
                            wallpaper.setUser(uploader);
                            wallpaper.setId_pages(id_pages_cur);
                            wallpaper.setActive(Boolean.TRUE);
                            wallpaper.setContent_file(tmp);

                            logger.debug("pre_uploaded file uploading: '" + tmp.getAbsolutePath() + "'");
                            if (insert(wallpaper, f)) {
                                Iterator<String> dimmensions = dimmensions_set.iterator();
                                while (dimmensions.hasNext()) {
                                    String dimmension = dimmensions.next();
                                    File pre_uploaded_image = new File(f,
                                            dimmension + File.separator + tmp.getName());
                                    if (!pre_uploaded_image.delete()) {
                                        pre_uploaded_image.deleteOnExit();
                                    }
                                }
                                usb.increaseDone(1);
                                restart_count++;
                                if (restart_count == UPLOAD_RESTART_COUNT) {
                                    restart_count = 0;
                                    wallpaper_service.restartTransaction();
                                }
                            }
                        }
                        //deleting pre_uploaded folder if it contains no images
                        if (pre_uploaded_folder.listFiles(filenameFilter).length == 0) {
                            FileUtils.deleteFiles(f, true);
                        }
                    }
                }
            }
        }
    }
    return usb.getDone();
}

From source file:marytts.modules.ModuleRegistry.java

/**
 * This method recursively calls itself.
 * It forward-constructs a list of seen types (upon test),
 * and backward-constructs a list of required modules (upon success).
 *
 * @param sourceType//from   w w  w .ja  v  a 2s  .c om
 * @param targetType
 * @param locale
 * @param voice
 * @param seenTypes
 * @return
 */
private static LinkedList<MaryModule> modulesRequiredForProcessing(MaryDataType sourceType,
        MaryDataType targetType, Locale locale, Voice voice, LinkedList<MaryDataType> seenTypes) {
    // Terminating condition:
    if (sourceType.equals(targetType)) {
        logger.debug("found path through modules");
        return new LinkedList<MaryModule>();
    }
    // Recursion step:
    // Any voice-specific modules?
    List<MaryModule> candidates = null;
    // TODO: the following should be obsolete as soon as we are properly using the voice index in ModuleRegistry
    if (voice != null)
        candidates = voice.getPreferredModulesAcceptingType(sourceType);
    if (candidates == null || candidates.isEmpty()) { // default: use all available modules
        candidates = get(sourceType, locale, voice);
    }
    if (candidates == null || candidates.isEmpty()) {
        // no module can handle this type
        return null;
    }
    for (Iterator<MaryModule> it = candidates.iterator(); it.hasNext();) {
        MaryModule candidate = it.next();
        MaryDataType outputType = candidate.outputType();
        // Ignore candidates that would bring us to a data type that we
        // have already seen (i.e., that would lead to a loop):
        if (!seenTypes.contains(outputType)) {
            seenTypes.add(outputType);
            logger.debug("Module " + candidate.name() + " converts " + sourceType.name() + " into " + outputType
                    + " (locale " + locale + ", voice " + voice + ")");
            // recursive call:
            LinkedList<MaryModule> path = modulesRequiredForProcessing(outputType, targetType, locale, voice,
                    seenTypes);
            if (path != null) {
                // success, found a path of which candidate is the first
                // step
                path.addFirst(candidate);
                return path;
            } // else, try next candidate
            seenTypes.removeLast();
        }
    }
    // We get here only if none of the candidates lead to a valid path
    return null; // failure
}

From source file:org.openxdm.xcap.client.test.error.BadRequestTest.java

@Test
public void test() throws HttpException, IOException, JAXBException, InterruptedException {

    // create uri      
    UserDocumentUriKey key = new UserDocumentUriKey(appUsage.getAUID(), user, documentName);

    String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + "<list/>"
            + "<list name=\"enemies\"/>" + "</resource-lists>";

    // send put request and get response
    Response response = client.put(key, appUsage.getMimetype(), content, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be 201", response.getCode() == 201);

    // create element selector      
    LinkedList<ElementSelectorStep> elementSelectorSteps = new LinkedList<ElementSelectorStep>();
    ElementSelectorStep step1 = new ElementSelectorStep("pre1:resource-lists");
    ElementSelectorStep step2 = new ElementSelectorStepByPos("pre2:list", 1);
    elementSelectorSteps.add(step1);/*from   w w w .  j  a v  a2  s.  c  o m*/
    elementSelectorSteps.addLast(step2);
    // set namespace bindings 
    Map<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("pre1", appUsage.getDefaultDocumentNamespace());

    // create attr put uri
    UserAttributeUriKey attrKey = new UserAttributeUriKey(appUsage.getAUID(), user, documentName,
            new ElementSelector(elementSelectorSteps), new AttributeSelector("name"), namespaces);
    // send put request and get response
    Response putResponse = client.put(attrKey, AttributeResource.MIMETYPE, "friends", null);
    // check put response, must be bad request
    assertTrue("Put response must exists", putResponse != null);
    assertTrue("Put response code should be " + BadRequestException.RESPONSE_STATUS,
            putResponse.getCode() == BadRequestException.RESPONSE_STATUS);

    // create attr delete & get uri
    elementSelectorSteps.removeLast();
    step2 = new ElementSelectorStepByPos("pre2:list", 2);
    elementSelectorSteps.addLast(step2);
    UserAttributeUriKey anotherAttrKey = new UserAttributeUriKey(appUsage.getAUID(), user, documentName,
            new ElementSelector(elementSelectorSteps), new AttributeSelector("name"), null);

    // send get request and get response
    Response getResponse = client.get(anotherAttrKey, null);
    // check get response, must be bad request
    assertTrue("Delete response must exists", getResponse != null);
    assertTrue("Delete response code should be " + BadRequestException.RESPONSE_STATUS,
            getResponse.getCode() == BadRequestException.RESPONSE_STATUS);

    // send delete request and get response
    Response deleteResponse = client.delete(anotherAttrKey, null);
    // check put response, must be bad request
    assertTrue("Delete response must exists", deleteResponse != null);
    assertTrue("Delete response code should be " + BadRequestException.RESPONSE_STATUS,
            deleteResponse.getCode() == BadRequestException.RESPONSE_STATUS);

    // cleanup
    client.delete(key, null);
}

From source file:edu.umd.cs.guitar.ripper.Ripper.java

/**
 * Rip a component//  ww  w. j  av  a2s.  c om
 *
 * As of now this method does not propagate exceptions.
 * It needs to be modified to progate exceptions. All callers
 * need to be modified to handle exceptions.
 *
 * <p>
 * 
 * @param component
 * @return
 */
public ComponentType ripComponent(GComponent component, GWindow window) {
    GUITARLog.log.info("");
    GUITARLog.log.info("----------------------------------");
    GUITARLog.log.info("Ripping component: ");
    GUITARLog.log.info("Signature: ");

    printComponentInfo(component, window);

    // 1. Rip special/customized components
    for (GComponentFilter cm : lComponentFilter) {
        if (cm.isProcess(component, window)) {
            GUITARLog.log.info("Filter " + cm.getClass().getSimpleName() + " is applied");

            return cm.ripComponent(component, window);
        }
    }

    // 2. Rip regular components
    ComponentType retComp = null;
    try {
        retComp = component.extractProperties();
        ComponentTypeWrapper compA = new ComponentTypeWrapper(retComp);

        if (useImage) {
            String sUUID = null;
            try {
                sUUID = captureImage(component);
            } catch (AWTException e) {
                // Ignore AWTException. sUUID is null.
            } catch (IOException e) {
                throw e;
            }

            if (sUUID != null) {
                compA.addProperty(GUITARConstants.UUID_TAG_NAME, sUUID);
            }
        }

        GUIType guiType = null;

        if (window != null) {
            guiType = window.extractGUIProperties();
        }

        retComp = compA.getDComponentType();

        // 2.1 Try to perform action on the component
        // to reveal more windows/components

        // clear window opened cache before performing actions
        monitor.resetWindowCache();

        if (monitor.isExpandable(component, window)) {
            monitor.expandGUI(component);
        } else {
            GUITARLog.log.info("Component is Unexpandable");
        }

        // Trigger terminal widget

        LinkedList<GWindow> lClosedWindows = monitor.getClosedWindowCache();

        String sTitle = window.getTitle();

        if (lClosedWindows.size() > 0) {

            GUITARLog.log.debug("!!!!! Window closed");

            for (GWindow closedWin : lClosedWindows) {
                String sClosedWinTitle = closedWin.getTitle();

                // Only consider widget closing the current window
                if (sTitle.equals(sClosedWinTitle)) {

                    GUITARLog.log.debug("\t" + sClosedWinTitle);

                    List<FullComponentType> lCloseComp = lCloseWindowComp.getFullComponent();

                    FullComponentType cCloseComp = factory.createFullComponentType();
                    cCloseComp.setWindow(closedWin.extractWindow().getWindow());
                    cCloseComp.setComponent(retComp);
                    lCloseComp.add(cCloseComp);
                    lCloseWindowComp.setFullComponent(lCloseComp);
                } // if
            } // for
        } // if

        if (monitor.isNewWindowOpened()) {

            List<FullComponentType> lOpenComp = lOpenWindowComps.getFullComponent();
            FullComponentType cOpenComp = factory.createFullComponentType();
            cOpenComp.setWindow(window.extractWindow().getWindow());
            cOpenComp.setComponent(retComp);
            lOpenComp.add(cOpenComp);
            lOpenWindowComps.setFullComponent(lOpenComp);

            LinkedList<GWindow> lNewWindows = monitor.getOpenedWindowCache();
            monitor.resetWindowCache();
            GUITARLog.log.info(lNewWindows.size() + " new window(s) opened!!!");
            for (GWindow newWins : lNewWindows) {
                GUITARLog.log.info("*\t Title:*" + newWins.getTitle() + "*");
            }

            // Process the opened windows in a FIFO order
            while (!lNewWindows.isEmpty()) {

                GWindow gNewWin = lNewWindows.getLast();
                lNewWindows.removeLast();

                GComponent gWinComp = gNewWin.getContainer();

                if (gWinComp != null) {

                    // Add invokelist property for the component
                    String sWindowTitle = gNewWin.getTitle();
                    compA = new ComponentTypeWrapper(retComp);
                    compA.addValueByName(GUITARConstants.INVOKELIST_TAG_NAME, sWindowTitle);

                    GUITARLog.log.debug(sWindowTitle + " recorded");

                    retComp = compA.getDComponentType();

                    // Check ignore window
                    if (!monitor.isIgnoredWindow(gNewWin)) {

                        if (!monitor.isRippedWindow(gNewWin)) {
                            gNewWin.setRoot(false);
                            monitor.addRippedList(gNewWin);

                            GUIType dWindow = ripWindow(gNewWin);

                            if (dWindow != null)
                                dGUIStructure.getGUI().add(dWindow);
                        } else {
                            GUITARLog.log.info("Window is ripped!!!");
                        }

                    } else {
                        GUITARLog.log.info("Window is ignored!!!");
                    }
                }

                monitor.closeWindow(gNewWin);
            }
        }

        // TODO: check if the component is still available after ripping
        // its child window
        List<GComponent> gChildrenList = component.getChildren();
        int nChildren = gChildrenList.size();
        int i = 0;

        // Debug

        String lChildren = "[";
        for (int j = 0; j < nChildren; j++) {
            lChildren += gChildrenList.get(j).getTitle() + " - " + gChildrenList.get(j).getClassVal() + "; ";
        }
        lChildren += "]";
        GUITARLog.log.debug("*" + component.getTitle() + "* in window *" + window.getTitle() + "* has "
                + nChildren + " children: " + lChildren);

        // End debug

        while (i < nChildren) {
            GComponent gChild = gChildrenList.get(i++);
            ComponentType guiChild = ripComponent(gChild, window);

            if (guiChild != null) {
                ((ContainerType) retComp).getContents().getWidgetOrContainer().add(guiChild);
            }

            if (nChildren < gChildrenList.size()) {
                nChildren = gChildrenList.size();
            }
        }

    } catch (Exception e) {
        if (e.getClass().getName().contains("StaleElementReferenceException")) {
            /**
             * This can happen when performing an action causes a page
             * navigation in the current window, for example, when
             * submitting a form.
             */
            GUITARLog.log.warn("Element went away: " + e.getMessage());
        } else {
            // TODO: Must throw exception
            GUITARLog.log.error("ripComponent exception", e);
        }

        /**
         * We'll return the component we calculated anyway so it
         * gets added to the GUI map. I'm not entirely sure this
         * is the right thing to do, but it gets us further anyway.
         */
        return retComp;
    }

    return retComp;
}

From source file:org.accelio.jxio.WorkerCache.java

Worker getCachedWorker(String clientId) {
    Worker w;/* w w w  .ja v  a2s. c o  m*/
    LinkedList<Worker> clientWorkers = workersCache.get(clientId);
    // first time this client connects or wasn't connected for a long time and was removed by LRU
    if (clientWorkers == null) {
        if (LOG.isDebugEnabled())
            LOG.debug("client id " + clientId + " wasn't found in hash");
        w = wp.getWorker();
        if (w != null) {
            LinkedList<Worker> list = new LinkedList<Worker>();
            list.add(w);
            workersCache.put(clientId, list);
        }
        return w;
    }
    // look for free worker in client's previously connected workers
    int pos = 0;
    while (pos < clientWorkers.size()) {
        w = clientWorkers.get(pos);
        if (w.isFree()) {
            if (LOG.isDebugEnabled())
                LOG.debug("found free worker" + w + " for client id " + clientId);
            clientWorkers.remove(pos);
            clientWorkers.addFirst(w);
            return w;
        }
        pos++;
    }
    // no free workers to use from previously connected, get a new one
    w = wp.getWorker();
    if (w != null) {
        clientWorkers.addFirst(w);
        if (clientWorkers.size() > MAX_ENTRY_WORKERS) {
            clientWorkers.removeLast();
        }
    }
    return w;
}

From source file:org.openxdm.xcap.client.test.error.UnsupportedMediaTypeTest.java

@Test
public void test() throws HttpException, IOException, JAXBException, InterruptedException {

    // create exception for return codes
    UnsupportedMediaTypeException exception = new UnsupportedMediaTypeException();

    String documentContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<resource-lists xmlns=\"urn:ietf:params:xml:ns:resource-lists\">" + "<list/>"
            + "</resource-lists>";

    // create uri key      
    UserDocumentUriKey documentKey = new UserDocumentUriKey(appUsage.getAUID(), user, documentName);

    // CREATES/*from  w  w w .  j a  v  a 2  s .co m*/

    // send put request and get response
    Response response = client.put(documentKey, "badmimetype", documentContent, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    // send put request and get response
    response = client.put(documentKey, appUsage.getMimetype(), documentContent, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be 201", response.getCode() == 201);

    String elementContent = "<list name=\"friends\"/>";

    // create element selector      
    LinkedList<ElementSelectorStep> elementSelectorSteps = new LinkedList<ElementSelectorStep>();
    ElementSelectorStep step1 = new ElementSelectorStep("resource-lists");
    ElementSelectorStep step2 = new ElementSelectorStepByAttr("list", "name", "friends");
    elementSelectorSteps.add(step1);
    elementSelectorSteps.addLast(step2);
    ElementSelector elementSelector = new ElementSelector(elementSelectorSteps);

    // create element uri key as a fake document uri key, no other way to send a bad mimetype      
    UserElementUriKey elementKey = new UserElementUriKey(appUsage.getAUID(), user, documentName,
            elementSelector, null);
    UnsupportedMediaTypeFakeDocumentUriKey evilKey = new UnsupportedMediaTypeFakeDocumentUriKey(elementKey);

    // send put request and get response      
    response = client.put(evilKey, "badmimetype", elementContent, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    elementSelectorSteps.removeLast();
    ElementSelectorStep step3 = new ElementSelectorStep("list");
    elementSelectorSteps.add(step3);
    elementSelector = new ElementSelector(elementSelectorSteps);

    AttributeSelector attributeSelector = new AttributeSelector("name");

    // create uri key      
    UserAttributeUriKey attributeKey = new UserAttributeUriKey(appUsage.getAUID(), user, documentName,
            elementSelector, attributeSelector, null);
    AnotherUnsupportedMediaTypeFakeDocumentUriKey anotherEvilKey = new AnotherUnsupportedMediaTypeFakeDocumentUriKey(
            attributeKey);
    // send put request and get response
    response = client.put(anotherEvilKey, "badmimetype", "friends", null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    // REPLACES

    // send put request and get response
    response = client.put(documentKey, "badmimetype", documentContent, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    // create uri key      
    elementKey = new UserElementUriKey(appUsage.getAUID(), user, documentName, elementSelector, null);

    // send put request and get response
    response = client.put(evilKey, "badmimetype", elementContent, null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    // send put request and get response
    response = client.put(attributeKey, AttributeResource.MIMETYPE, "friends", null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be 201", response.getCode() == 201);

    // send put request and get response
    response = client.put(anotherEvilKey, "badmimetype", "friends", null);

    // check put response
    assertTrue("Put response must exists", response != null);
    assertTrue("Put response code should be " + exception.getResponseStatus(),
            response.getCode() == exception.getResponseStatus());

    // clean up
    client.delete(documentKey, null);
}