Example usage for java.util ArrayList isEmpty

List of usage examples for java.util ArrayList isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:prop_add_serv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w  w.ja v  a 2s . co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();
    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");
            System.out.println(ln.getUId());
            String pradd1 = "";
            String pradd2 = "";
            String prage = "";
            String prarea = "";
            String prbhk = "";
            String prdescrip = "";
            String prprice = "";
            String prcity = "";
            String prstate = "";
            String prname = "";
            String prtype = "";

            String prfarea = "";
            String prphoto1 = "";
            String prphoto2 = "";
            String prphoto3 = "";
            String prphoto4 = "";

            //             
            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("pname")) {
                        //getting value of field
                        prname = fileItem.getString();
                        System.out.println(prname);
                    } else if (fieldName.equals("price")) {
                        //getting value of field
                        prprice = fileItem.getString();
                        System.out.println(prprice);
                    } else if (fieldName.equals("city")) {
                        prcity = fileItem.getString();
                        System.out.println(prcity);
                    } else if (fieldName.equals("state")) {
                        prstate = fileItem.getString();
                        System.out.println(prstate);
                    } else if (fieldName.equals("area")) {
                        prarea = fileItem.getString();
                        System.out.println(prarea);
                    } else if (fieldName.equals("pbhk")) {
                        prbhk = fileItem.getString();
                        System.out.println(prbhk);
                    } else if (fieldName.equals("pdescription")) {
                        prdescrip = fileItem.getString();
                        System.out.println(prdescrip);

                    } else if (fieldName.equals("ptype")) {
                        prtype = fileItem.getString();
                        System.out.println(prtype);

                    } else if (fieldName.equals("paddress1")) {
                        pradd1 = fileItem.getString();
                        System.out.println(pradd1);
                    } else if (fieldName.equals("paddress2")) {
                        pradd2 = fileItem.getString();
                        System.out.println(pradd2);
                    } else if (fieldName.equals("page")) {
                        prage = fileItem.getString();
                        System.out.println(prage);
                    } else if (fieldName.equals("pfarea")) {
                        prfarea = fileItem.getString();
                        System.out.println(prfarea);
                    }
                } else {

                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("photo1")) {

                        //getting name of file
                        prphoto1 = new File(fileItem.getName()).getName();

                        //get the extension of file by diving name into substring
                        // String extension=prphoto.substring(prphoto.indexOf(".")+1,prphoto.length());;
                        //rename file...concate name and extension
                        //prphoto=prname+"."+extension;
                        //System.out.println(prphoto);
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            // FOR UBUNTU add GETRESOURCE  and GETPATH
                            // String filePath = this.getServletContext().getResource("/images").getPath() + "\\";
                            fileItem.write(new File(fp + prphoto1));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    //PHOTO 2

                    else if (fieldName.equals("photo2")) {
                        prphoto2 = new File(fileItem.getName()).getName();

                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto2));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }

                    }
                    //PHOTO 3
                    else if (fieldName.equals("photo3")) {

                        prphoto3 = new File(fileItem.getName()).getName();
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto3));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                    //PHOTO 4
                    else if (fieldName.equals("photo4")) {
                        prphoto4 = new File(fileItem.getName()).getName();
                        try {

                            String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/";
                            fileItem.write(new File(fp + prphoto4));
                        } catch (Exception ex) {
                            out.println(ex.toString());
                        }
                    }

                }

            }

            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();

            String op = "";
            Criteria cr = ss.createCriteria(StateMaster.class);
            cr.add(Restrictions.eq("sId", Integer.parseInt(prstate)));
            ArrayList<StateMaster> ar = (ArrayList<StateMaster>) cr.list();
            if (ar.isEmpty()) {

            } else {
                StateMaster sm = ar.get(0);
                op = sm.getSName();

            }

            String city = "";
            Criteria cr2 = ss.createCriteria(CityMaster.class);
            cr2.add(Restrictions.eq("cityId", Integer.parseInt(prcity)));
            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>) cr2.list();
            System.out.println("----------" + ar2.size());
            if (ar2.isEmpty()) {

            } else {
                city = ar2.get(0).getCityName();
                System.out.println("-------" + city);
            }

            String area = "";
            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            cr3.add(Restrictions.eq("areaId", Integer.parseInt(prarea)));
            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>) cr3.list();
            System.out.println("----------" + ar3.size());
            if (ar3.isEmpty()) {

            } else {
                area = ar3.get(0).getAreaName();
                System.out.println("-------" + area);
            }

            PropDetail pd = new PropDetail();

            pd.setUId(ln);

            pd.setPAge(Integer.parseInt(prage));

            pd.setPBhk(prbhk);
            pd.setPDescription(prdescrip.trim());
            pd.setPAdd1(pradd1);
            pd.setPAdd2(pradd2);
            pd.setPPrice(Integer.parseInt(prprice));

            pd.setPCity(city);
            pd.setPState(op);
            pd.setPArea(area);

            pd.setPName(prname);
            pd.setPType(prtype);
            pd.setPImg1(prphoto1);
            System.out.println(prphoto1);
            System.out.println(prphoto2);
            pd.setPImg2(prphoto2);

            pd.setPImg3(prphoto3);
            pd.setPImg4(prphoto4);

            pd.setPFloor(Integer.parseInt(prfarea));

            ss.save(pd);

            tr.commit();

            RequestDispatcher rd = request.getRequestDispatcher("property_search_1.jsp");
            rd.forward(request, response);
        }
    } catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

