List of usage examples for org.apache.commons.collections CollectionUtils collect
public static Collection collect(Iterator inputIterator, Transformer transformer)
From source file:org.broadleafcommerce.core.offer.service.OfferServiceImpl.java
@Override @SuppressWarnings("unchecked") public Set<Offer> getUniqueOffersFromOrder(Order order) { HashSet<Offer> result = new HashSet<Offer>(); Transformer adjustmentToOfferTransformer = new Transformer() { @Override/*from ww w . j a va 2s.com*/ public Object transform(Object input) { return ((Adjustment) input).getOffer(); } }; result.addAll(CollectionUtils.collect(order.getOrderAdjustments(), adjustmentToOfferTransformer)); if (order.getOrderItems() != null) { for (OrderItem item : order.getOrderItems()) { result.addAll( CollectionUtils.collect(item.getOrderItemAdjustments(), adjustmentToOfferTransformer)); //record usage for price details on the item as well if (item.getOrderItemPriceDetails() != null) { for (OrderItemPriceDetail detail : item.getOrderItemPriceDetails()) { result.addAll(CollectionUtils.collect(detail.getOrderItemPriceDetailAdjustments(), adjustmentToOfferTransformer)); } } } } if (order.getFulfillmentGroups() != null) { for (FulfillmentGroup fg : order.getFulfillmentGroups()) { result.addAll( CollectionUtils.collect(fg.getFulfillmentGroupAdjustments(), adjustmentToOfferTransformer)); } } return result; }
From source file:org.dspace.discovery.SolrServiceImpl.java
@Override public List<Item> getRelatedItems(Context context, Item item, DiscoveryMoreLikeThisConfiguration mltConfig) { List<Item> results = new ArrayList<Item>(); try {//w w w . j a v a2 s . c o m SolrQuery solrQuery = new SolrQuery(); //Set the query to handle since this is unique solrQuery.setQuery("handle: " + item.getHandle()); //Add the more like this parameters ! solrQuery.setParam(MoreLikeThisParams.MLT, true); //Add a comma separated list of the similar fields @SuppressWarnings("unchecked") java.util.Collection<String> similarityMetadataFields = CollectionUtils .collect(mltConfig.getSimilarityMetadataFields(), new Transformer() { @Override public Object transform(Object input) { //Add the mlt appendix ! return input + "_mlt"; } }); solrQuery.setParam(MoreLikeThisParams.SIMILARITY_FIELDS, StringUtils.join(similarityMetadataFields, ',')); solrQuery.setParam(MoreLikeThisParams.MIN_TERM_FREQ, String.valueOf(mltConfig.getMinTermFrequency())); solrQuery.setParam(MoreLikeThisParams.DOC_COUNT, String.valueOf(mltConfig.getMax())); solrQuery.setParam(MoreLikeThisParams.MIN_WORD_LEN, String.valueOf(mltConfig.getMinWordLength())); QueryResponse rsp = getSolr().query(solrQuery); NamedList mltResults = (NamedList) rsp.getResponse().get("moreLikeThis"); if (mltResults != null && mltResults.get(item.getType() + "-" + item.getID()) != null) { SolrDocumentList relatedDocs = (SolrDocumentList) mltResults .get(item.getType() + "-" + item.getID()); for (Object relatedDoc : relatedDocs) { SolrDocument relatedDocument = (SolrDocument) relatedDoc; DSpaceObject relatedItem = findDSpaceObject(context, relatedDocument); if (relatedItem.getType() == Constants.ITEM) { results.add((Item) relatedItem); } } } } catch (Exception e) { log.error(LogManager.getHeader(context, "Error while retrieving related items", "Handle: " + item.getHandle()), e); } return results; }
From source file:org.eclipse.wb.internal.layout.group.gef.GroupLayoutEditPolicy2.java
@Override protected Command getAddCommand(final ChangeBoundsRequest request) { return new EditCommand(getJavaInfo()) { @Override/*from w ww.jav a 2 s .c om*/ protected void executeEdit() throws Exception { List<EditPart> editParts = request.getEditParts(); @SuppressWarnings("unchecked") List<AbstractComponentInfo> models = (List<AbstractComponentInfo>) CollectionUtils .collect(editParts, new Transformer() { public Object transform(Object input) { return ((EditPart) input).getModel(); } }); m_layout.command_add(models); } }; }
From source file:org.esa.s2tbx.dataio.s2.l1b.L1bMetadataProc.java
public static Collection<String> getTiles(Level1B_User_Product product) { A_PRODUCT_INFO.Product_Organisation info = product.getGeneral_Info().getProduct_Info() .getProduct_Organisation();//from w w w .j a v a2 s .co m List<A_PRODUCT_INFO.Product_Organisation.Granule_List> aGranuleList = info.getGranule_List(); Transformer tileSelector = o -> { A_PRODUCT_INFO.Product_Organisation.Granule_List ali = (A_PRODUCT_INFO.Product_Organisation.Granule_List) o; A_PRODUCT_ORGANIZATION.Granules gr = ali.getGranules(); return gr.getGranuleIdentifier(); }; return CollectionUtils.collect(aGranuleList, tileSelector); }
From source file:org.esa.s2tbx.dataio.s2.l1c.L1cMetadataProc.java
public static Collection<String> getTiles(Level1C_User_Product product) { A_PRODUCT_INFO.Product_Organisation info = product.getGeneral_Info().getProduct_Info() .getProduct_Organisation();/*from w w w. java2 s . c o m*/ List<A_PRODUCT_INFO.Product_Organisation.Granule_List> aGranuleList = info.getGranule_List(); Transformer tileSelector; tileSelector = o -> { A_PRODUCT_INFO.Product_Organisation.Granule_List ali = (A_PRODUCT_INFO.Product_Organisation.Granule_List) o; A_PRODUCT_ORGANIZATION.Granules gr = ali.getGranules(); return gr.getGranuleIdentifier(); }; return CollectionUtils.collect(aGranuleList, tileSelector); }
From source file:org.esa.s2tbx.dataio.s2.l2a.L2aMetadataProc.java
public static Collection<String> getTiles(Level2A_User_Product product) { A_L2A_Product_Info.L2A_Product_Organisation info = product.getGeneral_Info().getL2A_Product_Info() .getL2A_Product_Organisation(); List<A_L2A_Product_Info.L2A_Product_Organisation.Granule_List> aGranuleList = info.getGranule_List(); Transformer tileSelector = o -> { A_L2A_Product_Info.L2A_Product_Organisation.Granule_List ali = (A_L2A_Product_Info.L2A_Product_Organisation.Granule_List) o; A_PRODUCT_ORGANIZATION_2A.Granules gr = ali.getGranules(); return gr.getGranuleIdentifier(); };//from w w w. jav a 2s. c o m return CollectionUtils.collect(aGranuleList, tileSelector); }
From source file:org.fao.geonet.kernel.mef.Importer.java
public static List<String> doImport(final Element params, final ImportMetadataDTO dto, final ServiceContext context, File mefFile, final String stylePath, final boolean indexGroup) throws Exception { final GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); final DataManager dm = gc.getDataManager(); // Load preferred schema and set to iso19139 by default final String preferredSchema = (gc.getHandlerConfig().getMandatoryValue("preferredSchema") != null ? gc.getHandlerConfig().getMandatoryValue("preferredSchema") : "iso19139"); final Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); final List<String> id = new ArrayList<String>(); final List<Element> md = new ArrayList<Element>(); final List<Element> fc = new ArrayList<Element>(); // Try to define MEF version from mef file not from parameter String fileType = dto.getFileType(); if (fileType.equals("mef")) { MEFLib.Version version = MEFLib.getMEFVersion(mefFile); if (version.equals(MEFLib.Version.V2)) fileType = "mef2"; }//from w ww. ja va2 s. c o m IVisitor visitor; if (fileType.equals("single")) visitor = new XmlVisitor(); else if (fileType.equals("mef")) visitor = new MEFVisitor(); else if (fileType.equals("mef2")) visitor = new MEF2Visitor(); else throw new BadArgumentException("Bad file type parameter."); // --- import metadata from MEF, Xml, ZIP files MEFLib.visit(mefFile, visitor, new IMEFVisitor() { @Override public void handleMetadata(Element metadata, int index) throws Exception { Log.debug(Geonet.MEF, "Collecting metadata:\n" + Xml.getString(metadata)); md.add(index, metadata); } @Override public void handleMetadataFiles(File[] Files, int index) throws Exception { Log.debug(Geonet.MEF, "Multiple metadata files"); Element metadataValidForImport = null; for (File file : Files) { if (file != null && !file.isDirectory()) { Element metadata = Xml.loadFile(file); String metadataSchema = dm.autodetectSchema(metadata); // If local node doesn't know metadata // schema try to load next xml file. if (metadataSchema == null) { continue; } // If schema is preferred local node schema // load that file. if (metadataSchema.equals(preferredSchema)) { Log.debug(Geonet.MEF, "Found metadata file " + file.getName() + " with preferred schema (" + preferredSchema + ")."); handleMetadata(metadata, index); return; } else { Log.debug(Geonet.MEF, "Found metadata file " + file.getName() + " with known schema (" + metadataSchema + ")."); metadataValidForImport = metadata; } } } // Import a valid metadata if not one found // with preferred schema. if (metadataValidForImport != null) { Log.debug(Geonet.MEF, "Importing metadata with valide schema but not preferred one."); handleMetadata(metadataValidForImport, index); } else throw new BadFormatEx("No valid metadata file found."); } // -------------------------------------------------------------------- @Override public void handleFeatureCat(Element featureCat, int index) throws Exception { if (featureCat != null) { Log.debug(Geonet.MEF, "Collecting feature catalog:\n" + Xml.getString(featureCat)); } fc.add(index, featureCat); } // -------------------------------------------------------------------- /** * Record is not a template by default. No category attached to * record by default. No stylesheet used by default. If no site * identifier provided, use current node id by default. No * validation by default. * * If record is a template and not a MEF file always generate a new * UUID. */ @Override @SuppressWarnings("unchecked") public void handleInfo(Element info, int index) throws Exception { String FS = File.separator; String uuid = null; String createDate = null; String changeDate = null; String source; String sourceName = null; // Schema in info.xml is not used anymore. // as we use autodetect schema to define // metadata schema. // String schema = null; String isTemplate = "n"; String localId = null; String rating = null; String popularity = null; // Category Category category = null; boolean validate = false; Element metadata = md.get(index); String schema = dm.autodetectSchema(metadata); if (schema == null) throw new Exception("Unknown schema format : " + schema); // Handle non MEF files insertion if (info.getChildren().size() == 0) { source = gc.getSiteId(); category = dto.getCategory(); String style = "None"; if (dto.getStylesheet() != null) { style = dto.getStylesheet().getName(); } // Apply a stylesheet transformation if requested if (!style.equals("None")) md.add(index, Xml.transform(md.get(index), stylePath + FS + style)); // Get the Metadata uuid if it's not a template. if (isTemplate.equals("n")) uuid = dm.extractUUID(schema, md.get(index)); validate = Util.getParam(params, Params.VALIDATE, "off").equals("on"); } else { Element categsElt = info.getChild("categories"); Collection<String> categNames = CollectionUtils.collect(categsElt.getChildren("category"), new Transformer() { @Override public Object transform(Object input) { return ((Element) input).getAttributeValue("name"); } }); CategoryManager cm = new CategoryManager(dbms); // FIXME Category may be null ... NPE!! category = mapLocalCategory(cm.getAllCategories(), categNames); Element general = info.getChild("general"); uuid = general.getChildText("uuid"); createDate = general.getChildText("createDate"); changeDate = general.getChildText("changeDate"); source = general.getChildText("siteId"); sourceName = general.getChildText("siteName"); localId = general.getChildText("localId"); isTemplate = "n"; rating = general.getChildText("rating"); popularity = general.getChildText("popularity"); } if (validate) dm.validate(schema, metadata); String uuidAction = Params.NOTHING; importRecord(uuid, localId, uuidAction, md, schema, index, source, sourceName, context, id, createDate, changeDate, isTemplate, category.getId()); if (fc.size() != 0 && fc.get(index) != null) { // UUID is set as @uuid in root element uuid = UUID.randomUUID().toString(); fc.add(index, dm.setUUID("iso19110", uuid, fc.get(index))); String fcId = dm.insertMetadataExt(dbms, "iso19110", fc.get(index), source, createDate, changeDate, uuid, context.getUserSession().getUsername()); Log.debug(Geonet.MEF, "Adding Feature catalog with uuid: " + uuid); // Create database relation between metadata and feature // catalog String mdId = id.get(index); String query = "INSERT INTO Relations (id, relatedId) VALUES (?, ?)"; dbms.execute(query, Integer.parseInt(mdId), Integer.parseInt(fcId)); id.add(fcId); // TODO : privileges not handled for feature // catalog ... } int iId = Integer.parseInt(id.get(index)); if (rating != null) dbms.execute("UPDATE Metadata SET rating=? WHERE id=?", new Integer(rating), iId); if (popularity != null) dbms.execute("UPDATE Metadata SET popularity=? WHERE id=?", new Integer(popularity), iId); dm.setTemplateExt(dbms, uuid, isTemplate, null); dm.setHarvestedExt(dbms, uuid, null); String pubDir = Lib.resource.getDir(context, "public", id.get(index)); String priDir = Lib.resource.getDir(context, "private", id.get(index)); new File(pubDir).mkdirs(); new File(priDir).mkdirs(); if (indexGroup) { dm.indexMetadataGroup(dbms, uuid, null); } else { dm.indexMetadata(dbms, uuid, null); } } // -------------------------------------------------------------------- @Override public void handlePublicFile(String file, String changeDate, InputStream is, int index) throws IOException { Log.debug(Geonet.MEF, "Adding public file with name=" + file); saveFile(context, id.get(index), "public", file, changeDate, is); } // -------------------------------------------------------------------- @Override public void handlePrivateFile(String file, String changeDate, InputStream is, int index) throws IOException { Log.debug(Geonet.MEF, "Adding private file with name=" + file); saveFile(context, id.get(index), "private", file, changeDate, is); } }); return id; }
From source file:org.fao.geonet.lib.ResourceLib.java
/** * Check that the operation is allowed for current user. See * {@link AccessManager#getOperations(ServiceContext, String, String)}. * /*from w w w . ja v a2s . c o m*/ * @param context * @param id The metadata identifier * @param operation See {@link AccessManager}. * @throws Exception */ @SuppressWarnings("unchecked") public void checkPrivilege(ServiceContext context, String id, int operation) throws Exception { // Always grant VIEW privileges for non authenticated users. if (OperationEnum.VIEW.getId() == operation) { return; } Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); AccessManager accessMan = new AccessManager(dbms); UserSession us = context.getUserSession(); List<Group> groups = null; GroupManager gm = new GroupManager(dbms); IDataPolicyManager dpm = new DataPolicyManager(dbms); if (us.isAuthenticated()) { if (accessMan.isOwner(context, id)) { groups = gm.getAllGroups(); } else { groups = gm.getAllUserGroups(us.getUserId()); } } Collection<Operation> operations = dpm.getAllOperationAllowedByMetadataId(id, groups); Collection<Integer> operationsEnum = CollectionUtils.collect(operations, new Transformer() { @Override public Object transform(Object arg0) { return ((Operation) arg0).getId(); } }); if (!operationsEnum.contains(operation)) { throw new OperationNotAllowedEx(); } }
From source file:org.fenixedu.academic.dto.guide.reimbursementGuide.InfoReimbursementGuide.java
public void copyFromDomain(ReimbursementGuide reimbursementGuide) { super.copyFromDomain(reimbursementGuide); if (reimbursementGuide != null) { setCreationDate(reimbursementGuide.getCreationDate()); setInfoGuide(InfoGuideWithPersonAndExecutionDegreeAndDegreeCurricularPlanAndDegree .newInfoFromDomain(reimbursementGuide.getGuide())); setNumber(reimbursementGuide.getNumber()); List infoReimbursementGuideEntries = (List) CollectionUtils .collect(reimbursementGuide.getReimbursementGuideEntriesSet(), new Transformer() { @Override//from w w w.j a va2 s . c om public Object transform(Object arg0) { ReimbursementGuideEntry reimbursementGuideEntry = (ReimbursementGuideEntry) arg0; return InfoReimbursementGuideEntry.newInfoFromDomain(reimbursementGuideEntry); } }); setInfoReimbursementGuideEntries(infoReimbursementGuideEntries); List infoReimbursementGuideSituations = (List) CollectionUtils .collect(reimbursementGuide.getReimbursementGuideSituationsSet(), new Transformer() { @Override public Object transform(Object arg0) { ReimbursementGuideSituation reimbursementGuideSituation = (ReimbursementGuideSituation) arg0; return InfoReimbursementGuideSituation.newInfoFromDomain(reimbursementGuideSituation); } }); setInfoReimbursementGuideSituations(infoReimbursementGuideSituations); } }
From source file:org.fenixedu.academic.presentationTier.Action.gep.TeachingStaffDispatchAction.java
protected List readActiveDegreeCurricularPlansByExecutionYear(String executionYearID) throws FenixServiceException { ExecutionYear executionYear = FenixFramework.getDomainObject(executionYearID); Collection executionDegrees = null; if (executionYear != null) { executionDegrees = executionYear.getExecutionDegreesSet(); }/*from w ww . jav a 2 s .com*/ if (executionDegrees == null) { throw new FenixServiceException("nullDegree"); } List infoDegreeCurricularPlans = (List) CollectionUtils.collect(executionDegrees, new Transformer() { @Override public Object transform(Object obj) { ExecutionDegree cursoExecucao = (ExecutionDegree) obj; DegreeCurricularPlan degreeCurricularPlan = cursoExecucao.getDegreeCurricularPlan(); return InfoDegreeCurricularPlan.newInfoFromDomain(degreeCurricularPlan); } }); return infoDegreeCurricularPlans; }