List of usage examples for java.util LinkedList addAll
public boolean addAll(Collection<? extends E> c)
From source file:org.apache.hama.ml.recommendation.cf.OnlineCF.java
@Override public List<Preference<Long, Long>> getMostPreferredItems(long userId, int count) { Comparator<Preference<Long, Long>> scoreComparator = new Comparator<Preference<Long, Long>>() { @Override/* w ww . j a va 2 s .co m*/ public int compare(Preference<Long, Long> arg0, Preference<Long, Long> arg1) { double difference = arg0.getValue().get() - arg1.getValue().get(); return (int) (100000 * difference); } }; PriorityQueue<Preference<Long, Long>> queue = new PriorityQueue<Preference<Long, Long>>(count, scoreComparator); LinkedList<Preference<Long, Long>> results = new LinkedList<Preference<Long, Long>>(); if (function == null) { Class<?> cls = conf.getClass(OnlineCF.Settings.CONF_ONLINE_UPDATE_FUNCTION, null); try { function = (OnlineUpdate.Function) (cls.newInstance()); } catch (Exception e) { // set default function } } InputStructure e = new InputStructure(); e.user = this.modelUserFactorizedValues.get(Long.valueOf(userId)); e.userFeatureFactorized = this.modelUserFeatureFactorizedValues; e.userFeatures = this.modelUserFeatures.get(Long.valueOf(userId)); e.itemFeatureFactorized = this.modelItemFeatureFactorizedValues; if (e.user == null) { return null; } double score = 0.0; for (Entry<Long, VectorWritable> item : modelItemFactorizedValues.entrySet()) { e.item = item.getValue(); e.itemFeatures = this.modelItemFeatures.get(item.getKey()); score = function.predict(e); queue.add(new Preference<Long, Long>(userId, item.getKey(), score)); } results.addAll(queue); return results; }
From source file:mitm.application.djigzo.james.mailets.MailAttributes.java
@SuppressWarnings("unchecked") @Override/*from www . jav a 2s. c o m*/ public void serviceMailTransacted(Mail mail) throws MessagingException { /* * First delete all attributes, then set and finally add */ for (String attribute : deleteAttributes) { mail.removeAttribute(attribute); } /* * Set attributes */ for (Entry<String, String> attribute : setAttributes.entrySet()) { LinkedList<String> attributes = parseAttribute(attribute.getValue(), mail); if (attributes.size() > 0) { mail.setAttribute(attribute.getKey(), StringUtils.join(attributes, ',')); } else { mail.removeAttribute(attribute.getKey()); } } /* * Serialized attributes */ for (Entry<String, Serializable> attribute : serializedAttributes.entrySet()) { mail.setAttribute(attribute.getKey(), attribute.getValue()); } /* * Add attributes. If an attribute already exists and is a Collection, the new value * will be added to the collection. If not, a LinkedList will be created and the * value will be added to the list. */ for (Entry<String, List<String>> attribute : addAttributes.entrySet()) { /* * Check if the attribute exists and is a collection */ Object existingAttr = mail.getAttribute(attribute.getKey()); Collection<Object> attributes; if (existingAttr == null || !(existingAttr instanceof Collection)) { attributes = new LinkedList<Object>(); } else { attributes = (Collection<Object>) existingAttr; } attributes.addAll(parseAttributes(attribute.getValue(), mail)); if (attributes.size() > 0) { mail.setAttribute(attribute.getKey(), (Serializable) attributes); } else { mail.removeAttribute(attribute.getKey()); } } if (nextProcessor != null) { mail.setState(nextProcessor); } }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.main.SmartDeploymentService.java
private String enrich_CAMF_CSAR_Process(String csarTmp, String serviceName) { String extractedFolder = csarTmp + ".extracted"; String toscaFile = extractedFolder + "/Definitions/Application.tosca"; String scriptDir = extractedFolder + "/Scripts/"; try {// ww w.ja v a 2 s .c om // extract CSAR CSARParser.extractCsar(new File(csarTmp), extractedFolder); // enrich with QUELLE for String toscaXML = FileUtils.readFileToString(new File(toscaFile)); EngineLogger.logger.debug("Read tosca string done. 100 first characters: {}", toscaXML); EngineLogger.logger.debug("Now trying to enrich with QUELLE...."); //enrichCAMFToscaWithQuelle(toscaXML, serviceName, new String[]{EnrichFunctions.QuelleCloudServiceRecommendation.toString(), EnrichFunctions.SalsaInfoCompletion.toString()}); SmartDeploymentService sds = new SmartDeploymentService(); String result = sds.enrichCAMFToscaWithQuelle(toscaXML, serviceName, new String[] { EnrichFunctions.QuelleCloudServiceRecommendation.toString() }); EngineLogger.logger.debug("After enrich with QUELLE, the result is: {}", result); // write back to right place FileUtils.writeStringToFile(new File(toscaFile), result); // read software requirement in TOSCA for each node, put in a map + artifact // a map between node ID and full requirement in Tag Map<String, String> allRequirements = new HashMap<>(); TDefinitions def = ToscaXmlProcess.readToscaFile(toscaFile); for (TNodeTemplate node : ToscaStructureQuery.getNodeTemplateList(def)) { EngineLogger.logger.debug("Checking node: {}", node.getId()); String policiesStr = new String(); if (node.getPolicies() != null) { EngineLogger.logger.debug("Found policies of node: " + node.getId() + "/" + node.getName()); List<TPolicy> policies = node.getPolicies().getPolicy(); for (TPolicy p : policies) { if (p.getPolicyType().getLocalPart().equals("Requirement") && p.getPolicyType().getPrefix().equals("SmartDeployment")) { if (p.getName().startsWith("CONSTRAINT")) { // TODO: parse SYBL policies } else { policiesStr += p.getName().trim(); if (!p.getName().trim().endsWith(";")) { policiesStr += ";"; EngineLogger.logger.debug("polociesStr = {}", policiesStr); } } } } } EngineLogger.logger.debug("Collected policies for node {} is : {}", node.getId(), policiesStr); allRequirements.put(node.getId(), policiesStr); } EngineLogger.logger.debug("In total, we got following requirements: " + allRequirements.toString()); // Load dependency graph knowledge base String dependencyDataFile = SmartDeploymentService.class.getResource("/data/salsa.dependencygraph.xml") .getFile(); SalsaStackDependenciesGraph depGraph = SalsaStackDependenciesGraph .fromXML(FileUtils.readFileToString(new File(dependencyDataFile))); // ENRICH SCRIPT // extract all the requirement, put into the hashmap for (Map.Entry<String, String> entry : allRequirements.entrySet()) { EngineLogger.logger.debug("Analyzing node: {}. Full policies string is: *** {} ***", entry.getKey(), entry.getValue()); // extract CARL Strings CharStream stream = new ANTLRInputStream(entry.getValue()); CARLLexer lexer = new CARLLexer(stream); CommonTokenStream tokens = new CommonTokenStream(lexer); CARLParser parser = new CARLParser(tokens); RequirementsContext requirementsContext = parser.requirements(); ParseTreeWalker walker = new ParseTreeWalker(); // create standard walker CARLProgramListener extractor = new CARLProgramListener(parser); walker.walk(extractor, requirementsContext); // initiate walk of tree with listener org.eclipse.camf.carl.model.Requirements requirements = extractor.getRequirements(); HashMap<String, String> allReqsOfNode = new HashMap<>(); ArrayList<String> checkList = new ArrayList<>(); // os=Ubuntu; os:ver=12.04; sw=jre:1.7 ==> os=Ubuntu, // here flat all the requirement of the node for (IRequirement req : requirements.getRequirements()) { EngineLogger.logger.debug("Irequirement: " + req.toString()); if (req.getCategory().equals(RequirementCategory.SOFTWARE)) { SoftwareRequirement swr = (SoftwareRequirement) req; allReqsOfNode.put("sw", removeQuote(swr.getName())); allReqsOfNode.put(removeQuote(swr.getName()) + ":ver", swr.getVersion().getVersion()); checkList.add(swr.getName()); } else { if (req.getCategory().equals(RequirementCategory.OPERATING_SYSTEM)) { // the system part is generated by quelle OSRequirement osReq = (OSRequirement) req; if (osReq.getName() != null) { allReqsOfNode.put("os", removeQuote(osReq.getName())); } if (osReq.getVersion() != null) { allReqsOfNode.put("os:ver", osReq.getVersion().getVersion()); } } } } // find all the deploymet script of all "sw" requirements LinkedList<String> listOfScripts = new LinkedList<>(); EngineLogger.logger.debug("The node {} will be enriched based-on the requirements: {}", entry.getKey(), checkList.toString()); for (String swReq : checkList) { EngineLogger.logger.debug("Searching deployment script for software req: {}", swReq); SalsaStackDependenciesGraph theNode = depGraph.findNodeByName(swReq); EngineLogger.logger.debug("Node found: {}", theNode.getName()); EngineLogger.logger.debug("All requirements: {}", allReqsOfNode.toString()); LinkedList<String> tmp = theNode.searchDeploymentScriptTemplate(allReqsOfNode); if (tmp != null) { listOfScripts.addAll(tmp); } } EngineLogger.logger.debug(listOfScripts.toString()); // create a script to solve all dependencies first String nodeID = entry.getKey(); String theDependencyScript = "#!/bin/bash \n\n######## Generated by the Decision Module to solve the software dependencies ######## \n\n"; for (String appendScript : listOfScripts) { String theAppend = SmartDeploymentService.class.getResource("/scriptRepo/" + appendScript) .getFile(); String stringToAppend = FileUtils.readFileToString(new File(theAppend)); theDependencyScript += stringToAppend + "\n"; } theDependencyScript += "######## End of generated script ########"; String tmpScriptFile = scriptDir + "/" + nodeID + ".salsatmp"; // read original script, remove the #!/bin/bash if having String originalScriptFile = null; TNodeTemplate node = ToscaStructureQuery.getNodetemplateById(nodeID, def); EngineLogger.logger.debug("Getting artifact template of node: {}", node.getId()); for (TDeploymentArtifact art : node.getDeploymentArtifacts().getDeploymentArtifact()) { EngineLogger.logger.debug("Checking art.Name: {}, type: {}", art.getName(), art.getArtifactType().getLocalPart()); if (art.getArtifactType().getLocalPart().equals("ScriptArtifactPropertiesType")) { String artTemplateID = art.getArtifactRef().getLocalPart(); TArtifactTemplate artTemplate = ToscaStructureQuery.getArtifactTemplateById(artTemplateID, def); if (artTemplate != null) { originalScriptFile = artTemplate.getArtifactReferences().getArtifactReference().get(0) .getReference(); originalScriptFile = extractedFolder + "/" + originalScriptFile; } } } if (originalScriptFile != null) { String originalScript = FileUtils.readFileToString(new File(originalScriptFile)); originalScript = originalScript.replace("#!/bin/bash", ""); originalScript = originalScript.replace("#!/bin/sh", ""); theDependencyScript += originalScript; FileUtils.writeStringToFile(new File(tmpScriptFile), theDependencyScript); EngineLogger.logger.debug("originalScript: {}, moveto: {}", originalScriptFile, originalScriptFile + ".original"); FileUtils.moveFile(FileUtils.getFile(originalScriptFile), FileUtils.getFile(originalScriptFile + ".original")); FileUtils.moveFile(FileUtils.getFile(tmpScriptFile), FileUtils.getFile(originalScriptFile)); } else { // TODO: there is no original script, just add new template, add tmpScript into that } } // end for each node in allRequirements analysis // repack the CSAR FileUtils.deleteQuietly(FileUtils.getFile(csarTmp)); File directory = new File(extractedFolder); File[] fList = directory.listFiles(); //CSARParser.buildCSAR(fList, csarTmp); String builtCSAR = SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + ".csar"; CSARParser.buildCSAR(extractedFolder, builtCSAR); } catch (IOException ex) { EngineLogger.logger.error("Error when enriching CSAR: " + csarTmp, ex); return "Error"; } catch (JAXBException ex) { EngineLogger.logger.error("Cannot parse the Tosca definition in CSAR file: " + toscaFile, ex); return "Error"; } // return the link to the CSAR String csarURLReturn = SalsaConfiguration.getSalsaCenterEndpoint() + "/rest/smart/CAMFTosca/enrich/CSAR/" + serviceName; EngineLogger.logger.info("Enrich CSAR done. URL to download is: {}", csarURLReturn); return csarURLReturn; }
From source file:view.EditorView.java
/** * Renders the current game and unconnected rooms in the view. * * @param autoLayout If {@code true}, the rooms will be automatically laid out according to their topology. * @param onlyUpdateLines If {@code true}, only connecting lines between the rooms are rendered, rooms are left as they are. Useful if the user is currently moving the room around with the mouse. */// w w w . j a va 2 s .c om public void renderView(boolean autoLayout, boolean onlyUpdateLines) { int indexCorrection = 0; while (drawing.getChildren().size() > indexCorrection) { if (!onlyUpdateLines && !(drawing.getChildren().get(indexCorrection) instanceof ConnectionLine)) { drawing.getChildren().remove(indexCorrection); } else if (drawing.getChildren().get(indexCorrection) instanceof ConnectionLine) { // Check if line is still valid ((ConnectionLine) drawing.getChildren().get(indexCorrection)).updateLocation(); indexCorrection++; } else { indexCorrection++; } } renderThreadPool.submit(() -> { // update the connection status of all rooms if (allRoomsAsList != null) { for (RoomRectangle room : allRoomsAsList) { updateConnectionStatusOfRoom(room); } } LinkedList<RoomRectangle> renderQueue = new LinkedList<>(); // The distance between connected rooms double roomDistance = 50; RoomRectangle startRoom; if (allRoomsAsList == null) { // First time to render startRoom = new RoomRectangle(drawing, this.getCurrentGame().getCurrentRoom()); allRoomsAsListCopy = new RoomRectangleList(); allRoomsAsList = new RoomRectangleList(); allRoomsAsList.add(startRoom); } else { startRoom = allRoomsAsList.findByRoom(this.getCurrentGame().getCurrentRoom()); allRoomsAsListCopy = allRoomsAsList; if (!onlyUpdateLines) { allRoomsAsList = new RoomRectangleList(); } } renderQueue.add(startRoom); // render unconnected rooms renderQueue.addAll(unconnectedRooms); while (!renderQueue.isEmpty()) { RoomRectangle currentRoom = renderQueue.remove(); if (currentRoom == null) { FOKLogger.severe(EditorView.class.getName(), "currentRoom == null means that the room was never added to allRoomsAsList and that means that we ran into a bug, so report it :("); Platform.runLater(() -> new ReportingDialog(stage.getScene()).show(AppConfig.gitHubUserName, AppConfig.gitHubRepoName, new IllegalStateException( "A room of the game was never added to allRoomsAsList. This is an internal bug and needs to be reported to the dev team. Please tell us at https://github.com/vatbub/zorkClone/issues what you did when this exception occurred."))); } //noinspection ConstantConditions if (!currentRoom.isRendered()) { if (!allRoomsAsList.contains(currentRoom)) { allRoomsAsList.add(currentRoom); } currentRoom.setCustomParent(drawing); currentRoom.updateNameLabelPosition(); } for (Map.Entry<WalkDirection, Room> entry : currentRoom.getRoom().getAdjacentRooms().entrySet()) { RoomRectangle newRoom; newRoom = allRoomsAsListCopy.findByRoom(entry.getValue()); if (newRoom == null) { // not rendered yet newRoom = new RoomRectangle(drawing, entry.getValue()); allRoomsAsList.add(newRoom); } // Set room position if (autoLayout && !newRoom.isRendered()) { switch (entry.getKey()) { case NORTH: newRoom.setY(currentRoom.getY() - newRoom.getHeight() - roomDistance); newRoom.setX(currentRoom.getX() + currentRoom.getWidth() / 2 - newRoom.getWidth() / 2); break; case WEST: newRoom.setY(currentRoom.getY()); newRoom.setX(currentRoom.getX() - newRoom.getWidth() - roomDistance); break; case EAST: newRoom.setY(currentRoom.getY()); newRoom.setX(currentRoom.getX() + currentRoom.getWidth() + roomDistance); break; case SOUTH: newRoom.setY(currentRoom.getY() + currentRoom.getHeight() + roomDistance); newRoom.setX(currentRoom.getX() + currentRoom.getWidth() / 2 - newRoom.getWidth() / 2); break; case NORTH_WEST: newRoom.setY(currentRoom.getY() - newRoom.getHeight() - roomDistance); newRoom.setX(currentRoom.getX() - newRoom.getWidth() - roomDistance); break; case NORTH_EAST: newRoom.setY(currentRoom.getY() - newRoom.getHeight() - roomDistance); newRoom.setX(currentRoom.getX() + currentRoom.getWidth() + roomDistance); break; case SOUTH_WEST: newRoom.setY(currentRoom.getY() + currentRoom.getHeight() + roomDistance); newRoom.setX(currentRoom.getX() - newRoom.getWidth() - roomDistance); break; case SOUTH_EAST: newRoom.setY(currentRoom.getY() + currentRoom.getHeight() + roomDistance); newRoom.setX(currentRoom.getX() + currentRoom.getWidth() + roomDistance); break; } } ConnectionLine connectionLine = lineList.findByStartAndEndRoomIgnoreLineDirection(currentRoom, newRoom); if (connectionLine == null) { // create a new line connectionLine = new ConnectionLine(currentRoom, newRoom); connectionLine.setInvalidationRunnable(lineInvalidationRunnable); lineList.add(connectionLine); final Line connectionLineCopy = connectionLine; Platform.runLater(() -> drawing.getChildren().add(connectionLineCopy)); } ConnectionLine finalConnectionLine = connectionLine; Platform.runLater(finalConnectionLine::updateLocation); if (!newRoom.isRendered()) { // render the child renderQueue.add(newRoom); } } } // set the room count currentRoomCount = allRoomsAsList.size(); allRoomsAsListCopy = null; }); }
From source file:org.jsweet.transpiler.JSweetTranspiler.java
private void ts2js(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files) throws IOException { if (tsCompilationProcess != null && isTscWatchMode()) { return;/*from w w w .j a va2 s . co m*/ } if (isTscWatchMode()) { watchedFiles = files; } logger.debug("ts2js: " + Arrays.asList(files)); LinkedList<String> args = new LinkedList<>(); if (System.getProperty("os.name").startsWith("Windows")) { args.addAll(asList("--target", ecmaTargetVersion.name())); } else { args.addAll(asList("--target", ecmaTargetVersion.name())); } if (isUsingModules()) { if (ecmaTargetVersion.higherThan(EcmaScriptComplianceLevel.ES5)) { logger.warn("cannot use old fashionned modules with ES>5 target"); } else { args.add("--module"); args.add(moduleKind.toString()); } } if (ecmaTargetVersion.ordinal() >= EcmaScriptComplianceLevel.ES5.ordinal()) { args.add("--experimentalDecorators"); } if (isTscWatchMode()) { args.add("--watch"); } if (isPreserveSourceLineNumbers()) { args.add("--sourceMap"); } if (isGenerateDeclarations()) { args.add("--declaration"); } args.addAll(asList("--rootDir", tsOutputDir.getAbsolutePath())); // args.addAll(asList("--sourceRoot", tsOutputDir.toString())); if (jsOutputDir != null) { args.addAll(asList("--outDir", jsOutputDir.getAbsolutePath())); } File tscRootFile = getOrCreateTscRootFile(); if (tscRootFile.exists()) { args.add(relativizeTsFile(tscRootFile).toString()); } for (SourceFile sourceFile : files) { String filePath = relativizeTsFile(sourceFile.getTsFile()).toString(); if (!args.contains(filePath)) { args.add(filePath); } } // this may not be necessary because tsc seems to add required modules // automatically for (File f : auxiliaryTsModuleFiles) { String filePath = relativizeTsFile(f).toString(); if (!args.contains(filePath)) { args.add(filePath); } } for (File dir : tsDefDirs) { LinkedList<File> tsDefFiles = new LinkedList<>(); Util.addFiles(".d.ts", dir, tsDefFiles); for (File f : tsDefFiles) { args.add(relativizeTsFile(f).toString()); } } LinkedList<File> tsDefFiles = new LinkedList<>(); Util.addFiles(".d.ts", tsOutputDir, tsDefFiles); for (File f : tsDefFiles) { args.add(relativizeTsFile(f).toString()); } try { logger.info("launching tsc..."); runTSC(transpilationHandler, files, args.toArray(new String[0])); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.fop.layoutmgr.table.RowGroupLayoutManager.java
/** * Creates Knuth elements for a row group (see TableRowIterator.getNextRowGroup()). * @param context Active LayoutContext/*from w w w . ja va 2 s .c o m*/ * @param alignment alignment indicator * @param bodyType Indicates what kind of body is being processed (BODY, HEADER or FOOTER) * @param returnList List to received the generated elements */ private void createElementsForRowGroup(LayoutContext context, int alignment, int bodyType, LinkedList returnList) { log.debug("Handling row group with " + rowGroup.length + " rows..."); EffRow row; for (int rgi = 0; rgi < rowGroup.length; rgi++) { row = rowGroup[rgi]; for (Iterator iter = row.getGridUnits().iterator(); iter.hasNext();) { GridUnit gu = (GridUnit) iter.next(); if (gu.isPrimary()) { PrimaryGridUnit primary = gu.getPrimary(); // TODO a new LM must be created for every new static-content primary.createCellLM(); primary.getCellLM().setParent(tableLM); //Calculate width of cell int spanWidth = 0; Iterator colIter = tableLM.getTable().getColumns().listIterator(primary.getColIndex()); for (int i = 0, c = primary.getCell().getNumberColumnsSpanned(); i < c; i++) { spanWidth += ((TableColumn) colIter.next()).getColumnWidth().getValue(tableLM); } LayoutContext childLC = new LayoutContext(0); childLC.setStackLimitBP(context.getStackLimitBP()); //necessary? childLC.setRefIPD(spanWidth); //Get the element list for the cell contents List elems = primary.getCellLM().getNextKnuthElements(childLC, alignment); ElementListObserver.observe(elems, "table-cell", primary.getCell().getId()); primary.setElements(elems); } } } computeRowHeights(); List elements = tableStepper.getCombinedKnuthElementsForRowGroup(context, rowGroup, bodyType); returnList.addAll(elements); }
From source file:org.nuxeo.ecm.core.opencmis.impl.server.CMISQLQueryMaker.java
/** * {@inheritDoc}//from ww w . ja v a2 s . co m * <p> * The optional parameters must be passed: {@code params[0]} is the {@link NuxeoCmisService}, optional * {@code params[1]} is a type info map, optional {@code params[2]} is searchAllVersions (default * {@code Boolean.TRUE} for this method). */ @Override public Query buildQuery(SQLInfo sqlInfo, Model model, PathResolver pathResolver, String statement, QueryFilter queryFilter, Object... params) throws StorageException { database = sqlInfo.database; dialect = sqlInfo.dialect; this.model = model; NuxeoCmisService service = (NuxeoCmisService) params[0]; if (params.length > 1) { typeInfo = (Map<String, PropertyDefinition<?>>) params[1]; } if (params.length > 2) { Boolean searchAllVersions = (Boolean) params[2]; searchLatestVersion = Boolean.FALSE.equals(searchAllVersions); } TypeManagerImpl typeManager = service.repository.getTypeManager(); boolean addSystemColumns = true; // TODO hierTable = database.getTable(Model.HIER_TABLE_NAME); query = new QueryObject(typeManager); statement = applySecurityPolicyQueryTransformers(service, queryFilter.getPrincipal(), statement); CmisQueryWalker walker = null; try { walker = QueryUtil.getWalker(statement); walker.setDoFullTextParse(false); walker.query(query, new AnalyzingWalker()); } catch (RecognitionException e) { String msg; if (walker == null) { msg = e.getMessage(); } else { msg = "Line " + e.line + ":" + e.charPositionInLine + " " + walker.getErrorMessage(e, walker.getTokenNames()); } throw new QueryParseException(msg, e); } catch (QueryParseException e) { throw e; } catch (Exception e) { throw new QueryParseException(e.getMessage() + " for query: " + statement, e); } resolveQualifiers(); // now resolve column selectors to actual database columns for (CmisSelector sel : query.getSelectReferences()) { recordSelectSelector(sel); } for (CmisSelector sel : query.getJoinReferences()) { recordSelector(sel, JOIN); } for (CmisSelector sel : query.getWhereReferences()) { recordSelector(sel, WHERE); } for (SortSpec spec : query.getOrderBys()) { recordSelector(spec.getSelector(), ORDER_BY); } findVersionableQualifiers(); boolean distinct = false; // TODO extension addSystemColumns(addSystemColumns, distinct); /* * Find info about fragments needed. */ List<String> whereClauses = new LinkedList<String>(); List<Serializable> whereParams = new LinkedList<Serializable>(); /* * Walk joins. */ List<JoinSpec> joins = query.getJoins(); StringBuilder from = new StringBuilder(); List<Serializable> fromParams = new LinkedList<Serializable>(); for (int njoin = -1; njoin < joins.size(); njoin++) { JoinSpec join; boolean outerJoin; String alias; if (njoin == -1) { join = null; outerJoin = false; alias = query.getMainTypeAlias(); } else { join = joins.get(njoin); outerJoin = join.kind.equals("LEFT") || join.kind.equals("RIGHT"); alias = join.alias; } String typeQueryName = qualifierToType.get(alias); String qual = canonicalQualifier.get(alias); Table qualHierTable = getTable(hierTable, qual); // determine relevant primary types List<String> types = new ArrayList<String>(); TypeDefinition td = query.getTypeDefinitionFromQueryName(typeQueryName); if (td.getParentTypeId() != null) { // don't add abstract root types types.add(td.getId()); } LinkedList<TypeDefinitionContainer> typesTodo = new LinkedList<TypeDefinitionContainer>(); typesTodo.addAll(typeManager.getTypeDescendants(td.getId(), -1, Boolean.TRUE)); // recurse to get all subtypes TypeDefinitionContainer tc; while ((tc = typesTodo.poll()) != null) { types.add(tc.getTypeDefinition().getId()); typesTodo.addAll(tc.getChildren()); } if (types.isEmpty()) { // shoudn't happen types = Collections.singletonList("__NOSUCHTYPE__"); } // build clause StringBuilder qms = new StringBuilder(); for (int i = 0; i < types.size(); i++) { if (i != 0) { qms.append(", "); } qms.append("?"); } String primaryTypeClause = String.format("%s IN (%s)", qualHierTable.getColumn(model.MAIN_PRIMARY_TYPE_KEY).getFullQuotedName(), qms); // table this join is about Table table; if (join == null) { table = qualHierTable; } else { // find which table in onLeft/onRight refers to current // qualifier table = null; for (ColumnReference col : Arrays.asList(join.onLeft, join.onRight)) { if (alias.equals(col.getQualifier())) { // TODO match with canonical qualifier instead? table = ((Column) col.getInfo()).getTable(); break; } } if (table == null) { throw new QueryParseException("Bad query, qualifier not found: " + qual); } } String tableName; if (table.isAlias()) { tableName = table.getRealTable().getQuotedName() + " " + table.getQuotedName(); } else { tableName = table.getQuotedName(); } boolean isRelation = table.getKey().equals(REL_FRAGMENT_NAME); // join clause on requested columns boolean primaryTypeClauseDone = false; if (join == null) { from.append(tableName); } else { if (outerJoin) { from.append(" "); from.append(join.kind); } from.append(" JOIN "); from.append(tableName); from.append(" ON ("); from.append(((Column) join.onLeft.getInfo()).getFullQuotedName()); from.append(" = "); from.append(((Column) join.onRight.getInfo()).getFullQuotedName()); if (outerJoin && table.getKey().equals(Model.HIER_TABLE_NAME)) { // outer join, type check must be part of JOIN from.append(" AND "); from.append(primaryTypeClause); fromParams.addAll(types); primaryTypeClauseDone = true; } from.append(")"); } // join other fragments for qualifier String tableMainId = table.getColumn(Model.MAIN_KEY).getFullQuotedName(); for (Table t : allTables.get(qual).values()) { if (t.getKey().equals(table.getKey())) { // already done above continue; } String n; if (t.isAlias()) { n = t.getRealTable().getQuotedName() + " " + t.getQuotedName(); } else { n = t.getQuotedName(); } from.append(" LEFT JOIN "); from.append(n); from.append(" ON ("); from.append(t.getColumn(Model.MAIN_KEY).getFullQuotedName()); from.append(" = "); from.append(tableMainId); if (outerJoin && t.getKey().equals(Model.HIER_TABLE_NAME)) { // outer join, type check must be part of JOIN from.append(" AND "); from.append(primaryTypeClause); fromParams.addAll(types); primaryTypeClauseDone = true; } from.append(")"); } // primary type clause, if not included in a JOIN if (!primaryTypeClauseDone) { whereClauses.add(primaryTypeClause); whereParams.addAll(types); } // lifecycle not deleted filter if (skipDeleted) { ModelProperty propertyInfo = model.getPropertyInfo(model.MISC_LIFECYCLE_STATE_PROP); Column lscol = getTable(database.getTable(propertyInfo.fragmentName), qual) .getColumn(propertyInfo.fragmentKey); String lscolName = lscol.getFullQuotedName(); whereClauses.add(String.format("(%s <> ? OR %s IS NULL)", lscolName, lscolName)); whereParams.add(LifeCycleConstants.DELETED_STATE); } // searchAllVersions filter boolean versionable = versionableQualifiers.contains(qual); if (searchLatestVersion && versionable) { // add islatestversion = true Table ver = getTable(database.getTable(model.VERSION_TABLE_NAME), qual); Column latestvercol = ver.getColumn(model.VERSION_IS_LATEST_KEY); String latestvercolName = latestvercol.getFullQuotedName(); whereClauses.add(String.format("(%s = ?)", latestvercolName)); whereParams.add(Boolean.TRUE); } // security check boolean checkSecurity = !isRelation // && queryFilter != null && queryFilter.getPrincipals() != null; if (checkSecurity) { Serializable principals; Serializable permissions; if (dialect.supportsArrays()) { principals = queryFilter.getPrincipals(); permissions = queryFilter.getPermissions(); } else { principals = StringUtils.join(queryFilter.getPrincipals(), '|'); permissions = StringUtils.join(queryFilter.getPermissions(), '|'); } if (dialect.supportsReadAcl()) { /* optimized read acl */ String readAclTable; String readAclTableAlias; String aclrumTable; String aclrumTableAlias; if (joins.size() == 0) { readAclTable = Model.HIER_READ_ACL_TABLE_NAME; readAclTableAlias = readAclTable; aclrumTable = Model.ACLR_USER_MAP_TABLE_NAME; aclrumTableAlias = aclrumTable; } else { readAclTableAlias = "nxr" + (njoin + 1); readAclTable = Model.HIER_READ_ACL_TABLE_NAME + ' ' + readAclTableAlias; // TODO dialect aclrumTableAlias = "aclrum" + (njoin + 1); aclrumTable = Model.ACLR_USER_MAP_TABLE_NAME + ' ' + aclrumTableAlias; // TODO dialect } String readAclIdCol = readAclTableAlias + '.' + Model.HIER_READ_ACL_ID; String readAclAclIdCol = readAclTableAlias + '.' + Model.HIER_READ_ACL_ACL_ID; String aclrumAclIdCol = aclrumTableAlias + '.' + Model.ACLR_USER_MAP_ACL_ID; String aclrumUserIdCol = aclrumTableAlias + '.' + Model.ACLR_USER_MAP_USER_ID; // first join with hierarchy_read_acl if (outerJoin) { from.append(" "); from.append(join.kind); } from.append(String.format(" JOIN %s ON (%s = %s)", readAclTable, tableMainId, readAclIdCol)); // second join with aclr_user_map String securityCheck = dialect.getReadAclsCheckSql(aclrumUserIdCol); String joinOn = String.format("%s = %s", readAclAclIdCol, aclrumAclIdCol); if (outerJoin) { from.append(" "); from.append(join.kind); // outer join, security check must be part of JOIN joinOn = String.format("%s AND %s", joinOn, securityCheck); fromParams.add(principals); } else { // inner join, security check can go in WHERE clause whereClauses.add(securityCheck); whereParams.add(principals); } from.append(String.format(" JOIN %s ON (%s)", aclrumTable, joinOn)); } else { String securityCheck = dialect.getSecurityCheckSql(tableMainId); if (outerJoin) { securityCheck = String.format("(%s OR %s IS NULL)", securityCheck, tableMainId); } whereClauses.add(securityCheck); whereParams.add(principals); whereParams.add(permissions); } } } /* * WHERE clause. */ Tree whereNode = walker.getWherePredicateTree(); if (whereNode != null) { GeneratingWalker generator = new GeneratingWalker(); generator.walkPredicate(whereNode); whereClauses.add(generator.whereBuf.toString()); whereParams.addAll(generator.whereBufParams); // add JOINs for the external fulltext matches Collections.sort(generator.ftJoins); // implicit JOINs last // (PostgreSQL) for (org.nuxeo.ecm.core.storage.sql.jdbc.db.Join join : generator.ftJoins) { from.append(join.toSql(dialect)); if (join.tableParam != null) { fromParams.add(join.tableParam); } } } /* * SELECT clause. */ List<String> selectWhat = new ArrayList<String>(); List<Serializable> selectParams = new ArrayList<Serializable>(1); for (SqlColumn rc : realColumns) { selectWhat.add(rc.sql); } selectParams.addAll(realColumnsParams); CMISQLMapMaker mapMaker = new CMISQLMapMaker(realColumns, virtualColumns, service); String what = StringUtils.join(selectWhat, ", "); if (distinct) { what = "DISTINCT " + what; } /* * ORDER BY clause. */ List<String> orderbys = new LinkedList<String>(); for (SortSpec spec : query.getOrderBys()) { String orderby; CmisSelector sel = spec.getSelector(); if (sel instanceof ColumnReference) { Column column = (Column) sel.getInfo(); orderby = column.getFullQuotedName(); } else { orderby = fulltextMatchInfo.scoreAlias; } if (!spec.ascending) { orderby += " DESC"; } orderbys.add(orderby); } /* * Create the whole select. */ Select select = new Select(null); select.setWhat(what); select.setFrom(from.toString()); // TODO(fromParams); // TODO add before whereParams select.setWhere(StringUtils.join(whereClauses, " AND ")); select.setOrderBy(StringUtils.join(orderbys, ", ")); Query q = new Query(); q.selectInfo = new SQLInfoSelect(select.getStatement(), mapMaker); q.selectParams = selectParams; q.selectParams.addAll(fromParams); q.selectParams.addAll(whereParams); return q; }
From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java
/** * Launch simulation./* www . ja va 2s . c om*/ * * @param main * the main * @param args * the args */ private void launchSimulation(Class<? extends ComponentDefinition> main, String... args) { LinkedList<String> arguments = new LinkedList<String>(); String java = System.getProperty("java.home"); String sep = System.getProperty("file.separator"); String pathSep = System.getProperty("path.separator"); java += sep + "bin" + sep + "java"; if (System.getProperty("os.name").startsWith("Windows")) { arguments.add("\"" + java + "\""); } else { arguments.add(java); } arguments.add("-Xbootclasspath:" + directory + bootString() + pathSep + directory + "application"); arguments.add("-classpath"); arguments.add(directory + "application"); arguments.addAll(getJvmArgs(args)); arguments.add("-Dscenario=" + System.getProperty("scenario")); // add configuration properties for (Object key : System.getProperties().keySet()) { if (((String) key).contains("configuration")) arguments.add("-D" + key + "=" + System.getProperty((String) key)); } arguments.add(main.getName()); arguments.addAll(getApplicationArgs(args)); ProcessBuilder pb = new ProcessBuilder(arguments); pb.redirectErrorStream(true); saveSimulationCommandLine(arguments); try { Process process = pb.start(); BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; do { line = out.readLine(); if (line != null) { System.out.println(line); } } while (line != null); } catch (IOException e) { throw new RuntimeException("Cannot start simulation process", e); } }
From source file:fr.inria.soctrace.tools.importer.moca.core.MocaParser.java
/** * Recursively expand the hierarchy tree, following a top-down approach, by * creating new event producers by merging consecutive EP * * @param eventProdToMerge// w w w .j a va 2 s . c o m * the list of event producer that are consecutive * @param currentHierarchyDepth * the current depth we are building in the hierarchy tree * @param ppid * the parent id of the created nodes * @param dividingFactor * the factor into which the result will be divided * @return the list of created event producers */ private List<EventProducer> createHierarchy(List<EventProducer> eventProdToMerge, double currentHierarchyDepth, int ppid, int dividingFactor) { LinkedList<EventProducer> newEventProd = new LinkedList<EventProducer>(); int groupSize; // If first hierarchy depth if (currentHierarchyDepth == 0.0) // Do not split, just create a super producer representing the whole // group groupSize = eventProdToMerge.size(); else // Compute the size of a new group groupSize = eventProdToMerge.size() / dividingFactor; if (groupSize <= 1) return eventProdToMerge; int mergedProducers = 0; int i; // Compute new group of EP for (i = 0; i < eventProdToMerge.size() - groupSize; i = i + groupSize) { EventProducer newNode = createProducer( eventProdToMerge.get(i).getName() + "_" + (int) currentHierarchyDepth, ppid); newEventProd.add(newNode); LinkedList<EventProducer> newSubGroup = new LinkedList<EventProducer>(); // Update the parent of leaves event prod for (int j = i; j < i + groupSize; j++) { eventProdToMerge.get(j).setParentId(newNode.getId()); newSubGroup.add(eventProdToMerge.get(j)); } // Keep merging? if (currentHierarchyDepth + 1 < maxHierarchyDepth && newSubGroup.size() >= dividingFactor && newSubGroup.size() > 1) { newEventProd.addAll( createHierarchy(newSubGroup, currentHierarchyDepth + 1, newNode.getId(), dividingFactor)); } else { newEventProd.addAll(newSubGroup); } mergedProducers = i + groupSize; } int remainingEP = eventProdToMerge.size() - mergedProducers; if (remainingEP == 1) { newEventProd.add(eventProdToMerge.get(eventProdToMerge.size() - 1)); } else // Check if some producer remains if (mergedProducers < eventProdToMerge.size()) { EventProducer newNode = createProducer( eventProdToMerge.get(i).getName() + "_" + (int) currentHierarchyDepth, ppid); newEventProd.add(newNode); LinkedList<EventProducer> newSubGroup = new LinkedList<EventProducer>(); for (i = mergedProducers; i < eventProdToMerge.size(); i++) { if (currentHierarchyDepth > 0.0 || newNode.getName().matches("^\\d+$") || newNode.getName() .compareTo(eventProdToMerge.get(i).getName() + "_" + (int) currentHierarchyDepth) != 0) { // Do not copy data structure at depth 0 eventProdToMerge.get(i).setParentId(newNode.getId()); newSubGroup.add(eventProdToMerge.get(i)); } } if (currentHierarchyDepth + 1 < maxHierarchyDepth && newSubGroup.size() >= dividingFactor && newSubGroup.size() > 1 && dividingFactor > 1) { newEventProd.addAll( createHierarchy(newSubGroup, currentHierarchyDepth + 1, newNode.getId(), dividingFactor)); } else { newEventProd.addAll(newSubGroup); } } logger.debug(currentHierarchyDepth + ", " + newEventProd.size()); return newEventProd; }
From source file:org.alfresco.repo.workflow.activiti.ActivitiWorkflowEngine.java
@Override public List<WorkflowInstance> getWorkflows(WorkflowInstanceQuery workflowInstanceQuery, int maxItems, int skipCount) { LinkedList<WorkflowInstance> results = new LinkedList<WorkflowInstance>(); if (Boolean.FALSE.equals(workflowInstanceQuery.getActive()) == false) { //Add active. results.addAll(getWorkflowsInternal(workflowInstanceQuery, true, maxItems, skipCount)); }//from w ww .j a va 2 s. com if (Boolean.TRUE.equals(workflowInstanceQuery.getActive()) == false) { //Add complete results.addAll(getWorkflowsInternal(workflowInstanceQuery, false, maxItems, skipCount)); } return results; }