From source file:com.aliyun.odps.ship.download.DshipDownload.java

private void multiThreadDownload() throws TunnelException {
    ArrayList<Callable<Long>> callList = new ArrayList<Callable<Long>>();
    for (final FileDownloader downloader : workItems) {
        Callable<Long> call = new Callable<Long>() {
            @Override//from ww w.j  av  a 2 s .c  om
            public Long call() throws Exception {
                downloader.download();
                return downloader.getWrittenBytes();
            }
        };
        callList.add(call);
    }

    ExecutorService executors = Executors.newFixedThreadPool(threads);
    try {
        List<Future<Long>> futures = executors.invokeAll(callList);
        ArrayList<String> failedThread = new ArrayList<String>();
        for (int i = 0; i < futures.size(); ++i) {
            try {
                writtenBytes += futures.get(i).get();
            } catch (ExecutionException e) {
                e.printStackTrace();
                failedThread.add(String.valueOf(i));
            }
        }
        if (!failedThread.isEmpty()) {
            throw new TunnelException("Slice ID:" + StringUtils.join(failedThread, ",") + " Failed.");
        }
    } catch (InterruptedException e) {
        throw new UserInterruptException(e.getMessage());
    }
}

From source file:com.dalamar.watcher.TrainStationWatcher.java

public void diffWithDB() {

    ArrayList<LateTrain> trainsInDB = (ArrayList<LateTrain>) ltd.clear().betweenDates(date, date).station(name)
            .executeQuery();//from w  ww  .  j a  v a 2 s .co  m

    LateTrain[] trains = null;
    try {
        trains = fetchLateTrains();
    } catch (IOException ex) {
        Logger.getLogger(TrainStationWatcher.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (trains == null)
        return;

    if (trainsInDB.isEmpty()) {
        for (LateTrain tr : trains) {
            tr.setToStation(name);
            tr.setDateCaptured(date); // temporary for test. please fix later to Calendar.getInstance().getTime();
            ltd.save(tr);
        }
    }

    else {
        HashMap<String, LateTrain> trainNumToTrain = getTrainMap(trainsInDB);
        for (LateTrain tr : trains) {
            if (trainNumToTrain.containsKey(tr.getTrainNumber())) {
                diffSingleTrain(tr, trainNumToTrain);
            } else {
                tr.setToStation(this.name);
                tr.setDateCaptured(date);// temporary for test. please fix later to Calendar.getInstance().getTime();
                ltd.save(tr);
            }
        }
    }

    rectifyInDB();

}

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.PlayByPlayPerfMongo.java

@Test
@Override/* w  w  w .ja  va 2 s  . com*/
public void postQueryTest() {
    try {
        int numQueries = 50;
        Date start = new Date();
        MongoClient mongoClient = new MongoClient(uri);
        //mongoClient.setWriteConcern(WriteConcern.MAJORITY);
        DB db = mongoClient.getDB(this.getDb().name());
        final DBCollection coll = db.getCollection(this.getDb().name());
        for (int i = 0; i < numQueries; i++) {
            logger.debug("Query: " + i);
            ArrayList<String> res = new ArrayList<>();
            DBCursor curser = coll.find(new BasicDBObject("dwn", 4));
            int count = 0;
            while (curser.hasNext() && count++ < 10000) {
                DBObject o = curser.next();
                assertNotNull(o);
                assertTrue(o.toString().contains("4"));
                res.add(o.toString());
            }
            assertFalse(res.isEmpty());
        }
        Date end = new Date();
        long executionTime = end.getTime() - start.getTime();
        double inSeconds = (double) executionTime / 1000d;
        double average = (double) inSeconds / (double) numQueries;
        output.info("PBP-Mongo: Time to execute (single field) for " + numQueries + " is: " + inSeconds
                + " seconds");
        output.info("PBP-Mongo: Averge time for single field is: " + average);
    } catch (UnknownHostException e) {
        logger.error("Couldn't run test.", e);
        throw new RuntimeException(e);
    }
}

From source file:com.mtgi.analytics.aop.config.v11.BtHttpRequestsBeanDefinitionParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    //compile required constructor arguments from attributes and nested elements.  first up, event type.
    builder.addConstructorArg(element.getAttribute(ATT_EVENT_TYPE));

    //manager ID from enclosing tag, or ref attribute.
    String managerId = parserContext.isNested()
            ? (String) parserContext.getContainingBeanDefinition().getAttribute("id")
            : element.getAttribute(BtNamespaceConstants.ATT_TRACKING_MANAGER);
    builder.addConstructorArgReference(managerId);

    //parameter list to include in event data, if any.
    String paramList = element.getAttribute(ATT_PARAMETERS);
    builder.addConstructorArg(parseList(paramList));

    //parameter list to include in event name, if any
    String nameList = element.getAttribute(ATT_NAME_PARAMETERS);
    builder.addConstructorArg(parseList(nameList));

    //URI patterns, if any.  can be specified as attribute or nested elements.
    ArrayList<Pattern> accum = new ArrayList<Pattern>();
    if (element.hasAttribute(ATT_URI_PATTERN))
        accum.add(Pattern.compile(element.getAttribute(ATT_URI_PATTERN)));

    NodeList nl = element.getElementsByTagNameNS("*", ATT_URI_PATTERN);
    for (int i = 0; i < nl.getLength(); ++i) {
        Element e = (Element) nl.item(i);
        String pattern = e.getTextContent();
        if (StringUtils.hasText(pattern))
            accum.add(Pattern.compile(pattern));
    }//  w w w.  j  a  v  a2 s  .  c  om

    if (accum.isEmpty())
        builder.addConstructorArg(null);
    else
        builder.addConstructorArg(accum.toArray(new Pattern[accum.size()]));

    if (parserContext.isNested())
        parserContext.getReaderContext().registerWithGeneratedName(builder.getBeanDefinition());
}

From source file:com.clustercontrol.jobmanagement.bean.JobCommandInfo.java

private boolean equalsArray(ArrayList<?> list1, ArrayList<?> list2) {
    if (list1 != null && !list1.isEmpty()) {
        if (list2 != null && list1.size() == list2.size()) {
            Object[] ary1 = list1.toArray();
            Object[] ary2 = list2.toArray();
            Arrays.sort(ary1);/* w ww.  j  a  va2  s. c o  m*/
            Arrays.sort(ary2);

            for (int i = 0; i < ary1.length; i++) {
                if (!ary1[i].equals(ary2[i])) {
                    if (m_log.isTraceEnabled()) {
                        m_log.trace("equalsArray : " + ary1[i] + "!=" + ary2[i]);
                    }
                    return false;
                }
            }
            return true;
        }
    } else if (list2 == null || list2.isEmpty()) {
        return true;
    }
    return false;
}

From source file:org.apache.usergrid.java.client.model.UsergridEntity.java

public void pop(@NotNull final String name) {
    ArrayList<Object> arrayToPop = this.getArrayToPopOrShift(name);
    if (arrayToPop != null && !arrayToPop.isEmpty()) {
        arrayToPop.remove(arrayToPop.size() - 1);
        this.putProperty(name, arrayToPop);
    }//from w w w .  j ava  2 s .com
}

From source file:com.sckftr.android.utils.net.Network.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result.//from  www  .  j  av a  2  s . co m
 *
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param handler
 *@param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
*            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
*            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.        @return The result of the webservice call.
 */
static <Out> Out execute(Context context, String urlValue, Method method, Executor<BufferedReader, Out> handler,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws NetworkConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        //if (Log.canLog(Log.DEBUG)) {
        Log.d(TAG, method.toString() + ": " + urlValue);

        if (parameterList != null && !parameterList.isEmpty()) {
            //Log.d(TAG, "Parameters:");
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                Log.d(TAG, message);
            }

            //Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
        }

        if (postText != null) {
            Log.d(TAG, "Post data: " + postText);
        }

        if (headerMap != null && !headerMap.isEmpty()) {
            //Log.d(TAG, "Headers:");
            for (Entry<String, String> header : headerMap.entrySet()) {
                //Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
            }
        }
        //}

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new NetworkConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String err = evaluateStream(errorStream, new StringReaderHandler(), isGzip);
            throw new NetworkConnectionException(err, responseCode);
        }

        return evaluateStream(connection.getInputStream(), handler, isGzip);

    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new NetworkConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new NetworkConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new NetworkConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.apache.usergrid.java.client.model.UsergridEntity.java

public void shift(@NotNull final String name) {
    ArrayList<Object> arrayToShift = this.getArrayToPopOrShift(name);
    if (arrayToShift != null && !arrayToShift.isEmpty()) {
        arrayToShift.remove(0);//  ww  w.j  a  v a 2s.c o m
        this.putProperty(name, arrayToShift);
    }
}

From source file:co.carlosandresjimenez.gotit.backend.controller.GotItSvc.java

@RequestMapping(value = FOLLOW_REQUESTS_PATH, method = RequestMethod.GET)
public @ResponseBody ArrayList<User> getFollowRequestsList(HttpServletRequest request) {
    String userEmail = (String) request.getAttribute("email");

    if (userEmail == null || userEmail.isEmpty()) {
        return null; // RESPONSE_STATUS_AUTH_REQUIRED;
    }//  w ww  . j  a va 2s  . c o  m

    List<Following> followingList = followingRepository.findFollowRequest(userEmail, Following.PENDING);
    ArrayList<User> users = Lists.newArrayList();

    for (Following following : followingList)
        users.add(findUser(following.getUserEmail(), true));

    if (users.isEmpty())
        return null;

    return users;
}