List of usage examples for java.util ArrayList isEmpty
public boolean isEmpty()
From source file:com.cloudera.impala.planner.PlannerTestBase.java
/** * Produces the single-node or distributed plan for testCase and compares the * actual/expected plans if the corresponding test section exists in testCase. * * Returns the produced exec request or null if there was an error generating * the plan./*from ww w . j av a 2 s. c o m*/ */ private TExecRequest testPlan(TestCase testCase, Section section, TQueryCtx queryCtx, StringBuilder errorLog, StringBuilder actualOutput) { String query = testCase.getQuery(); queryCtx.request.setStmt(query); if (section == Section.PLAN) { queryCtx.request.getQuery_options().setNum_nodes(1); } else { // for distributed and parallel execution we want to run on all available nodes queryCtx.request.getQuery_options().setNum_nodes(ImpalaInternalServiceConstants.NUM_NODES_ALL); } if (section == Section.PARALLELPLANS) { queryCtx.request.query_options.mt_num_cores = 2; } ArrayList<String> expectedPlan = testCase.getSectionContents(section); boolean sectionExists = expectedPlan != null && !expectedPlan.isEmpty(); String expectedErrorMsg = getExpectedErrorMessage(expectedPlan); StringBuilder explainBuilder = new StringBuilder(); TExecRequest execRequest = null; if (sectionExists) actualOutput.append(section.getHeader() + "\n"); try { execRequest = frontend_.createExecRequest(queryCtx, explainBuilder); } catch (NotImplementedException e) { if (!sectionExists) return null; handleNotImplException(query, expectedErrorMsg, errorLog, actualOutput, e); } catch (Exception e) { errorLog.append( String.format("Query:\n%s\nError Stack:\n%s\n", query, ExceptionUtils.getStackTrace(e))); } // No expected plan was specified for section. Skip expected/actual comparison. if (!sectionExists) return execRequest; // Failed to produce an exec request. if (execRequest == null) return null; String explainStr = removeExplainHeader(explainBuilder.toString()); actualOutput.append(explainStr); LOG.info(section.toString() + ":" + explainStr); if (expectedErrorMsg != null) { errorLog.append(String.format("\nExpected failure, but query produced %s.\nQuery:\n%s\n\n%s:\n%s", section, query, section, explainStr)); } else { String planDiff = TestUtils.compareOutput(Lists.newArrayList(explainStr.split("\n")), expectedPlan, true, true); if (!planDiff.isEmpty()) { errorLog.append(String.format("\nSection %s of query:\n%s\n\n%s", section, query, planDiff)); // Append the VERBOSE explain plan because it contains details about // tuples/sizes/cardinality for easier debugging. String verbosePlan = getVerboseExplainPlan(queryCtx); errorLog.append("\nVerbose plan:\n" + verbosePlan); } } return execRequest; }
From source file:com.silverwrist.venice.conf.impl.ConferenceManager.java
public List getConferences(DynamoUser user, VeniceCommunity comm) throws DatabaseException { boolean show_hidden = false; try { // do we want to show hidden conferences? show_hidden = comm.getAcl().testPermission(user, ConfNamespaces.PERMISSIONS_NAMESPACE, "see.hidden"); } // end try//from ww w . ja v a 2s . co m catch (AclNotFoundException e) { // convert the AclNotFoundException DatabaseException de = new DatabaseException(ConferenceManager.class, "ConferenceMessages", "no.community.acl", e); de.setParameter(0, comm.getName()); throw de; } // end catch List in_list = m_ops.getConferences(comm.getCID()); if (in_list.isEmpty()) return Collections.EMPTY_LIST; ArrayList rc = new ArrayList(); Iterator it = in_list.iterator(); while (it.hasNext()) { // get each data element and convert it Map d = (Map) (it.next()); if (show_hidden || !(((Boolean) (d.get(ConferenceManagerOps.KEY_HIDE))).booleanValue())) { // skip hidden conferences if we don't have the "show hidden" permission ConferenceImpl conf = loadConference(d); rc.add(new LinkedConferenceImpl(m_ops.getLinkedConferenceOps(), conf, comm, m_srm, d)); } // end if } // end while if (rc.isEmpty()) return Collections.EMPTY_LIST; rc.trimToSize(); return Collections.unmodifiableList(rc); }
From source file:com.snaplogic.snaps.firstdata.Create.java
private ObjectSchema getSchema(SchemaProvider provider, Class<?> classType, SnapType snapType) { ArrayList<Method> getterMethods = findGetters(classType); ObjectSchema schema = null;/* w w w .j ava 2 s .co m*/ if (!getterMethods.isEmpty()) { schema = provider.createSchema(snapType, classType.getSimpleName()); } String name; String paramType; Class<?> subClass; Class<?> fieldTypeParameterType; ObjectSchema subSchema; ParameterizedType fieldGenericType; for (Method method : getterMethods) { try { paramType = method.getReturnType().getName(); if (paramType.startsWith(FD_PROXY_PKG_PREFIX) && !paramType.endsWith(TYPE)) { try { subClass = Class.forName(paramType); } catch (ClassNotFoundException e) { log.error(e.getMessage(), e); throw new ExecutionException(e.getMessage()); } subSchema = getSchema(provider, subClass, SnapType.STRING); if (subSchema != null) { schema.addChild(subSchema); } } else if (paramType.endsWith(List.class.getSimpleName())) { fieldGenericType = (ParameterizedType) method.getGenericReturnType(); fieldTypeParameterType = (Class<?>) fieldGenericType.getActualTypeArguments()[0]; if (fieldTypeParameterType == String.class) { subSchema = provider.createSchema(SnapType.COMPOSITE, getFieldName(method.getName())); } else { subSchema = getSchema(provider, fieldTypeParameterType, SnapType.COMPOSITE); } if (subSchema != null) { schema.addChild(subSchema); } } else { name = getFieldName(method.getName()); schema.addChild(provider.createSchema(getDataTypes(paramType), name)); } } catch (Exception e) { log.error(e.getMessage(), e); return null; } } return schema; }
From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestJsonTests.java
@Parameters public static Collection<Object[]> getAllDescriptionUrls() throws IOException, NullPointerException, XPathException, ParserConfigurationException, SAXException, JSONException { //Checks the ServiceProviderCatalog at the specified baseUrl of the REST service in order to grab all urls //to other ServiceProvidersCatalogs contained within it, recursively, in order to find the URLs of all //query factories of the REST service. ArrayList<String> serviceUrls = getServiceProviderURLsUsingJson(setupProps.getProperty("baseUri"), onlyOnce);/*w w w.jav a2 s . co m*/ ArrayList<String> capabilityURLsUsingJson = getCapabilityURLsUsingJson(OSLCConstants.QUERY_BASE_PROP, serviceUrls, true); String where = setupProps.getProperty("changeRequestsWhere"); if (where == null) { String queryProperty = setupProps.getProperty("queryEqualityProperty"); String queryPropertyValue = setupProps.getProperty("queryEqualityValue"); where = queryProperty + "=\"" + queryPropertyValue + "\""; } String additionalParameters = setupProps.getProperty("queryAdditionalParameters"); String query = (additionalParameters.length() == 0) ? "?" : "?" + additionalParameters + "&"; query = query + "oslc.where=" + URLEncoder.encode(where, "UTF-8") + "&oslc.pageSize=1"; ArrayList<String> results = new ArrayList<String>(); for (String queryBaseUri : capabilityURLsUsingJson) { String queryUrl = OSLCUtils.addQueryStringToURL(queryBaseUri, query); HttpResponse resp = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds, OSLCConstants.CT_JSON, headers); String respBody = EntityUtils.toString(resp.getEntity()); // Parse the response JSONArtifact userData = null; try { userData = JSON.parse(respBody); } catch (JSONException e) { // parsing error - we imply the response is not in JSON format } JSONObject resultJson = null; if (userData instanceof JSONArtifact) { resultJson = (JSONObject) userData; } JSONArray s = null; if (resultJson.containsKey("oslc:results")) { s = (JSONArray) resultJson.get("oslc:results"); } else if (resultJson.containsKey("rdfs:member")) { s = (JSONArray) resultJson.getJSONArray("rdfs:member"); } JSONObject r = (JSONObject) s.get(0); String one = null; if (r.containsKey("rdf:resource")) { one = r.getString("rdf:resource"); } else if (r.containsKey("rdf:about")) { one = r.getString("rdf:about"); } results.add(one); if (!results.isEmpty() && onlyOnce) break; } return toCollection(results); }
From source file:com.mohamnag.inappbilling.InAppBillingPlugin.java
/** * Loads products with specific IDs and gets their details. * * @param productIds/* w w w.j a v a 2 s . c o m*/ * @param callbackContext */ private void loadProductDetails(final ArrayList<String> productIds, final CallbackContext callbackContext) throws JSONException { jsLog("loadProductDetails called."); if (productIds == null || productIds.isEmpty()) { jsLog("Product list was empty"); callbackContext.success(myInventory.getAllProductsJSON()); } else { jsLog("Loading/refreshing product details"); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", productIds); // do same query with both types to load all! Error errInapp = querySkuDetails(querySkus, BILLING_ITEM_TYPE_INAPP); Error errSubs = querySkuDetails(querySkus, BILLING_ITEM_TYPE_SUBS); // only call success if no error has happened if (errInapp != null) { callbackContext.error(errInapp.toJavaScriptJSON()); } else if (errSubs != null) { callbackContext.error(errSubs.toJavaScriptJSON()); } else { callbackContext.success(myInventory.getAllProductsJSON()); } } }
From source file:com.predic8.membrane.core.transport.http.ConnectionManager.java
private int closeOldConnections() { ArrayList<ConnectionKey> toRemove = new ArrayList<ConnectionKey>(); ArrayList<Connection> toClose = new ArrayList<Connection>(); long now = System.currentTimeMillis(); log.trace("closing old connections"); int closed = 0, remaining; synchronized (this) { // close connections after their timeout for (Map.Entry<ConnectionKey, ArrayList<OldConnection>> e : availableConnections.entrySet()) { ArrayList<OldConnection> l = e.getValue(); for (int i = 0; i < l.size(); i++) { OldConnection o = l.get(i); if (o.deathTime < now) { // replace [i] by [last] if (i == l.size() - 1) l.remove(i);/*from w w w . ja v a2s. c o m*/ else l.set(i, l.remove(l.size() - 1)); --i; closed++; toClose.add(o.connection); } } if (l.isEmpty()) toRemove.add(e.getKey()); } for (ConnectionKey remove : toRemove) availableConnections.remove(remove); remaining = availableConnections.size(); } for (Connection c : toClose) { try { c.close(); } catch (Exception e) { // do nothing } } if (closed != 0) log.debug("closed " + closed + " connections"); return remaining; }
From source file:org.n52.oxf.sos.adapter.v200.SOSCapabilitiesMapper_200.java
private void addConstraints(final RequestMethodType xbGetRequestMethod, final RequestMethod ocRequestMethod) { if (xbGetRequestMethod.getConstraintArray() != null) { for (final DomainType xbConstraint : xbGetRequestMethod.getConstraintArray()) { final String name = xbConstraint.getName(); final ArrayList<String> allowedValues = new ArrayList<String>(); if (xbConstraint.isSetAllowedValues()) { for (final ValueType xbAllowedValue : xbConstraint.getAllowedValues().getValueArray()) { allowedValues.add(xbAllowedValue.getStringValue()); }//ww w .j a va 2 s.c om } if (name != null && !name.isEmpty() && !allowedValues.isEmpty()) { ocRequestMethod.addOwsConstraint( new Constraint(name, allowedValues.toArray(new String[allowedValues.size()]))); } } } }
From source file:com.rr.generic.ui.users.userController.java
/** * The 'saveProgramUserModules' POST request will submit the selected program modules for the user and program. * //from www. j a v a 2s . com * @param i The encrypted userId * @param v The encrypted secret * @param modules The selected program modules. * @return * @throws Exception */ @RequestMapping(value = "/saveProgramUserModules.do", method = RequestMethod.POST) public @ResponseBody ModelAndView saveProgramUserModules(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletRequest request) throws Exception { /* Decrypt the url */ int userId = decryptURLParam(i, v); /* Clear out current user modules */ usermanager.removeUsedModulesByUser(programId, userId); ArrayList programModuleList = new ArrayList( Arrays.asList(request.getParameter("selProgramModules").split(","))); if (!programModuleList.isEmpty()) { for (Object programModuleList1 : programModuleList) { Integer module = Integer.parseInt(programModuleList1.toString()); userProgramModules userModule = new userProgramModules(); userModule.setSystemUserId(userId); userModule.setProgramId(programId); userModule.setModuleId(module); if (request.getParameter("create_" + module) != null) { userModule.setAllowCreate(true); } if (request.getParameter("edit_" + module) != null) { userModule.setAllowEdit(true); } if (request.getParameter("delete_" + module) != null) { userModule.setAllowDelete(true); } if (request.getParameter("level1_" + module) != null) { userModule.setAllowLevel1(true); } if (request.getParameter("level2_" + module) != null) { userModule.setAllowLevel2(true); } if (request.getParameter("level3_" + module) != null) { userModule.setAllowLevel3(true); } if (request.getParameter("reconcile_" + module) != null) { userModule.setAllowReconcile(true); } if (request.getParameter("import_" + module) != null) { userModule.setAllowImport(true); } if (request.getParameter("export_" + module) != null) { userModule.setAllowExport(true); } usermanager.saveUsedModulesByUser(userModule); } } ModelAndView mav = new ModelAndView(); mav.setViewName("/users/programModules"); mav.addObject("encryptedURL", "?i=" + i + "&v=" + v); return mav; }
From source file:com.l2jfrozen.gameserver.geo.pathfinding.PathFinding.java
public final Node[] searchByClosest(final Node start, final Node end) { // Note: This is the version for cell-based calculation, harder // on cpu than from block-based pathnode files. However produces better routes. // Always continues checking from the closest to target non-blocked // node from to_visit list. There's extra length in path if needed // to go backwards/sideways but when moving generally forwards, this is extra fast // and accurate. And can reach insane distances (try it with 8000 nodes..). // Minimum required node count would be around 300-400. // Generally returns a bit (only a bit) more intelligent looking routes than // the basic version. Not a true distance image (which would increase CPU // load) level of intelligence though. // List of Visited Nodes final CellNodeMap known = CellNodeMap.newInstance(); // List of Nodes to Visit final ArrayList<Node> to_visit = L2Collections.newArrayList(); to_visit.add(start);/*from w w w . j ava2 s .c o m*/ known.add(start); try { final int targetx = end.getNodeX(); final int targety = end.getNodeY(); final int targetz = end.getZ(); int dx, dy, dz; boolean added; int i = 0; while (i < 3500) { if (to_visit.isEmpty()) { // No Path found return null; } final Node node = to_visit.remove(0); i++; node.attachNeighbors(); if (node.equals(end)) { // path found! note that node z coordinate is updated only in attach // to improve performance (alternative: much more checks) // LOGGER.info("path found, i:"+i); return constructPath(node); } final Node[] neighbors = node.getNeighbors(); if (neighbors == null) continue; for (final Node n : neighbors) { if (!known.contains(n)) { added = false; n.setParent(node); dx = targetx - n.getNodeX(); dy = targety - n.getNodeY(); dz = targetz - n.getZ(); n.setCost(dx * dx + dy * dy + dz / 2 * dz/* +n.getCost() */); for (int index = 0; index < to_visit.size(); index++) { // supposed to find it quite early.. if (to_visit.get(index).getCost() > n.getCost()) { to_visit.add(index, n); added = true; break; } } if (!added) to_visit.add(n); known.add(n); } } } // No Path found // LOGGER.info("no path found"); return null; } finally { CellNodeMap.recycle(known); L2Collections.recycle(to_visit); } }
From source file:jnode.vm.NetAPIImpl.java
public byte[][] getHostByName(String hostname) throws UnknownHostException { ArrayList<byte[]> list = null; for (NetworkLayer layer : networkLayerManager.getNetworkLayers()) { final ProtocolAddress[] addrs = layer.getHostByName(hostname); if (addrs != null) { if (list == null) { list = new ArrayList<byte[]>(); }/* ww w. j av a2s . com*/ final int cnt = addrs.length; for (int j = 0; j < cnt; j++) { final ProtocolAddress pa = addrs[j]; if (pa != null) { list.add(pa.toByteArray()); } } } } if ((list == null) || list.isEmpty()) { throw new UnknownHostException(hostname); } else { return (byte[][]) list.toArray(new byte[list.size()][]); } }